Short code, low memory but slow

  • 0

    Having seen many solutions use a list and a dictionary I decided to try just using a set.
    All works more efficiently apart from the random.sample() method which is incredibly slow in Python compared to using random.randint() to choose an index from a list.
    I also tried pop() to get a random item then add it back, but that only chooses an arbitrary item which is not random.
    So at least I learned something new.

    class RandomizedSet(object):
        def __init__(self):
   = set()
        def insert(self, val):
            if val in
                return False
            return True
        def remove(self, val):
            if val in
                return True
            return False
        def getRandom(self):
            return random.sample(, 1)[0]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.