Taro Logo

First Unique Number

#2 Most AskedMedium
0 views
Topics:
Arrays

You are given an array of integers votes where each integer represents the number of votes a candidate received. We need to rank the candidates by the number of votes they received from highest to lowest.

Return a string of all the candidates sorted by the number of votes they received. If two or more candidates receive the same number of votes, then order them alphabetically. For example, if votes = ["ABC", "ACB", "ABC", "ACB", "ACB"] then candidate A received 5 votes, candidate B received 2 votes, and candidate C received 3 votes.

The solution should be alphabetically ordered string. For example, if votes = ["ABC", "ACB", "ABC", "ACB", "ACB"] then return "ACB". If votes = ["WXYZ","XYZW"] then return "XWYZ".

Example 1:

Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: 
Candidate A receives 5 votes.
Candidate B receives 2 votes.
Candidate C receives 3 votes.
The order is ACB.

Example 2:

Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: 
Candidate W receives 1 vote.
Candidate X receives 1 vote.
Candidate Y receives 1 vote.
Candidate Z receives 1 vote.
The order is ordered alphabetically: WXYZ.
In the end, we need to sort them according to the number of votes they received.

Example 3:

Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: 
Only one round of votes.
The order is ZMNAGUEDSJYLBOPHRQICWFXTVK.

Constraints:

  • 1 <= votes.length <= 1000
  • 1 <= votes[i].length <= 26
  • All characters of votes[i] are upper-case English letters.
  • votes[i] are distinct.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What specific indicator value or exception should be returned if no unique number exists in the stream?
  2. Can the input stream contain negative integers and zeros, or are we only dealing with positive integers?
  3. When we add a new number to the stream via the add method, does it return anything, or is it strictly a void operation?
  4. If a number was previously unique, but a duplicate of it is added later, does it lose its unique status permanently, and what happens to the 'first unique' pointer?
  5. Can the initial collection passed to the constructor contain duplicates, and should we process them to find the initial first unique number?

Brute Force Solution

Approach

Imagine you are given a long line of people entering a room one by one, and you need to find the very first person who never shows up again. The brute force strategy involves closely examining each person in the room and checking the entire rest of the line to see if they ever reappear.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first person who entered the room.
  2. Walk through the rest of the waiting line from the beginning to the end to see if that same person appears a second time.
  3. If you find another copy of that person further down the line, you know they are not unique, so you completely forget about them and move on.
  4. If you check the entire line from start to finish and cannot find anyone else with that person's name, you have successfully found your answer.
  5. Stop your search immediately and point out this person as the first unique individual.
  6. If that first person did show up again, go back to the front, pick the second person in line, and repeat the exact same exhaustive checking process.
  7. Continue this process step by step down the line until you find someone who never repeats, or announce that everyone has a duplicate if you reach the very end with no matches.

Code Implementation

def find_first_unique_number(waiting_line):
    # We scan each person from the start to check if they ever appear anywhere else later
    for current_index in range(len(waiting_line)):
        current_person = waiting_line[current_index]
        is_person_unique = True
        
        for check_index in range(len(waiting_line)):
            if current_index != check_index and waiting_line[check_index] == current_person:
                is_person_unique = False
                break
        
        # If no duplicate was found during our full scan, this is our first unique person
        if is_person_unique:
            return current_person
            
    # If the loop finishes without returning, everyone in the room has a duplicate
    return -1

Big(O) Analysis

Time Complexity
O(n²) – For each of the n people entering the room, we must walk through the entire remaining waiting line to check for duplicates. For the first person we check n-1 elements, for the second person n-2 elements, and so on down the line. Summing these checks together leads to approximately n * n/2 total operations. Simplifying this expression by dropping constants gives a final worst-case runtime of O(n²).
Space Complexity
O(1) – The brute force strategy described in the plain English steps relies entirely on repeatedly scanning the existing waiting line without introducing any auxiliary data structures, such as hash maps, temporary lists, or recursive call stacks. We only maintain a few primitive tracking variables to iterate through the sequence of people. Therefore, the extra memory required remains constant regardless of how many individuals are in the line, resulting in an auxiliary space complexity of O(1).

Optimal Solution

Approach

To efficiently find the first unique number as items arrive, we combine a tracking book with an organized waiting line. This clever setup lets us instantly look up how many times a number has appeared while always keeping the current unique champion ready at the front.

Here's how the algorithm would work step-by-step:

  1. Create a tracking book to record how many times each number has been mentioned, and set up a waiting line to hold numbers that have only appeared once.
  2. When a new number arrives, immediately check the tracking book to see if it has been seen before.
  3. If the number has never been seen before, update the tracking book and add it to the back of the waiting line.
  4. If the number has been seen before, simply update its count in the tracking book without adding it to the waiting line again.
  5. Whenever asked to find the first unique number, look at the very front of the waiting line.
  6. Before trusting who is at the front of the waiting line, peek into the tracking book to check their total count.
  7. If the person at the front has been mentioned more than once, remove them from the front and repeat the check until you find someone with a count of exactly one.
  8. If the waiting line becomes completely empty during this process, report that there are no unique numbers available.

Code Implementation

from collections import deque


class FirstUnique:

    def __init__(self, initial_numbers):
        self.frequency_map = {}
        self.waiting_line = deque()
        for current_number in initial_numbers:
            self.add(current_number)

    def show_first_unique(self):
        # We clean the front of the queue to ensure the current champion is truly unique.
        while self.waiting_line:
            potential_champion = self.waiting_line[0]
            if self.frequency_map[potential_champion] == 1:
                return potential_champion
            self.waiting_line.popleft()
        return -1

    def add(self, incoming_number):
        # We update or initialize the frequency record to track how often numbers appear.
        if incoming_number not in self.frequency_map:
            self.frequency_map[incoming_number] = 1
            self.waiting_line.append(incoming_number)
        else:
            self.frequency_map[incoming_number] += 1
        # Numbers appearing multiple times are ignored in the waiting line to save search time.

Big(O) Analysis

Time Complexity
O(1) amortized – For each incoming number added to the data stream, checking the tracking book hash map and appending to the queue takes constant time on average. When querying the first unique number, we may repeatedly inspect and remove stale elements from the front of the queue, but each number is added and removed at most once across all queries. Thus, over a sequence of n operations, the total cost averages out to constant time per operation, resulting in O(1) amortized time complexity.
Space Complexity
O(N) – The auxiliary space complexity is driven by the tracking book, implemented as a hash map, and the waiting line, implemented as a queue. As numbers arrive, each unique value is stored in both the hash map and the queue. In the worst-case scenario where every single one of the N incoming numbers is distinct, both data structures will grow linearly to store up to N elements. Therefore, the total extra memory scales directly with the input size N, simplifying to Big O notation of O(N).

Edge Cases

Empty initial stream provided to the constructor
How to Handle:
Initialize empty underlying data structures so subsequent additions and queries function correctly without null pointer exceptions.
Stream contains all duplicate numbers with no unique elements
How to Handle:
Maintain a tracking mechanism that returns negative one or an appropriate indicator when no unique number exists.
Adding a number that has already appeared multiple times
How to Handle:
Update the frequency map and efficiently remove or bypass it in the uniqueness tracking structure.
A number appears only once initially, and then a duplicate is added later
How to Handle:
Ensure the data structure safely removes the element from the tracking queue or set upon its second occurrence.
Large scale input stream with millions of add operations
How to Handle:
Use a hash map combined with a doubly linked list or queue to guarantee constant time complexity for both operations.
Inputs containing negative numbers and zero alongside positive integers
How to Handle:
Use hash-based data structures that natively support negative integer keys and zero without requiring index offset adjustments.
Querying for the first unique number when the tracking structure is currently empty
How to Handle:
Return the predefined indicator value immediately to signal the absence of any unique elements.
0/4 completed