Design Phone Directory - Problem
Design Phone Directory
You're tasked with designing a phone directory system that manages available phone number slots efficiently. The directory starts with a fixed number of empty slots that can store phone numbers.
Your system needs to support three key operations:
get()- Assign an available phone number slot to a user. Returns the number, or-1if no slots are availablecheck(number)- Verify if a specific slot number is currently availablerelease(number)- Free up a previously assigned slot so it can be reused
Example: If you initialize the directory with 3 slots, numbers 0, 1, and 2 are initially available. After calling get(), one number becomes assigned. You can later release() that number to make it available again.
This problem tests your ability to design efficient data structures for resource management - a common requirement in system design interviews.
Input & Output
example_1.py โ Basic Operations
$
Input:
["PhoneDirectory", "get", "check", "get", "check", "release", "check"]
[[3], [], [2], [], [2], [2], [2]]
โบ
Output:
[null, 0, true, 1, false, null, true]
๐ก Note:
Initialize with 3 slots (0,1,2). get() returns 0 and marks it unavailable. check(2) returns true as it's still available. get() returns 1. check(2) returns false since 2 is assigned. release(2) frees slot 2. check(2) returns true again.
example_2.py โ All Slots Exhausted
$
Input:
["PhoneDirectory", "get", "get", "get", "get"]
[[2], [], [], [], []]
โบ
Output:
[null, 0, 1, -1, -1]
๐ก Note:
Initialize with 2 slots. First get() returns 0, second returns 1. Third and fourth get() return -1 since all slots are exhausted.
example_3.py โ Release and Reuse
$
Input:
["PhoneDirectory", "get", "get", "release", "get", "release", "get"]
[[1], [], [], [0], [], [0], []]
โบ
Output:
[null, 0, -1, null, 0, null, -1]
๐ก Note:
Initialize with 1 slot. get() returns 0. Second get() returns -1. release(0) frees slot 0. get() can now return 0 again. After another release(0) and get(), we're back to no available slots.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
All phone numbers 0 to maxNumbers-1 are available
2
Assignment
get() removes and returns the next available number
3
Availability Check
check() verifies if a specific number is available
4
Release
release() returns a number to the available pool
Key Takeaway
๐ฏ Key Insight: Combining queue for O(1) assignment with set for O(1) lookup creates an optimal resource management system
Time & Space Complexity
Time Complexity
O(1)
Queue operations and set lookups are all O(1)
โ Linear Growth
Space Complexity
O(n)
Queue and set each store up to n numbers
โก Linearithmic Space
Constraints
- 1 โค maxNumbers โค 104
- 0 โค number < maxNumbers
- At most 2 ร 104 calls will be made to get, check, and release
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code