Eight interview problems that ask how often a value appears. The move: count once, then ask the question of the counts instead of the items.
You work on a banking app, an online store and a ride-hailing app. The eight problems on this street come from all of them. Each one reads a list of ids or codes, and the answer depends on how many times a value appears.
The questions look different, because the rule about the count changes. Here is each problem and the rule it puts on a count.
| Problem | The rule on the count of a value |
|---|---|
| First error code that appears once | exactly 1, and earliest in the log |
| Count orders per customer | whatever the count is, for each query |
| Majority payment method | more than half of the list |
| Values above a third of requests | more than a third of the list |
| Missing and repeated ids | 2 for one id, 0 for another |
| Top three most active users | among the three largest, ties by id |
| Fewest distinct values after k removals | smallest counts removed first |
| Longest streak of consecutive ids | at least 1, for every id in a run |
Read the right column and you will see one shape. The items themselves do not matter after you have counted them. The rule is about the numbers in the map.
You met the map in Counting and grouping. This street asks what you do with it next.
Build the count map in one pass. After that, forget the list and write the rule as a question about the counts.
After one pass, the map holds the exact count of every value. So any rule about how often values appear, such as exactly one, more than a share or the smallest first, is answered from the map alone.
Three kinds of rule come back on this street.
| The rule | What you read from the map |
|---|---|
| A threshold (exactly 1, above half) | each count against a number |
| A rank (top three) | the counts, sorted or placed in buckets |
| A budget (remove k entries) | the counts of counts, from the smallest |
Take the budget rule. A cache holds the entries 4, 4, 4, 7, 7, 9, 9, 9, 9, 2, 5. You must remove exactly 4 of them to leave the fewest distinct values.
The counts are 3, 2, 4, 1 and 1, so sorted they read 1, 1, 2, 3, 4. A value disappears only when all of its entries go. Spend the budget on the cheapest values first.
Exercise · Predict the output: How many values are left?. The code counts each value, sorts the counts and spends the budget k from the smallest count. What does it print?
values = [4, 4, 4, 7, 7, 9, 9, 9, 9, 2, 5]
k = 4
counts = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
sizes = sorted(counts.values())
left = len(sizes)
for s in sizes:
if k >= s:
k -= s
left -= 1
print(left)The same loop with one character changed is a classic slip. It compares k > s where k >= s is right.
Exercise · Find the bug: The last removal that fits. This returns the fewest distinct values left after exactly k removals. It is right for most inputs but wrong when the budget matches a count exactly. Which line is wrong?
def fewest_distinct(values, k):
counts = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
left = len(counts)
for s in sorted(counts.values()):
if k > s:
k -= s
left -= 1
return leftSpend a removal budget on the smallest counts first, because a value only disappears when all of its entries go.
The Academy lesson Counting and grouping builds the map and groups by a key. Seen-set and complement uses a map to remember. Frequency, palindromes and anagrams counts letters. This street adds four things.
A share needs no full map. More than a half can be held by one value only. More than a third can be held by at most two values, because three of them would need more than the whole list. A vote with one or two candidates and a checking pass finds them in constant memory.
On the list 1, 2, 3 the vote ends on 3, which appears once. So the checking pass is not optional when a majority is not guaranteed.
Position questions need the list again. The first code that appears once is not the smallest or the largest. Count first, then scan the original log in order and stop at the first count of one.
Counts have counts. A budget question sorts the counts themselves. Ranking users needs the order of counts, with ties broken by id. A leaderboard of the largest three is a sort of the pairs, or buckets numbered by count.
A set is a count of one. To find the longest run of consecutive ids, put the ids in a set and start a run only at an id whose predecessor is missing. Starting from every id re-walks each run. On the ids 1 to 100,000 that costs 5,000,050,000 steps, and starting only at run heads walks each id once, 100,000 steps.
More than a third allows two values, so one vote candidate misses one. Keep two candidates and check both.
Exercise · Break it: One candidate is not enough. This returns every client id that appears in more than a third of the requests. It keeps one vote candidate and then checks its count. Find an input where it gives the wrong answer.
def values_above_a_third(requests):
candidate = 0
votes = 0
for x in requests:
if votes == 0:
candidate = x
votes = 1
elif x == candidate:
votes += 1
else:
votes -= 1
total = 0
for x in requests:
if x == candidate:
total += 1
return [candidate] if total > len(requests) // 3 else []Solve them in this order. The first three read a count, the next two read a share or a range of ids, and the last three rank, spend or sequence the counts.
Before you code each problem, write the rule on the count in one line, as in the table at the top. Then name what you read from the map: one count, a ranking, or the counts of counts.
Give each problem about 20 minutes. Spend the first three on the rule line and on the question of order: does the answer depend on position, on ties or on the original list? Say it out loud as you would to an interviewer.
Three edge cases come back on almost every rung. The list can be empty, every value can be the same, and the answer can be a tie. Write one small test for each before you run anything.
When a solution fails, check the rule line first. Most wrong answers on this street come from a strict comparison that should not be strict. The other cause is a read of the map where the problem needs the list order.
Checkpoint · Duplicates and counting
Q1/5 You want the first error code in a log that appears exactly once. What do you do after building the count map?
Answer: B
The map has no knowledge of position. A second scan of the log, in its own order, finds the earliest code with a count of one.
Q2/5 A value must appear in more than a third of a list. How many values can possibly qualify?
Answer: B
Three values with more than a third each would need more entries than the list holds. So two vote candidates are enough, and a second pass checks them.
Q3/5 You may remove exactly k entries and want the fewest distinct values left. Which values do you remove first?
Answer: C
A value only disappears when every one of its entries is gone. The smallest counts cost the least budget per value removed.
Q4/5 You keep one vote candidate to find values above a third of a list. On 1, 1, 1, 1, 2, 2, 2, 2, 3, what goes wrong?
Answer: C
Both 1 and 2 appear four times in nine entries, which is more than a third. A single candidate cannot hold both, so the answer is incomplete.
Q5/5 To find the longest streak of consecutive ids, you put the ids in a set. When do you start counting a streak?
Answer: C
Starting at a run head means every run is walked once. Starting at every id re-walks each run, which is 5,000,050,000 steps for the ids 1 to 100,000.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.