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 INPUT Initial Queue 2 3 5 front back Operations: new FirstUnique([2,3,5]) showFirstUnique() add(5) showFirstUnique() Data Structures: HashMap + Doubly Linked List (or Queue with count map) ALGORITHM STEPS 1 Initialize Count: {2:1, 3:1, 5:1} Unique queue: [2,3,5] 2 showFirstUnique() Return front of unique queue Result: 2 (count[2]=1) 3 add(5) Count: {2:1, 3:1, 5:2} 5 now duplicate, remove Unique: [2,3] 4 showFirstUnique() Front still 2 (count=1) Result: 2 Final State: HashMap 2 --> 1 3 --> 1 5 --> 2 Unique Queue 2 3 first FINAL RESULT Operation Results: showFirstUnique() 2 add(5) then showFirstUnique() 2 Output Array: [2, 2] OK - Both calls return 2 2 remains first unique even after adding 5 Time: O(1) per operation Space: O(n) for maps Key Insight: Use a HashMap to track counts and a Queue/LinkedList to maintain order of unique elements. When adding a value, if count becomes 2, mark it as duplicate (lazy removal from queue). For showFirstUnique(), pop duplicates from front until finding count=1 or queue empty (return -1). TutorialsPoint - First Unique Number | Hash Map + Queue Approach
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