Python coding

Set with O(1) removal and indexing

Write a class IndexedSet: a set of integers that keeps its values in slots numbered 0 to size - 1, so picking a uniformly random member would be just at(random index). Every operation must run in O(1) on average.

  • insert(x): if x is absent, store it in the next free slot (index size) and return True; otherwise return False.
  • remove(x): if x is present, delete it, move the value from the last slot into the slot it left, and return True; otherwise return False.
  • contains(x) returns whether x is stored.
  • at(i) returns the value in slot i; i is always valid.
  • size() returns how many values are stored.

The tests call the provided run_set(ops): it applies each operation in order and returns the list of results.

  • run_set([["insert",4],["insert",9],["insert",4],["contains",9],["size"],["at",0],["at",1]]) → [true,true,false,true,2,4,9]
  • run_set([["insert",1],["insert",2],["insert",3],["remove",1],["at",0],["at",1],["size"],["contains",1]]) → [true,true,true,true,3,2,2,false]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A list gives O(1) access by slot but O(n) search; a hash map gives O(1) search but has no slots. Use both, each covering the other's weak spot.

Hint 2

Keep values (slot → value) and slot (value → slot). To remove, look up the slot, copy the last value into it, update that value's slot, then pop the end of the list.

Hint 3

The trap: when the removed value sits in the last slot itself, updating the moved value's slot after deleting the entry re-adds it. Delete the map entry last.

Solution and why it works
pythonO(1) average per operation · O(n)
# --- your code ---
class IndexedSet:
    def __init__(self):
        self.values = []                 # slot -> value
        self.slot = {}                   # value -> slot

    def insert(self, x: int) -> bool:
        if x in self.slot:
            return False
        self.slot[x] = len(self.values)
        self.values.append(x)
        return True

    def remove(self, x: int) -> bool:
        if x not in self.slot:
            return False
        i, last = self.slot[x], self.values[-1]
        self.values[i], self.slot[last] = last, i   # the last value fills the gap
        self.values.pop()
        del self.slot[x]                 # after the move: x may be the last value
        return True

    def contains(self, x: int) -> bool:
        return x in self.slot

    def at(self, i: int) -> int:
        return self.values[i]

    def size(self) -> int:
        return len(self.values)


# --- provided: do not edit ---
def run_set(ops: list[list]) -> list:
    s = IndexedSet()
    return [getattr(s, name)(*args) for name, *args in ops]

A list indexes in O(1) but deletes from the middle in O(n); a hash map deletes in O(1) but has no positions. Storing each value's slot in the map joins them: removal overwrites the freed slot with the last value, fixes that value's slot in the map and pops the tail, all O(1). Order is not preserved, which a set never promised. The trap is removing the value in the last slot: delete its map entry after the move, or the move re-inserts it.