IntermediatePython · 21 min · 18 challenges

Problem Solving: Intermediate

It is late November at Spotify, and a Wrapped card claims a listener gave 38% of their year to one artist. That figure needs the year's total before any artist's slice exists. A brand-new account has no plays at all, and the play log is far too long to compare every row with every other. Each choice decides whether the card ships correct.

Solving a Problem in 2 Passes

Daily Life
Interviews
Some questions about a list can be answered row by row. Others depend on a fact about the whole list: its total, its average, or how often a value occurs. For those, the loop meets row 1 before it has read the rows that decide row 1's answer. The way out is to read the data twice: a first pass that only learns a summary, then a second pass that acts on every row.

A share needs the total first

Take 4 play events for a single listener, each an artist and the minutes played. The task is to print what percent of the listener's minutes each event represents. A percent is minutes divided by the total, and the total stays unknown until the last row has been read. Here is a 1-pass attempt that divides by the total seen so far:
plays = [("Mitski", 60), ("SZA", 20), ("Mitski", 40), ("Khruangbin", 80)]
running = 0
for artist, minutes in plays:
running += minutes
print(artist, minutes * 100 // running)
>>>Output
Mitski 100
SZA 25
Mitski 33
Khruangbin 40
Only Khruangbin's line is right. Every earlier row was divided by a partial total: Mitski's first 60 minutes looked like 100% because nothing else had been read yet. No change to the arithmetic inside that loop can repair it, since the missing information sits in rows the loop hasn't reached.
plays = [("Mitski", 60), ("SZA", 20), ("Mitski", 40), ("Khruangbin", 80)]
total = 0
for artist, minutes in plays:
total += minutes
for artist, minutes in plays:
print(artist, minutes * 100 // total)
>>>Output
Mitski 30
SZA 10
Mitski 20
Khruangbin 40

The first loop prints nothing. Its only job is to produce total, and the second loop reads that value on every row. Every 2-pass solution has this shape: pass 1 builds a small summary, and pass 2 makes each row's decision using it.

When the summary is a dict of counts

The summary can be bigger than a single number. Suppose an event log lists the user behind each event, and the task is the first user who appears exactly once, a one-time visitor. When the loop reaches cy, it cannot tell whether cy shows up again 3 rows later. Pass 1 counts every user into a dict; pass 2 walks the log in its original order and stops at the first user whose count is 1.

events = ["ana", "bo", "ana", "cy", "bo", "dee"]
counts = {}
for user in events:
counts[user] = counts.get(user, 0) + 1
first_once = None
for user in events:
if counts[user] == 1:
first_once = user
break
print(counts)
print(first_once)
user=
first_once=
events
[
]
012345
counts
:
:
:
:
output0 lines
events is a new list that holds 'ana', 'bo', 'ana', 'cy', 'bo', 'dee'
1/29

Pass 1 fills counts; pass 2 stops at the first user counted once.

The dict is complete before the second loop asks its first question, so counts[user] == 1 is a statement about the entire log. The second pass could walk counts instead, because a dict keeps its keys in first-inserted order and a user seen once was inserted at its only position. Either loop works; neither can run until the counting is finished.

Spotting a problem that needs 2 passes

✓One pass is enough when
  • The answer for a row depends only on rows already read
  • Running totals, a maximum, a count of rows over a threshold
  • Example: print the cumulative minutes after each play
✗A second pass is needed when
  • A row's answer depends on rows that come after it
  • Shares of a total, distance from the average, 'appears only once'
  • Example: flag every order larger than the day's average order
TIP
Phrases such as 'share of', 'percent of the total', 'compared with the average' and 'unique' signal that each row is judged against the whole list. Look for them in the task before writing the first loop.
Reading twice doubles the row visits, so 1 million rows become 2 million, and the summary from pass 1 must fit in memory. A single number costs nothing; a dict of counts grows with the number of distinct users. Both costs grow in step with the data, which keeps 2-pass solutions practical on large inputs.
Multiple Choice

Which task needs a second pass over a list of order amounts?

An average adds one line between the 2 passes. Pass 1 adds into total. Once that loop has finished, average = total / len(amounts) runs a single time, outside both loops, and pass 2 compares each amount with that fixed value. For orders [40, 10, 30, 80], pass 1 ends with total at 160 and average at 40.0, and pass 2 flags only 80, because > leaves out the 40 that equals it. Indented one level deeper, inside pass 1, the division becomes a running average that changes on every row and matches the real one only after the last row.

Loading the challenge

Edge Case Handling

Daily Life
Interviews
A function that works on the inputs its author pictured is half finished. Pipelines hand functions empty batches, missing values, strings where numbers were expected and lists of a single row. An edge case is an input at the boundary of what the function was written for, and each one either gets a deliberate answer or produces a crash or a silent wrong number.

Where an unguarded function breaks

Multiple Choice

What does this program print?

def average(values):
return sum(values) / len(values)
print(average([4, 8, 6]))
print(average([]))
Empty is only one boundary. The table lists the inputs worth asking about for any function that takes a list of numbers, with what this average function does with each.
Input kindExampleWhat average does
Empty`[]`ZeroDivisionError
None`None`TypeError from `sum`
Wrong container`"468"`TypeError from `sum`
Bad item`[4, "8", 6]`TypeError from `sum`
Single item`[7]`7.0, correct
Booleans`[True, False]`0.5, counted as 1 and 0 without complaint

Guard clauses that return a deliberate answer

A guard clause checks for a bad case at the top of the function and returns immediately. The design question is what to return. For an average of nothing, 0 would be a lie: a dashboard would plot 0 minutes for a listener with no data, and nobody downstream could tell it from a real 0. None says 'no answer exists' and forces the caller to check with is None.

def average(values):
if not isinstance(values, list):
return None
if len(values) == 0:
return None
return sum(values) / len(values)
print(average([4, 8, 6]))
print(average([]))
print(average(None))
print(average("468"))
>>>Output
6.0
None
None
None

isinstance(None, list) is False, so the first guard catches None along with strings and dicts. The order of guards matters: each check must be safe to run on whatever the earlier checks let through. Put the len check first and average(None) crashes with TypeError: object of type 'NoneType' has no len() before the type check ever runs.

Bad items inside a good list

A type check on the list says nothing about its items. A batch of watch times may carry a string that was never converted, or a None where a client failed to report. The function faces a policy choice: reject the whole batch, or skip the bad items. Skipping keeps the pipeline moving, but a silent skip hides data loss, so the version below returns the count of dropped items alongside the average.

def average_minutes(values):
if not isinstance(values, list):
return None, 0
total = 0
good = 0
skipped = 0
for v in values:
if isinstance(v, int):
total += v
good += 1
else:
skipped += 1
if good == 0:
return None, skipped
return total / good, skipped
print(average_minutes([30, "45", 60, None]))
print(average_minutes(["x"]))
print(average_minutes(None))
>>>Output
(45.0, 2)
(None, 1)
(None, 0)

The final guard, good == 0, catches a case the type checks cannot: a real list in which every item was bad. Without it, ["x"] reaches total / good and divides by zero, the empty-list crash arriving by a different road.

✓Do
  • Decide the return value for empty, None and wrong-type input before writing the main logic
  • Order guards so each check is safe on what earlier checks let through
  • Report how many items were skipped instead of dropping them silently
  • Test every function on [], None and a 1-item list
✗Don't
  • Return 0 for 'no data' when 0 is also a real answer
  • Call len() on a value that may be None
  • Assume a list of the right type holds items of the right type
  • Guard only the case that crashed last week
Loading the challenge

What Input Size Rules Out

Daily Life
Interviews
A problem statement often says how big the input can get: up to 1,000 rows, up to 100,000 events, an answer within 1 second. Those limits are design information. Before writing code, you can estimate how many steps each candidate approach takes and discard the ones that cannot finish in time.

Count steps, then compare with a budget

A loop over n items runs its body n times, and 2 passes run 2 × n bodies. A loop inside a loop that compares every item with every later item runs about n × n ÷ 2 bodies, because the first item is compared with n - 1 others, the second with n - 2, and so on. For a working budget, take around 10 million simple steps per second in Python: a conservative figure for loop bodies doing a comparison or an addition, which you can confirm by timing a loop on your own machine.

The animation runs 2 approaches to a duplicate check on 6 IDs and counts the steps each one takes.
ids = [7, 3, 9, 3, 5, 8]
pair_checks = 0
dup_nested = False
for i in range(len(ids)):
for j in range(i + 1, len(ids)):
pair_checks += 1
if ids[i] == ids[j]:
dup_nested = True
dict_steps = 0
counts = {}
for x in ids:
dict_steps += 1
counts[x] = counts.get(x, 0) + 1
print(pair_checks, dup_nested)
print(dict_steps, counts)
pair_checks=
dup_nested=
i=
j=
dict_steps=
x=
ids
[
]
012345
counts
:
:
:
:
:
output0 lines
ids is a new list that holds 7, 3, 9, 3, 5, 8
1/86

Pair checks grow with n × n; counting steps grow with n.

At 6 IDs the gap is 15 against 6. The table pushes n to sizes a pipeline actually sees and converts steps to time with the budget of 10 million simple steps per second.
n (items)Steps, 1 passTime, 1 passPair checksTime, pair checks
1,0001,0000.0001 s499,5000.05 s
100,000100,0000.01 sabout 5 billionabout 8 minutes
10,000,00010,000,0001 sabout 50 trillionabout 58 days
Read the table against a limit of 100,000 events and 1 second. Pair checks need roughly 8 minutes, so any solution shaped like a loop inside a loop is ruled out before it is written, however clean it looks. One pass or 2 passes cost about 0.01 to 0.02 seconds and fit with room to spare. At 10 million rows a single pass costs about 1 second, so a 1-second limit allows only one lean pass; a 5-second limit allows a handful of passes, and still nothing nested.

Small limits allow the direct approach

The arithmetic also works in the other direction. If a task guarantees at most 1,000 rows, the pair loop finishes in about 0.05 seconds, and its directness becomes an advantage: it reads like the problem statement and leaves little room for mistakes. A stated limit tells you which approaches are forbidden, and also which ones you are allowed to keep plain.

Loops hidden inside a single line

Some loops do not look like loops. x in some_list, some_list.count(x), some_list.index(x) and some_list.remove(x) each scan the list from the front, so calling one inside a for loop builds a loop inside a loop. The dedup below has a single visible for, but user not in seen walks seen on every row.

events = ["ana", "bo", "ana", "cy", "bo", "dee"]
seen = []
for user in events:
if user not in seen:
seen.append(user)
print(seen)

With 1 million mostly distinct users, seen grows toward 1 million names, and each later row scans most of it: hundreds of billions of comparisons. A dict behaves differently. key in counts and counts[key] take about the same time whether the dict holds 10 keys or 10 million, which is why the counting pass in the animation stays at n steps.

Reading a size limit
  • ▸Up to around 1,000 items: comparing every pair fits, so pick the clearest code
  • ▸Up to around 100,000 items: 1 or a few passes, with dict lookups inside
  • ▸About 10 million items: a few passes at most, and watch what each pass stores
  • ▸A time limit is a step budget: about 10 million simple steps per second
  • ▸Count the hidden scans from in, count, index and remove as loops
Multiple Choice

A task gives up to 200,000 transactions and expects an answer in about 1 second. With a budget of 10 million simple steps per second, which approach is ruled out before coding?

The pair count has an exact form. The first item meets n - 1 later items, the second n - 2, down to 0 for the last, and those add up to n * (n - 1) // 2. For the 6 IDs in the animation that is 6 × 5 ÷ 2 = 15, the pair_checks it printed; for 1,000 items it is 499,500, the figure in the table. Turning a limit into a verdict is then one comparison: compute the steps for the largest allowed n and check whether they stay within the budget, 10 million steps for a 1-second limit.

Loading the challenge

Solving a Simpler Version First

Daily Life
Interviews
Some problems arrive with several difficulties tangled together. Handling all of them in the first draft produces code that is wrong in ways that are hard to locate. A better move is to strip the problem down to a version small enough to work by hand, solve it, and then add the difficulties back one at a time, testing after each.

The full problem: longest streak per user

A product team wants each user's longest run of consecutive active days. The events arrive as (user, day) tuples, where day is a day number. They are out of order, a user can be active twice on the same day, and many users share a single list. That is 3 complications on top of the core question.

VersionWhat it dropsWhat it teaches
1Many users, disorder, repeat daysA streak breaks wherever 2 neighbors differ by more than 1
2Many users, disorderA gap of 0 is a repeat day: skip it, neither extend nor break
3Many usersSorting the days first turns disorder into version 2
4NothingGroup by user, then call the single-user function per user
//

Version 1: a single user, sorted, no repeats

With a single user's days already sorted and no repeats, the core idea fits in one comparison: if a day is exactly 1 more than the day before it, the current run grows; otherwise the run ends and a new one starts. The program collects every run length and takes the largest at the end.
days = [1, 2, 3, 5, 6, 10]
runs = []
current = 1
for i in range(1, len(days)):
if days[i] == days[i - 1] + 1:
current += 1
else:
runs.append(current)
current = 1
runs.append(current)
print(runs)
print(max(runs))
current=
i=
days
[
]
012345
runs
[
]
012
output0 lines
days is a new list that holds 1, 2, 3, 5, 6, 10
1/25

A run grows while each day is 1 more than the last and closes at every gap.

Day 5 follows day 3, so the first run closes at 3 and a new run starts. Day 10 follows day 6 and closes a run of 2. The runs.append(current) after the loop records the last run, which no gap ever closed.

//

Versions 2 to 4: add a difficulty at a time

Version 2 adds repeat days. With [1, 2, 2, 3], version 1 sees 2 followed by 2, a difference of 0, and wrongly closes the run. Computing gap = days[i] - days[i - 1] and skipping when gap == 0 repairs it. Version 3 adds disorder, and sorted(days) at the top reduces it to version 2. Version 4 adds many users: group the days into a dict of lists keyed by user, then call the finished single-user function once per key.

def longest_streak(days):
if len(days) == 0:
return 0
days = sorted(days)
runs = []
current = 1
for i in range(1, len(days)):
gap = days[i] - days[i - 1]
if gap == 0:
continue
if gap == 1:
current += 1
else:
runs.append(current)
current = 1
runs.append(current)
return max(runs)
events = [("ana", 3), ("bo", 1), ("ana", 1), ("ana", 2),
("bo", 2), ("ana", 2), ("bo", 5)]
by_user = {}
for user, day in events:
if user not in by_user:
by_user[user] = []
by_user[user].append(day)
for user, days in by_user.items():
print(user, longest_streak(days))
>>>Output
ana 3
bo 2

Each version kept the earlier tests valid. Version 1's sample still returns 3 under the final code, and ana's days [3, 1, 2, 2] exercise both the sort and the repeat skip. The empty-list guard came from running the version 1 logic on an input it never saw: with no days the loop does not run, and the trailing append would report a streak of 1.

Ways to shrink a problem
  • ▸Solve for 1 user, 1 key or 1 day before many
  • ▸Assume the input is sorted, then sort it yourself later
  • ▸Assume no duplicates, then decide what a duplicate should mean
  • ▸Fix the size at 3 or 4 items and work the answer by hand
  • ▸Drop the output format and print raw values until the logic is right
TIP
Write down the assumptions the simple version makes. That list becomes the plan: each assumption you remove is one change to the code and one new test case.
Multiple Choice

The full task: for each region, find the hour with the highest total revenue, from rows of (region, hour, revenue) in no particular order. Which simpler version is the best first step?

When an added difficulty breaks an earlier version, list each kind of input the difficulty brings and the branch it reaches in the old code. For the streak loop, those inputs are the possible gaps between neighboring days. Version 1 has only 2 branches, so every gap that is not 1 lands in the branch that closes the run.
Gap between neighborsVersion 1 branchRight behavior
1`if`: the run growsGrow the run, as version 1 does
0, a repeat day`else`: the run closesSkip the row
2 or more`else`: the run closesClose the run, as version 1 does
Loading the challenge

Comparing 2 Working Solutions

Daily Life
Interviews
Solutions that both pass every test can still differ in what they cost. One may finish in a fraction of a second where the other takes minutes, one may hold an extra dict the size of the input, and one may read like the problem statement while the other needs explaining. Choosing between them is a judgment made against the input limits and the people who will maintain the code.

Finding the first one-time user with count() and with a dict

def first_once_count(events):
for user in events:
if events.count(user) == 1:
return user
return None
def first_once_dict(events):
counts = {}
for user in events:
counts[user] = counts.get(user, 0) + 1
for user in events:
if counts[user] == 1:
return user
return None
events = ["ana", "bo", "ana", "cy", "bo", "dee"]
print(first_once_count(events))
print(first_once_dict(events))
>>>Output
cy
cy

Both print cy. first_once_count is 4 lines and says what it means: the first user whose count in the log is 1. Its cost hides in events.count(user), which reads the whole list on every call. first_once_dict takes 2 loops and a dict, and reads the log exactly twice.

Speed, memory and clarity side by side

Measurefirst_once_countfirst_once_dict
Reads of a log with no one-time usern × n2 × n
n = 1,0001,000,000 reads2,000 reads
n = 100,00010 billion reads, about 17 minutes200,000 reads, about 0.02 s
Extra memoryNothing beyond the listOne dict entry per distinct user
ClarityMirrors the task in a single conditionTwo loops; the reader must see why

The table assumes a log with no one-time user, the input that makes both functions read to the end. There the count version calls count n times, each a full scan, while the dict version finishes its 2 passes and returns None. The times use the same budget as before, 10 million simple steps per second.

A rule for choosing

Start from the stated limits. Discard any solution whose step count does not fit the budget; that decision needs no taste. Among the ones that fit, prefer the one a teammate can verify fastest, which usually means the shortest code that states the task directly. Memory decides only when the extra structure would not fit, for example a dict over hundreds of millions of distinct keys on a single machine.
✓Keep first_once_count when
  • The log is capped at roughly 1,000 events
  • The function runs once in a script, not once per row of a pipeline
  • Readers need to check it against the spec at a glance
✗Switch to first_once_dict when
  • The log can reach 100,000 events or more
  • The function runs inside a loop over many logs
  • The next request, every one-time user, needs the counts anyway
The last row points at a fourth measure: how each solution absorbs the next change. Once the counts exist, listing every one-time user, or every user seen more than 5 times, is an edit to the second loop's condition. The count version would repeat its full scans for each new question.
Multiple Choice

A nightly job checks a config list capped at 50 entries for any name that appears twice. One correct version calls names.count(name) > 1 inside a loop; another builds a dict of counts first. Which should the team keep?

The count version has a second flaw once the task changes from 'is there a duplicate' to 'list the duplicates'. A loop over ids that prints every ID passing ids.count(i) > 1 prints it once per appearance, so an ID that occurs 3 times prints 3 times. Walking the dict of counts visits each key exactly once, in the order it was first inserted, which is the order of its first appearance in the list. Counting in pass 1 and filtering the dict in pass 2 gives one line per duplicated ID.

Loading the challenge
PUTTING IT ALL TOGETHER

> Spotify's Wrapped shows each listener their top artist and the minutes they spent with that artist over the year. A batch job has to turn a log of (listener, artist, minutes) rows into a card per listener, including listeners who signed up recently and have no plays, with every card's share computed correctly.

The simpler version comes first: a single listener's (artist, minutes) rows, ignoring every other listener, then grouping by listener in a dict once that works.
For each listener, pass 1 totals minutes overall and per artist in a dict; pass 2 picks the top artist and divides by the total.
A guard returns None for a listener whose total is 0, so a new account gets no card instead of a ZeroDivisionError.
The batch size rules out comparing rows pairwise or calling count inside a loop; grouping into a dict keeps the job to a few passes.
If a short list-based version and a dict version both produce correct cards, the batch size picks the dict version, and clarity breaks ties only where both fit the budget.
KEY TAKEAWAYS
When a row's answer depends on the whole list, read twice: pass 1 builds a summary, pass 2 decides each row with it.
Guard clauses at the top of a function give empty, None and wrong-type input a deliberate answer, ordered so each check is safe.
A size limit plus a budget of roughly 10 million simple steps per second rules out loop-inside-a-loop solutions beyond around 5,000 items when the limit is 1 second.
in, count, index and remove on a list each hide a scan, and inside a loop they make a nested loop.
Solve a stripped-down version first, then add each removed difficulty back with its own test.
Between correct solutions, discard what breaks the budget, then keep the clearest of what remains.

Two passes, guarded inputs, size budgets and simpler drafts: habits that pick a solution before you type it.

Category
Python
Difficulty
intermediate
Duration
21 minutes
Challenges
18 hands-on challenges

Topics covered: Solving a Problem in 2 Passes, Edge Case Handling, What Input Size Rules Out, Solving a Simpler Version First, Comparing 2 Working Solutions

Lesson Sections

  1. Solving a Problem in 2 Passes (concepts: List Comprehension)

    Some questions about a list can be answered row by row. Others depend on a fact about the whole list: its total, its average, or how often a value occurs. For those, the loop meets row 1 before it has read the rows that decide row 1's answer. The way out is to read the data twice: a first pass that only learns a summary, then a second pass that acts on every row. A share needs the total first Take 4 play events for a single listener, each an artist and the minutes played. The task is to print wh

  2. Edge Case Handling (concepts: Guard Clauses)

    A function that works on the inputs its author pictured is half finished. Pipelines hand functions empty batches, missing values, strings where numbers were expected and lists of a single row. An edge case is an input at the boundary of what the function was written for, and each one either gets a deliberate answer or produces a crash or a silent wrong number. Where an unguarded function breaks Empty is only one boundary. The table lists the inputs worth asking about for any function that takes

  3. What Input Size Rules Out (concepts: Sets)

    A problem statement often says how big the input can get: up to 1,000 rows, up to 100,000 events, an answer within 1 second. Those limits are design information. Before writing code, you can estimate how many steps each candidate approach takes and discard the ones that cannot finish in time. Count steps, then compare with a budget The animation runs 2 approaches to a duplicate check on 6 IDs and counts the steps each one takes. At 6 IDs the gap is 15 against 6. The table pushes n to sizes a pip

  4. Solving a Simpler Version First (concepts: Generators)

    Some problems arrive with several difficulties tangled together. Handling all of them in the first draft produces code that is wrong in ways that are hard to locate. A better move is to strip the problem down to a version small enough to work by hand, solve it, and then add the difficulties back one at a time, testing after each. The full problem: longest streak per user Version 1: a single user, sorted, no repeats With a single user's days already sorted and no repeats, the core idea fits in on

  5. Comparing 2 Working Solutions (concepts: Collections)

    Solutions that both pass every test can still differ in what they cost. One may finish in a fraction of a second where the other takes minutes, one may hold an extra dict the size of the input, and one may read like the problem statement while the other needs explaining. Choosing between them is a judgment made against the input limits and the people who will maintain the code. Finding the first one-time user with count() and with a dict Speed, memory and clarity side by side A rule for choosing