Idea: since phone numbers cannot have duplicates, set is obviously a good option here. check(), release() and get() can be easily done.
Here is the code:
class PhoneDirectory(object): def __init__(self, maxNumbers): # generate number from 0 to maxNumbers # and add them into the set self.s = set([i for i in range(maxNumbers)]) def get(self): # if set is empty, that means no available number if len(self.s) == 0: return -1 # set.pop() removes an arbitrary element from the set and returns it return self.s.pop() def check(self, number): # check if the number is still available (in the set) return number in self.s def release(self, number): # add the number into the set # this is robust since even though number is available already, # it won't create a duplicate self.s.add(number)
Runtime 115ms. Beats 95.77%