Similar Problems

Similar Problems not available

Design Phone Directory - Leetcode Solution

Companies:

LeetCode:  Design Phone Directory Leetcode Solution

Difficulty: Medium

Topics: linked-list design array hash-table  

The Phone Directory problem on LeetCode asks us to design a phone directory with the following functionalities:

  1. get() function: Returns a phone number that is not currently assigned to anyone. If no such number is available, it returns -1.
  2. check(number) function: Returns true if the given phone number is available and false if it is already assigned to someone.
  3. release(number) function: Frees up the phone number so that it can be reassigned.

To solve this problem, we can use a set to keep track of all the available phone numbers and a queue to store the released phone numbers. Whenever the get() function is called, we pop a phone number from the set of available phone numbers. If the set is empty, we return -1. When the release() function is called, we add the released phone number to the queue. When the check() function is called, we can check if the given phone number is in the set of available phone numbers or not.

Here's the implementation in Python:

class PhoneDirectory:
    def __init__(self, maxNumbers: int):
        self.available = set(range(maxNumbers))
        self.released = []

    def get(self) -> int:
        if self.available:
            num = self.available.pop()
        elif self.released:
            num = self.released.pop(0)
        else:
            return -1

        return num

    def check(self, number: int) -> bool:
        return number in self.available

    def release(self, number: int) -> None:
        if number not in self.available:
            self.available.add(number)
            self.released.append(number)

This solution has a time complexity of O(1) for all three functions and a space complexity of O(n), where n is the maximum number of phone numbers.

Design Phone Directory Solution Code

1