First Unique Number
1 approach, code in every language
Problem description
You are given a stream of integers and must always be able to report the first value in the stream that has appeared exactly once so far.
Implement the FirstUnique class. The constructor FirstUnique(nums) seeds the stream with an initial array of numbers. The method showFirstUnique() returns the earliest value that is still unique, or -1 when no such value exists. The method add(value) appends value to the stream.
As duplicates arrive, values that were once unique may stop being unique, so the reported answer can change over time.
Example 1
Input: ["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"] [[[2,3,5]],[],[5],[],[2],[],[3],[]]
Output: [null,2,null,2,null,3,null,-1]
Start with [2,3,5]; first unique is 2. add(5) makes 5 a duplicate but 2 is still first unique. add(2) makes 2 a duplicate, so 3 becomes first unique. add(3) makes 3 a duplicate, leaving no unique value, so the answer is -1.
Example 2
Input: ["FirstUnique","showFirstUnique","add","add","showFirstUnique"] [[[7,7,7]],[],[7],[8],[]]
Output: [null,-1,null,null,8]
The initial [7,7,7] has no unique value, so the answer is -1. After add(7) and add(8), 8 is the only value seen once, so it becomes the first unique.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^81 <= value <= 10^8At most 5 * 10^4 calls will be made to showFirstUnique and add.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free