MediumHash TableDesignQueueData Stream

First Unique Number

LeetCode
1 approach, code in all languages

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^5
  • 1 <= nums[i] <= 10^8
  • 1 <= value <= 10^8
  • At most 5 * 10^4 calls will be made to showFirstUnique and add.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now