KatInterview

Track the Earliest Single-Occurrence Integer in a Stream

Data Structure DesignAuto-graded · 14 test cases
HardAuto-gradedData Structure Designqueuehash-tabledata-structure-design

Last 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:

  1. 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.
  2. 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 integers
  • operations: 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 -1 if none exists
  • For "add": None

Constraints:

  • 0 ≤ len(nums) ≤ 10⁵
  • 1 ≤ len(operations) ≤ 10⁵
  • -10⁹ ≤ integer values ≤ 10⁹
  • Each operation in operations is 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.