Earliest Non-Repeating ID in a Live Feed Replay
Data Structure DesignAuto-graded · 22 test casesLast updated
Replay a sequence of operations on a stream of integer IDs and report, at each query, the earliest-arriving ID seen exactly once, using a hash map plus an ordered queue.
Earliest Non-Repeating ID in a Live Feed Replay
A service receives a feed of positive integer IDs, one at a time. At any moment you may be asked for the earliest non-repeating ID: among all IDs that have appeared exactly once so far, the one whose arrival came first. If no ID has appeared exactly once, the answer is -1.
Rather than building a class, you implement one function that replays a recorded list of operations and returns the outputs produced by each of them.
Operations
Each operation is a name paired with an argument list at the same position:
| Operation name | Arguments | Effect | Output |
|---|---|---|---|
"RestaurantTracker" | [] | Resets the tracker to a fresh, empty state, discarding everything seen earlier. | None |
"add_restaurant" | [id] | Records the arrival of id at the end of the feed. | None |
"get_first_unique" | [] | Reports the earliest-arriving ID that has appeared exactly once so far, or -1 if there is none. | that ID or -1 |
Any other operation name must raise a ValueError.
Task
Given operations and arguments (parallel lists of equal length), process the operations from left to right and return a list with exactly one output per operation, in the same order.
Rules
- "Earliest" refers to the position of an ID's first (and only) arrival in the feed.
- An ID that has appeared two or more times is never considered unique, even if later arrivals are of other IDs.
- A query on an empty feed returns
-1. - A query does not change the feed; repeating it without new arrivals yields the same answer.
- After a reset operation, IDs from before the reset have no influence on later answers.
Constraints
1 <= id <= 10^6- The total number of
add_restaurantoperations does not exceed10^5. len(operations) == len(arguments)- Aim for amortized
O(1)time per operation.
Examples
Example 1
Input: first_unique_replay(['RestaurantTracker', 'add_restaurant', 'add_restaurant', 'add_restaurant', 'get_first_unique', 'add_restaurant', 'get_first_unique'], [[], [101], [202], [101], [], [303], []])
Output: [None, None, None, None, 202, None, 202]
Example 2
Input: first_unique_replay(['RestaurantTracker', 'get_first_unique'], [[], []])
Output: [None, -1]
Example 3
Input: first_unique_replay(['RestaurantTracker', 'add_restaurant', 'add_restaurant', 'add_restaurant', 'get_first_unique', 'add_restaurant', 'get_first_unique', 'add_restaurant', 'get_first_unique'], [[], [7], [7], [8], [], [8], [], [9], []])
Output: [None, None, None, None, 8, None, -1, None, 9]
Hints
Hint 1
Keeping only a frequency map makes each query require a scan over all IDs in arrival order. You also need to remember arrival order somewhere.
Hint 2
Put an ID into a queue only at the moment its count becomes 1. Later duplicates do not need to touch the queue at all.
Hint 3
When answering a query, discard entries from the front of the queue whose count is no longer 1. Counts never decrease, so a discarded ID can never become unique again, and each ID is pushed and popped at most once.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain two structures:
- A hash map
countsfrom ID to the number of times it has arrived. - A queue
candidatesholding IDs in order of first arrival.
An ID is appended to the queue only when its count goes from 0 to 1. When it later becomes a duplicate we do not remove it from the middle of the queue. Instead, a query uses lazy deletion: it pops from the front while the front ID's count is not 1, then reports the front ID, or -1 if the queue is empty.
A reset operation clears both structures. Unknown operation names raise ValueError.
Why it is correct
- Each ID is enqueued at most once, and its position reflects its first arrival, since counts only grow and the enqueue happens only at count 1.
- Counts never decrease, so once an ID's count exceeds 1 it can never be unique again. Dropping it from the queue is therefore safe.
- After stale entries are popped, the front has count 1, and every entry ahead of it was stale. Every unique ID is in the queue, so the front is the earliest unique ID.
- Stale entries buried in the middle are harmless; they are removed if and when they reach the front.
Complexity
add: O(1).get: amortized O(1). Each ID is pushed once and popped at most once, so total popping work over all queries is bounded by the number of adds.- Overall O(n) time for n operations, and O(k) space for k distinct IDs.
Reference solution
from collections import deque
from typing import List, Optional
def first_unique_replay(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
counts = {}
candidates = deque()
results = []
for operation, args in zip(operations, arguments):
if operation == "RestaurantTracker":
counts.clear()
candidates.clear()
results.append(None)
elif operation == "add_restaurant":
item = args[0]
counts[item] = counts.get(item, 0) + 1
if counts[item] == 1:
candidates.append(item)
results.append(None)
elif operation == "get_first_unique":
while candidates and counts[candidates[0]] != 1:
candidates.popleft()
results.append(candidates[0] if candidates else -1)
else:
raise ValueError("unknown operation")
return results