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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code