Problem set 1: arrays and hashing
🌍 In real life. A cricket coach sets drills that mix everything the team has practised: no drill names the shot to play, so the batter has to read each ball. These four problem sets work the same way. Each problem is told as a small real job; the hints reveal the pattern step by step, the first naming the technique and the second the steps.
The idea in one sentence: for every problem, read the clues and the limits first (Lessons 61.1–61.2), name the pattern before writing code, start with a brute force if you are unsure, and test the edge cases (Lesson 61.4).
Its words:
- frequency count: a dict from each item to how many times it appears
- in place: changing the list itself, with O(1) extra memory
- majority: an item that fills more than half of the list
This set (Easy): arrays and hashing
- First unique letter. A shop's loyalty card lists the first letter of each visitor's name in order; find the first letter that appears only once.
- Move the zeros. A delivery list has 0 for cancelled orders; push them to the end while the real orders keep their order.
- Majority vote. In a class election one name got more than half the votes; find it in one pass.
How to work a problem:
- say what is asked in one sentence, with an example
- list the clues: counting things → a dict; order matters → keep a list; "more than half" → a vote that cancels
- write it, then try the empty, one-item and all-the-same inputs
Counting with a dict is a hash table underneath (Chapter 35): each letter jumps straight to its bucket:
Why these patterns fit. First unique needs to know each letter's total before it can judge any letter, so it takes two passes: count, then look. Moving zeros only asks for order among the non-zeros, so a filter keeps them in order. The majority vote works because the winner has more votes than all the others together: every cancel removes one winning vote and one other, and the winner still has some left at the end.
What it costs, by counting. All three are one or two passes: O(n) time. For 1,000,000 letters, the counts dict holds at most 26 entries, O(1) memory; the vote keeps two variables, O(1) memory. A brute force that checks every letter against every other would take 1,000,000,000,000 steps.
A warm-up in the same style, checking that two words use the same letters:
def is_anagram(a, b):
counts = {}
for ch in a:
counts[ch] = counts.get(ch, 0) + 1
for ch in b:
counts[ch] = counts.get(ch, 0) - 1
return all(v == 0 for v in counts.values())
print(is_anagram("listen", "silent"), is_anagram("rat", "car"))
Mistakes and edge cases.
- counting with
s.count(ch)inside a loop: that hides an O(n²) loop - sorting to move zeros: sorting changes the order of the real orders
- the vote without a guaranteed majority: the candidate it returns is only right when a majority exists; otherwise count it to check
- empty input: no unique letter means −1
Quiz
"Find the first letter that appears only once." Which pattern?
- Count with a dict, then a second pass in order
- Binary search
- Backtracking
What does this print?
def first_unique(s): counts = {} for ch in s: counts[ch] = counts.get(ch, 0) + 1 # pass 1: count every letter for i, ch in enumerate(s): if counts[ch] == 1: # pass 2: the first letter seen once return i return -1 print(first_unique("loveleetcode"), first_unique("aabb"))What does this print?
def majority(nums): candidate, votes = None, 0 for x in nums: if votes == 0: candidate = x # a fresh candidate votes += 1 if x == candidate else -1 # a different number cancels one vote return candidate print(majority([2, 2, 1, 1, 1, 2, 2]))Why not sort the list to push the zeros to the end?
- Sorting would also reorder the real orders
- Sorting can't handle zeros
- Sorting uses too much memory
is_anagram("listen", "silent") should be True, but this gives False. Which line is wrong?
def is_anagram(a, b): counts = {} for ch in a: counts[ch] = counts.get(ch, 0) + 1 for ch in b: counts[ch] = counts.get(ch, 0) + 1 return all(v == 0 for v in counts.values())
Coding tasks
First unique letter. Write
first_unique(s): the index of the first letter ofsthat appears exactly once, or-1if there is none.Move the zeros. Write
move_zeros(nums): return a new list with every 0 moved to the end and the other numbers in their original order.Majority vote. Write
majority(nums): one value appears more than half the time; return it, using O(1) extra memory.