Parcel Locker Manager with History Tracking
Data Structure DesignAuto-graded · 15 test casesLast updated
Build a locker allocation system that assigns the smallest free locker, validates pickups, and remembers the last package stored in each locker.
You are building a parcel locker controller for a delivery service. The system manages n lockers numbered from 1 to n.
Write a function that simulates a sequence of operations on the locker controller:
def run_locker_operations(n: int, operations: List[str], arguments: List[List]) -> List:
The function receives:
n: the total number of lockers (numbered1throughn)operations: a list of operation namesarguments: a parallel list wherearguments[i]contains the parameters foroperations[i]
Each operation produces one output value, and the function returns the list of all outputs in order.
Operations
"store" with argument [package_id]:
- Assign the smallest available locker number to hold
package_id - Return the assigned locker number
- If
package_idis already stored in some locker, or if all lockers are full, return-1instead
"pickup" with arguments [locker_id, package_id]:
- Release locker
locker_idif it is currently occupied bypackage_id - Return
Trueif the pickup succeeds and the locker is released - Return
Falseiflocker_idis out of range, the locker is empty, or the stored package does not matchpackage_id - A released locker becomes immediately available for future store operations
"get_last_stored" with argument [locker_id]:
- Return the
package_idof the most recent package that was stored inlocker_id, even if that locker is now empty - Return
Noneiflocker_idis out of range or if no package has ever been stored in that locker
Constraints
1 ≤ n ≤ 100,0001 ≤ len(package_id) ≤ 32, alphanumeric characters only1 ≤ len(operations) ≤ 200,000- Each operation name is one of
"store","pickup", or"get_last_stored" locker_idvalues in arguments may be out of range or invalid types
Examples
Example 1
Input: run_locker_operations(3, ['store', 'store', 'store', 'pickup', 'pickup', 'store', 'get_last_stored', 'pickup', 'get_last_stored', 'get_last_stored'], [['PKG-A'], ['PKG-B'], ['PKG-A'], [1, 'PKG-A'], [1, 'PKG-A'], ['PKG-C'], [1], [1, 'PKG-C'], [1], [3]])
Output: [1, 2, -1, True, False, 1, 'PKG-C', True, 'PKG-C', None]
Hints
Hint 1
Use a min-heap to efficiently track and retrieve the smallest available locker number.
Hint 2
Maintain separate data structures for current occupancy (which packages are in lockers right now) and historical data (what was the last package in each locker).
Hint 3
Track a reverse mapping from package IDs to locker numbers so you can quickly check if a package is already stored somewhere.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge requires juggling three distinct responsibilities: efficiently finding the smallest free locker, preventing duplicate storage of the same package, and remembering historical data that survives pickups. Each responsibility maps naturally to its own data structure.
1. Finding the smallest available locker
A min-heap containing all free locker numbers lets us extract the minimum in O(log n) time. Initially the heap contains 1, 2, ..., n. When a store operation succeeds, we pop the minimum. When a pickup succeeds, we push the released locker back into the heap.
2. Tracking current state and preventing duplicates
We maintain:
- A
currentarray wherecurrent[locker_id]holds the package currently stored in that locker, orNoneif empty - A
package_locationsdictionary mapping each package ID to its current locker number
The dictionary enables O(1) duplicate detection: before storing a package, we check if it already exists in package_locations. A package that was previously picked up will no longer be in this dictionary, so it can be stored again.
3. Preserving history
A last_stored array records the most recent package stored in each locker. This array is updated only on successful store operations and is never cleared during pickup. This persistence is exactly what get_last_stored requires: it returns the value regardless of whether the locker is currently occupied.
Operation logic
-
store: Check if the package is already stored or if the heap is empty. If either condition holds, return
-1. Otherwise, pop the minimum locker from the heap, update all three data structures (current,last_stored,package_locations), and return the locker number. -
pickup: Validate that
locker_idis in range and thatcurrent[locker_id]equalspackage_id. The equality check handles both empty lockers (whereNone != package_id) and mismatched packages in one comparison. If valid, clearcurrent[locker_id], remove the entry frompackage_locations, push the locker back to the heap, and returnTrue. Otherwise returnFalse. -
get_last_stored: Validate
locker_idand returnlast_stored[locker_id]if valid, orNoneotherwise.
Why It Works
The heap invariant guarantees that heappop always returns the smallest free locker. The package_locations dictionary is synchronized with the current array: entries are added on store and removed on pickup, so it accurately reflects which packages are currently in the system. The last_stored array is write-only during store operations, ensuring that historical data persists even after a locker is emptied.
Complexity
- Time: O(n) to initialize the heap and arrays, then O(log n) per store or pickup operation (heap operations), and O(1) per
get_last_stored. With up to 200,000 operations, the total is O(n + q log n) where q is the number of operations. - Space: O(n) for the heap and arrays, plus O(min(n, q)) for the
package_locationsdictionary.
import heapq
from typing import List
def run_locker_operations(n, operations, arguments):
available = list(range(1, n + 1))
heapq.heapify(available)
current = [None] * (n + 1)
last_stored = [None] * (n + 1)
package_locations = {}
result = []
for operation, args in zip(operations, arguments):
if operation == "store":
package_id = args[0]
if package_id in package_locations or not available:
result.append(-1)
else:
locker_id = heapq.heappop(available)
current[locker_id] = package_id
last_stored[locker_id] = package_id
package_locations[package_id] = locker_id
result.append(locker_id)
elif operation == "pickup":
locker_id, package_id = args
if (not isinstance(locker_id, int) or locker_id < 1 or locker_id > n or
current[locker_id] != package_id):
result.append(False)
else:
current[locker_id] = None
del package_locations[package_id]
heapq.heappush(available, locker_id)
result.append(True)
elif operation == "get_last_stored":
locker_id = args[0]
if not isinstance(locker_id, int) or locker_id < 1 or locker_id > n:
result.append(None)
else:
result.append(last_stored[locker_id])
return result