The First Unique Number interview question is a design task for a data stream. You need to implement a class that can:
add(value): Add a new number to the stream.showFirstUnique(): Return the value of the first number that has been added to the stream exactly once. If no unique number exists, return -1.Uber and Meta ask this to test your ability to maintain Ordered Uniqueness. It requires a combination of data structures to achieve for both operations. It evaluations your knowledge of Linked List interview patterns and Hash Table interview patterns working together (similar to an LRU cache).
This problem is best solved using a Hash Map + Doubly-Linked List or a Hash Map + Queue.
Map<Integer, Node>: Maps a value to its node in a doubly-linked list.Set<Integer> isDuplicate: Tracks numbers that have appeared more than once.add:
isDuplicate, ignore.isDuplicate.showFirstUnique: Return the head of the linked list.add(2), add(3), add(2)
add(2): Unique: [2].add(3): Unique: [2, 3].add(2): 2 is now a duplicate. Remove from unique. Unique: [3].showFirstUnique(): Returns 3.add(3): 3 is now a duplicate. Unique: [].showFirstUnique(): Returns -1.showFirstUnique (), which is too slow for frequent calls.showFirstUnique is called (Lazy Deletion). While valid, it can use more memory than the linked list approach.Practice combining data structures. Problems that require "First seen," "Most recent," or "Unique in order" almost always use a Map combined with a sequential structure like a Queue or Linked List.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Design an Ordered Stream | Easy | Solve | |
| Moving Average from Data Stream | Easy | Solve | |
| Design Front Middle Back Queue | Medium | Solve | |
| Detect Squares | Medium | Solve | |
| Design Snake Game | Medium | Solve |