First Unique Number - Problem

You have a queue of integers, and you need to retrieve the first unique integer in the queue.

Implement the FirstUnique class:

  • FirstUnique(int[] nums) - Initializes the object with the numbers in the queue.
  • int showFirstUnique() - Returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.
  • void add(int value) - Inserts value to the queue.

Input & Output

Example 1 — Basic Operations
$ Input: FirstUnique firstUnique = new FirstUnique([2,3,5]); firstUnique.showFirstUnique(); firstUnique.add(5); firstUnique.showFirstUnique();
Output: 2, 2
💡 Note: Initially first unique is 2. After adding 5 (which already exists), 2 is still the first unique.
Example 2 — Remove First Unique
$ Input: FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]); firstUnique.showFirstUnique(); firstUnique.add(7); firstUnique.add(3); firstUnique.showFirstUnique();
Output: -1, 3
💡 Note: All 7s are duplicates so first call returns -1. After adding 3, it becomes the first unique.
Example 3 — Multiple Unique Elements
$ Input: FirstUnique firstUnique = new FirstUnique([809]); firstUnique.showFirstUnique(); firstUnique.add(809); firstUnique.showFirstUnique();
Output: 809, -1
💡 Note: Initially 809 is unique. After adding another 809, no unique elements remain.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 108
  • 1 ≤ value ≤ 108
  • At most 50000 calls will be made to showFirstUnique and add.

Visualization

Tap to expand
First Unique Number ProblemInput Stream235Frequency Tracking2: count=1 ✓3: count=1 ✓5: count=1 ✓showFirstUnique() → scan for first element with count=1Returns: 2First element in insertion order that appears exactly once
Understanding the Visualization
1
Input Stream
Numbers arrive in sequence: [2,3,5]
2
Track Unique
Maintain order of first occurrences
3
Query Result
Return first element that appears exactly once
Key Takeaway
🎯 Key Insight: Use doubly linked list to maintain unique elements and achieve O(1) queries
Asked in
Amazon 45 Bloomberg 32 Google 28 Microsoft 25
67.5K Views
High Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen