A worked example: two files that fill a disk exactly
The prompt: you have a list of file sizes, and a disk with exactly capacity free. Find two different files whose sizes add up to exactly capacity. Return their positions in the list, or None if no pair does. Here, sizes = [700, 250, 1200, 300, 450, 800] and capacity = 1500.
Clarify first. Say it out loud. Two different files, but they may have the same size. If several pairs work, any one will do, and here we return the first pair to complete as we read left to right. A single file of exactly 1500 isn't a pair.
The obvious answer. Try every pair: two nested loops, O(n²) time, O(1) extra memory. Say it, give its cost, and move on. It's the baseline the interviewer wants you to beat.
Each file's partner has a fixed size, so one pass with a dict finds it
For each file, its partner's size is fixed: need = capacity - size. So the question for each file is whether you've already seen a file of size need. That's a seen-lookup, with one twist: you need the partner's position, not just whether it exists. So it's a dict from size to position, not a set.
def fill_exactly(sizes, capacity):
# size -> position of a file that size
seen = {}
for j, size in enumerate(sizes):
need = capacity - size
if need in seen:
return seen[need], j
seen[size] = j
return None
print(fill_exactly([700, 250, 1200, 300, 450, 800], 1500))
Capacity 1500, and the sizes are 700, 250, 1200, 300, 450, 800. Which pair of positions fills it exactly first?