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 slots maxNumbers
  • int get() - Provides a number that is not assigned to anyone. Returns -1 if no number is available
  • bool check(int number) - Returns true if the slot number is available and false otherwise
  • void release(int number) - Recycles or releases the slot number

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
Phone Directory: Efficient Slot ManagementPhone Directory (maxNumbers = 3):Slot 0Slot 1Slot 2AvailableAvailableAvailableOperations:• get() → Returns available slot number• check(number) → Is slot available?• release(number) → Free up slotAfter get() operation:Slot 0Slot 1Slot 2UsedAvailableAvailableReturned: 0
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
18.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen