Track the Earliest Single-Occurrence Integer in a Stream
Data Structure DesignAuto-graded · 14 test casesLast updated
Design a structure that efficiently identifies the first integer appearing exactly once in a dynamic sequence of integers.
Build a structure that processes a stream of integers and identifies which integer appeared first among those that have appeared exactly once.
Your structure will be initialized with a starting sequence of integers, then support two operations:
- Query the earliest single-occurrence integer: return the first integer (by arrival order) that has appeared exactly once in the entire stream seen so far.
- Append a new integer: add another integer to the stream.
If no integer has appeared exactly once, return -1.
The judge will drive your structure through a single function that replays a sequence of operations:
def track_unique_stream(nums: List[int], operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
Parameters:
nums: the initial sequence of integersoperations: a list of operation names, each either"show_first_unique"or"add"arguments: parallel list of argument lists;[]for query operations,[value]for add operations
Return: A list of results, one per operation:
- For
"show_first_unique": the earliest integer with count exactly 1, or-1if none exists - For
"add":None
Constraints:
- 0 ≤ len(nums) ≤ 10⁵
- 1 ≤ len(operations) ≤ 10⁵
- -10⁹ ≤ integer values ≤ 10⁹
- Each operation in
operationsis either"show_first_unique"or"add" arguments[i]is[]for query operations and[value]for add operations
Examples
Example 1
Input: track_unique_stream([2, 3, 5], ['show_first_unique', 'add', 'show_first_unique', 'add', 'show_first_unique', 'add', 'show_first_unique'], [[], [5], [], [2], [], [3], []])
Output: [2, None, 2, None, 3, None, -1]
Example 2
Input: track_unique_stream([7, 7, 7, 7, 7, 7], ['show_first_unique', 'add', 'show_first_unique'], [[], [8], []])
Output: [-1, None, 8]
Hints
Hint 1
How can you quickly determine if an integer has appeared more than once?
Hint 2
If you keep integers in arrival order, how do you avoid searching through the entire list to find the first single-occurrence integer?
Hint 3
Consider lazy removal: instead of immediately deleting duplicate entries from your ordered collection, wait until they reach the front and discard them then.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need to quickly find the earliest-arriving integer whose occurrence count is exactly one, and we need to support updates efficiently.
Combine two data structures:
- Frequency map: a hash table tracking how many times each integer has appeared
- Arrival queue: a queue holding integers in the order they arrived
The clever technique is deferred cleanup. When an integer becomes a duplicate, we don't immediately search through the queue to remove it. Instead, we leave it in place. Later, when queried for the first single-occurrence integer, we remove stale entries from the front of the queue until we find an integer with count exactly 1.
Why this works: Once an integer's count exceeds 1, it can never drop back to 1 (we only add, never remove). So any queue entry with count ≠ 1 is permanently invalid and can be discarded. Every integer with count exactly 1 is still somewhere in the queue, in its original arrival position.
When we query, we clean up the front until we find a valid answer or exhaust the queue. The first entry that survives cleanup is the earliest-arriving single-occurrence integer.
Correctness
- Frequency counts are monotonically increasing
- An integer with count exactly 1 appears once in the queue, at its arrival position
- Integers with count > 1 may appear multiple times in the queue, but all copies will be discarded during cleanup
- After cleanup, the front of the queue holds the correct answer
Complexity
Let n = initial sequence length, m = number of operations.
Time:
- Initialization: O(n) to build the frequency map and queue
- Add operation: O(1)
- Query operation: O(1) amortized — each integer enters the queue once and is removed at most once, so total cleanup work across all queries is O(n + m)
- Overall: O(n + m)
Space: O(n + m) for the frequency map, queue, and results list
Alternative Approach
For worst-case O(1) per query (instead of amortized), maintain an ordered hash map or linked hash set of currently-unique integers. Add an integer on its first appearance, remove it on its second. The first key is always the answer. This requires more careful bookkeeping but guarantees constant time per operation.
from collections import Counter, deque
from typing import List, Optional
def track_unique_stream(nums: List[int], operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
frequency = Counter(nums)
arrival_queue = deque(nums)
results = []
def find_first_unique():
while arrival_queue and frequency[arrival_queue[0]] != 1:
arrival_queue.popleft()
return arrival_queue[0] if arrival_queue else -1
for op, args in zip(operations, arguments):
if op == "show_first_unique":
results.append(find_first_unique())
elif op == "add":
val = args[0]
frequency[val] += 1
arrival_queue.append(val)
results.append(None)
return results