First Unique Ticket
A list tickets holds ticket numbers, and some numbers appear more than once. Write first_unique(tickets) that returns the first number in the list that appears exactly once in the whole list. If every number repeats, return None.
Understand the problem
Find out what "first" and "exactly once" mean here.
What does first_unique([4, 1, 2, 1, 4, 3]) return?
Counts: 4 appears twice, 1 twice, 2 once, 3 once. Both 2 and 3 appear exactly once, and 2 comes first in the list, so the answer is 2.
What does first_unique([7, 7, 8, 9, 8]) return?
7 appears twice, 8 twice, 9 once. The only number that appears once is 9.
What should first_unique([5, 5]) return? Type the word.
Every number repeats, so there is no unique one: None.
Try examples by hand
Notice what has to be known before you can answer.
To decide whether the first item is unique, what must you know?
- Only the first item
- How many times it appears in the whole list
- The last item
Whether a number is unique depends on the whole list, including items after it. You cannot decide while reading it for the first time. This is why you need counts.
You count each ticket by scanning the whole list of 20,000 tickets, once per ticket. About how many items do you look at in total?
- About 40 thousand
- About 400 million
- About 20 trillion
20,000 x 20,000 = 400,000,000. Counting inside a loop over the same list is the signature of an O(n squared) solution.
Write the brute force
Do not look for the clever answer yet. Write the simplest version that is correct, even if it is slow. A correct slow answer gives you something to test against and something to improve.
def first_unique(tickets):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
For each ticket in order, how do you find out how often it appears in the whole list?
Hint 2: the shape of the answer
Loop over the tickets in order. For each, use tickets.count(ticket). Return the first one whose count is 1.
Find the bottleneck
Before you improve anything, find what is slow. Answer these, then write the faster version.
What does your brute force do that is wasteful?
- It counts the same number again every time that number appears
- It reads the list in order
- It returns early
If a number appears 5 times, its count is computed 5 times, each time scanning the whole list. Count once, remember the result.
Which structure stores "ticket number -> how many times" and can be updated as you read?
- A list
- A dictionary
- A tuple
A dictionary maps each key to a value, so counts[ticket] is the count. collections.Counter is a dictionary built for exactly this.
After you have all the counts, how do you find the first unique ticket?
- Sort the dictionary
- Go through the original list in order and return the first with count 1
- Return the smallest key with count 1
The dictionary does not know the original order of the tickets (and the smallest number is not the first one). The list does, so walk the list again and look each ticket up.
Make it faster
Now write the version that counts once and then reads the list.
def first_unique(tickets):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
What can you do in one pass to make the second pass cheap?
Hint 2: the pattern
Two passes. Pass one counts every ticket in a dictionary (or Counter). Pass two reads the tickets in order and checks the count.
Hint 3: pseudocode
counts = empty dictionary
for each ticket: counts[ticket] = counts.get(ticket, 0) + 1
for each ticket in the original order:
if counts[ticket] == 1: return ticket
return None
Reflect
Brute force: O(n squared)
def first_unique(tickets):
for ticket in tickets:
if tickets.count(ticket) == 1:
return ticket
return None
Improved: O(n)
def first_unique(tickets):
counts = {}
for ticket in tickets:
counts[ticket] = counts.get(ticket, 0) + 1
for ticket in tickets:
if counts[ticket] == 1:
return ticket
return None
Another way: Counter
from collections import Counter
def first_unique(tickets):
counts = Counter(tickets)
for ticket in tickets:
if counts[ticket] == 1:
return ticket
return None
Pattern: count once, then answer many questions. A frequency table (value -> count) turns "how many times does x appear?" from a scan into a lookup. This is the most common use of a dictionary in interviews.
Two passes are fine. Two passes over the list is still O(n); constants do not matter in big-O. The first pass gathers facts about the whole list, the second uses them while keeping the original order.
Cost:
| Version | Time | Extra space |
|---|---|---|
count() inside a loop |
O(n squared) | O(1) |
| Frequency dictionary | O(n) | O(n) |
What an interviewer might ask next: What if the tickets arrive one at a time in a stream and you must always know the first unique one so far? (Keep the counts, and the order in which tickets first arrived.)
import random
VISIBLE = 3
CASES = [
(([4, 1, 2, 1, 4, 3],), 2, 'two numbers are unique, the first one wins'),
(([7, 7, 8, 9, 8],), 9, 'the unique one is last'),
(([5, 5],), None, 'everything repeats'),
(([],), None, 'empty list'),
(([6],), 6, 'one ticket'),
(([1, 2, 3],), 1, 'all unique'),
(([2, 2, 3, 3, 4, 2],), 4, 'a number that repeats three times'),
(([9, 8, 9, 7, 8],), 7, 'a unique number at the end'),
(([8, 3, 3, 6, 2, 8],), 6, 'the first unique number is not the smallest'),
]
def REFERENCE(tickets):
counts = {}
for ticket in tickets:
counts[ticket] = counts.get(ticket, 0) + 1
for ticket in tickets:
if counts[ticket] == 1:
return ticket
LIMIT = 2.0
def PERF():
rng = random.Random(3)
tickets = list(range(15000)) * 2
rng.shuffle(tickets)
tickets.append(-1)
others = list(range(50000)) * 2
rng.shuffle(others)
return [('30000 tickets, the only unique one is last', (tickets,)), ('100000 tickets, none is unique', (others,))]