Practice/Apple/Leetcode 379. Design Phone Directory
Leetcode 379. Design Phone Directory
CodingMust
Problem
Design and implement a resource pool manager that handles a fixed collection of numbered resources (from 0 to maxResources-1). Your implementation should efficiently support the following operations:
- Allocate: Assign and return an available resource identifier
- Check: Determine whether a specific resource is currently available
- Release: Free a previously allocated resource, returning it to the available pool
The system must track which resources are currently in use and which are available for allocation. When a resource is released, it should become available for future allocation requests.
Requirements
- Implement a constructor that initializes the pool with a specified maximum number of resources
- The
get() method should return an available resource ID, or -1 if none are available
- The
check(resourceId) method should return true if the resource is available, false otherwise
- The
release(resourceId) method should mark a resource as available for future use
- All operations should ideally run in O(1) time complexity
- Handle edge cases like releasing already-available resources or invalid resource IDs gracefully
Constraints
- 1 ≤ maxResources ≤ 10^4
- 0 ≤ resourceId < maxResources
- At most 2 × 10^4 total calls will be made to get, check, and release
- Resource IDs are integers in the range [0, maxResources-1]
Examples
Example 1:
`
Operations: Initialize(3), get(), get(), check(0), release(0), check(0), get()
Output: [null, 0, 1, false, null, true, 0]
Explanation:
- ResourcePool(3): Initialize with resources 0, 1, 2
- get(): Returns 0 (first available resource)
- get(): Returns 1 (next available resource)
- check(0): Returns false (resource 0 is allocated)
- release(0): Release resource 0 back to the pool
- check(0): Returns true (resource 0 is now available)
- get(): Returns 0 (resource 0 is available again)
`
Example 2:
`
Operations: Initialize(2), get(), get(), get()
Output: [null, 0, 1, -1]
Explanation:
- ResourcePool(2): Initialize with resources 0, 1
- get(): Returns 0
- get(): Returns 1
- get(): Returns -1 (no more resources available)
`
Example 3:
`
Operations: Initialize(5), get(), get(), release(0), get(), check(0)
Output: [null, 0, 1, null, 0, false]
Explanation:
- After releasing resource 0, it becomes available for reallocation
- The next get() returns resource 0 again
- Checking resource 0 shows it's now allocated (unavailable)
`