Design Phone Directory - Problem
Design a phone directory that initially has maxNumbers empty slots that can store numbers. The directory should support storing numbers, checking if a certain slot is empty, and emptying a given slot.
Implement the PhoneDirectory class:
PhoneDirectory(int maxNumbers)- Initializes the phone directory with the number of available slotsmaxNumbersint get()- Provides a number that is not assigned to anyone. Returns-1if no number is availablebool check(int number)- Returnstrueif the slotnumberis available andfalseotherwisevoid release(int number)- Recycles or releases the slotnumber
All operations should be performed efficiently to handle multiple queries.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["PhoneDirectory", "get", "check", "get", "check", "release", "check"], parameters = [[3], [], [2], [], [2], [2], [2]]
›
Output:
[null, 0, true, 1, false, null, true]
💡 Note:
Initialize directory with 3 slots. get() returns 0 (first available). check(2) returns true (slot 2 available). get() returns 1. check(2) returns false (still available). release(2) has no effect. check(2) returns true.
Example 2 — Full Directory
$
Input:
operations = ["PhoneDirectory", "get", "get", "get"], parameters = [[2], [], [], []]
›
Output:
[null, 0, 1, -1]
💡 Note:
Directory with 2 slots. First get() returns 0, second returns 1, third returns -1 (no slots available).
Example 3 — Release and Reuse
$
Input:
operations = ["PhoneDirectory", "get", "get", "release", "get"], parameters = [[2], [], [], [0], []]
›
Output:
[null, 0, 1, null, 0]
💡 Note:
Get slots 0 and 1, release slot 0, then get() returns the released slot 0.
Constraints
- 1 ≤ maxNumbers ≤ 104
- 0 ≤ number < maxNumbers
- At most 2 × 104 calls will be made to get, check, and release
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Create directory with maxNumbers available slots
2
Operations
get(), check(), release() operations on slots
3
Result
Efficient slot management with O(1) operations
Key Takeaway
🎯 Key Insight: Use a queue to store available slot numbers for O(1) get operations while maintaining a boolean array for quick status checks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code