Skip to content

Wrong complexity for Create Insert Delete GetRandom O(1) problem #15

@jakobkogler

Description

@jakobkogler

The problem statement says, that all three operations should take O(1) time on average.
However the current implementation is only O(n) on average. It might have passed the Leetcode submission, as their tests are usually not strong. But the code logic is technically still wrong...

Both the C++ and the Python versions are affected:

/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if(ss.find(val) == ss.end())
return false;
ss.erase(val);
for (int i = 0;i < a.size();i++) {
if(a[i] == val) {
a[i] = a[a.size() - 1];
a.pop_back();
break;
}
}
return true;
}

def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val not in self.ss:
return False
self.ss.discard(val)
for i, ai in enumerate(self.a):
if ai == val:
self.a[i] = self.a[-1]
self.a.pop()
break
return True

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions