First Unique Number — LeetCode 1429 Python Solution

MediumLeetCode PremiumDesignQueueArrayHash TableData Stream
Problem
#1429
Pattern
Stack
Reading time
4 min

The problem

You have a queue of integers, 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.

Example

Input
["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"]
Output
[null,2,null,2,null,3,null,-1]
Explanation
FirstUnique firstUnique = new FirstUnique([2,3,5]);

Python solution

Python
class FirstUnique:
    def __init__(self, nums: List[int]):
        self.cnt = Counter(nums)
        self.unique = OrderedDict({v: 1 for v in nums if self.cnt[v] == 1})

    def showFirstUnique(self) -> int:
        return -1 if not self.unique else next(v for v in self.unique.keys())

    def add(self, value: int) -> None:
        self.cnt[value] += 1
        if self.cnt[value] == 1:
            self.unique[value] = 1
        elif value in self.unique:
            self.unique.pop(value)


# Your FirstUnique object will be instantiated and called as such:
# obj = FirstUnique(nums)
# param_1 = obj.showFirstUnique()
# obj.add(value)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1429. First Unique Number is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1429. First Unique Number?
LeetCode 1429. First Unique Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 1429. First Unique Number?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1429. First Unique Number?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1429. First Unique Number cover?
LeetCode 1429. First Unique Number is tagged Design, Queue, Array, Hash Table and Data Stream on LeetCode.
Is LeetCode 1429. First Unique Number a premium problem?
Yes. LeetCode 1429. First Unique Number is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview