A useful code explanation tells the listener what the function promises, why the algorithm meets that promise and what assumptions its cost analysis needs. Reading each line aloud rarely accomplishes that.
Start by resolving an ambiguity that could change the answer. Then choose the simplest method you can justify.
Original practice problem
Return the first repeated item in a sequence. Before coding, ask what “first” means. For [a, b, b, a], the first second-occurrence encountered is b. The earliest original position belonging to an item that eventually repeats is a.
Assume the intended answer is b: scan from left to right and return the item whose repeat is encountered first. Also assume hashable elements with the intended equality behavior.
def first_repeat(items):
seen = set()
for item in items:
if item in seen:
return (True, item)
seen.add(item)
return (False, None)
The boolean makes a repeated None distinguishable from no repeat. That small interface choice is worth explaining if arbitrary hashable values are accepted.
State the invariant
Before each iteration, seen contains exactly the distinct items in the already processed prefix. If the current item is in that set, it repeats an earlier item. Since the scan returns at the first such encounter, the function meets the selected meaning of “first.” If no return occurs, every item appeared only once.
This connects the data structure to correctness. “A set is fast” explains a performance motivation, not why the answer is right.
Give the cost with assumptions
With ordinary expected constant-time hash-set operations, the scan takes expected O(n) time and up to O(n) additional storage. Hash behavior and equality costs matter to the model. Unhashable elements require a changed interface or algorithm; they should not fail unexpectedly if the contract promised to accept them.
Walk through revealing cases
An empty sequence returns no repeat. [4,4] returns four on the second item. [None,None] returns (True,None). [a,b,b,a] distinguishes the two meanings of first. A list containing unhashable nested lists exposes the input-type assumption.
If the interviewer clarifies a different interpretation, identify the changed requirement and revise the method. Do not defend code that solves the old problem.
This is original practice, not a reported employer question. For broader preparation, read the Quant Career Field Guide or use the engineering transition worksheet.
Read before choosing
Open the actual pages.
11 sample pages, including complete explanations. No email address or account required.
Open the PDF previewPreview page 4 of 11. Use Enlarge page for a closer view. When the page is focused, use left and right arrows to change pages.
