474. First Unique Number

You have a queue of integers, and you need to support the following operations efficiently:

  • Initialize the queue with a list of numbers.
  • Find the first unique number in the queue (the first number that appears only once).
  • Add a new number to the queue.

Example 1:

Input : operations : ["FirstUnique", "showFirstUnique", "add", "showFirstUnique", "add", "showFirstUnique", "add", "showFirstUnique"]

values : [[2,3,5],[],[5],[],[2],[],[3],[]]

Output : [null,2,null,2,null,3,null,-1]

Explanation :

FirstUnique firstUnique = new FirstUnique([2,3,5]);

firstUnique.showFirstUnique(); // return 2

firstUnique.add(5); // the queue is now [2,3,5,5]

firstUnique.showFirstUnique(); // return 2

firstUnique.add(2); // the queue is now [2,3,5,5,2]

firstUnique.showFirstUnique(); // return 3

firstUnique.add(3); // the queue is now [2,3,5,5,2,3]

firstUnique.showFirstUnique(); // return -1

Example 2:

Input : operations : ["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"]

values: [[7,7,7,7,7,7],[],[7],[3],[3],[7],[17],[]]

Output : [null,-1,null,null,null,null,null,17]

Explanation :

FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]);

firstUnique.showFirstUnique(); // return -1

firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7]

firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3]

firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3,3]

firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7,3,3,7]

firstUnique.add(17); // the queue is now [7,7,7,7,7,7,7,3,3,7,17]

firstUnique.showFirstUnique(); // return 17

Now Your Turn!

Pick the correct output for the given input

Input : operations :["FirstUnique","showFirstUnique","add","showFirstUnique"]

values : [[809],[],[809],[]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class FirstUnique {
public:
FirstUnique(vector<int>& nums) {
}
int showFirstUnique() {
}
void add(int value) {
}
};
 
/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/
Test Case

Input:

Input1
Input2