Clarify the input and output contract
Why you care
The expensive bugs on the job are contract bugs: the feed has duplicates, the "sorted" file is sorted per partition only, downstream needed original row positions. A coding round is the same thing in miniature, and the interviewer watches whether you notice. Employer guides tell candidates to clarify before coding; none publishes a checklist, so this list is editorial. This card is first because every later pattern has a precondition, and preconditions are facts about the input.
Explain like I'm 5
A tailor who cuts cloth before asking who the suit is for will cut something lovely that does not fit. A good tailor measures, repeats the numbers back ("forty-two chest, needed Friday?") and only then picks the cloth. The measurements are the contract; the cloth is the pattern.
Core concept
The rule: restate the input and output contract in your own words before you name a pattern.
- Size and value bounds set the cost budget (Translate constraints into feasible complexity).
- Order: sorted by what key, for the whole input?
- Duplicates and empties: can values repeat; can the input be empty?
- Mutation: may you modify the input? In-place patterns need permission.
- Output shape: which order, positions or values? If positions matter, sorting first destroys the answer unless indices travel along.
- Exact or approximate, streaming or batch: each can change the whole design.
Decision rule: ask if one answer would make you pick or reject an algorithm; skip if you can state a default ("I'll assume 32-bit values and read-only input"). Four to six questions is normal. Ten with no restatement is stalling; silence then code is guessing. Finish with a two-sentence restatement including one duplicate example and one empty case.
Minimal example Sorting first loses positions
vals = [30, 10, 20, 10]
srt = sorted(vals)
print(srt, srt.index(30), vals.index(30))
print(sorted(enumerate(vals), key=lambda p: p[1]))
print(len(set(vals)), len(vals))[10, 10, 20, 30] 3 0
[(1, 10), (3, 10), (2, 20), (0, 30)]
3 4The 30 moves from index 0 to 3. Pairs keep the original index. The set collapsed 4 elements into 3.
In production A contract you can interrogate
Write the contract as data. Unanswered fields are the questions you have not asked. The domain is a batch of settlement amounts; nothing is solved, only the front end.
from dataclasses import dataclass, fields
@dataclass
class Contract:
max_n: int | None = None
value_range: tuple | None = None
sorted_input: bool | None = None
duplicates: bool | None = None
empty_ok: bool | None = None
may_mutate: bool | None = None
keep_indices: bool | None = None
exact: bool | None = None
streaming: bool | None = None
def open_questions(c):
return [f.name for f in fields(c) if getattr(c, f.name) is None]
def check_input(c, data):
problems = []
if not data and c.empty_ok is False:
problems.append("empty input")
if c.max_n is not None and len(data) > c.max_n:
problems.append(f"n={len(data)} exceeds {c.max_n}")
if c.value_range is not None:
lo, hi = c.value_range
if any(not lo <= x <= hi for x in data):
problems.append(f"value outside {lo}..{hi}")
if c.sorted_input and any(a > b for a, b in zip(data, data[1:])):
problems.append("not sorted")
if c.duplicates is False and len(set(data)) != len(data):
problems.append("duplicates")
return problems
c = Contract(max_n=5, value_range=(0, 1000), sorted_input=True,
duplicates=False, empty_ok=False)
print(open_questions(c))
for batch in ([], [5, 9, 9], [1, 2, 3, 4, 5, 6], [10, 5], [3, -1]):
print(batch, check_input(c, batch) or "ok")
partial = Contract(max_n=5)
print(check_input(partial, [1, 2, 3]) or "ok", check_input(partial, []) or "ok")['may_mutate', 'keep_indices', 'exact', 'streaming']
[] ['empty input']
[5, 9, 9] ['duplicates']
[1, 2, 3, 4, 5, 6] ['n=6 exceeds 5']
[10, 5] ['not sorted']
[3, -1] ['value outside 0..1000', 'not sorted']
ok okFour fields are still None: four questions unasked. A partly filled contract checks only what you have answered, so the last line prints ok ok.
In your world
The situation
Your nightly job reads settlements.csv from S3. A ticket says "dedupe the merchant rows", so you write a set() pass and Jenkins goes green.
What actually breaks
Nobody asked whether reconciliation needs one row per merchant or per merchant per day. The set collapsed 48,213 rows into 9,870 and finance's variance report was off by 38,343 rows for a week.
What you'd do on Monday
Put the contract in the ticket as five lines (key, order, empties, mutability, expected output count), then assert it on the first run:
expected_out = len({(r["merchant_id"], r["day"]) for r in rows})
assert len(result) == expected_out, f"contract says {expected_out}, got {len(result)}"Imagine you work at Razorpay
The numbers
4,000,000 events/hour ÷ 3,600 s ≈ 1,111 events/s. "Distinct paying customers today" means up to 96M events and, say, 20M distinct ids. An exact Python set of 20M string ids is about 20M × ~100 bytes ≈ 2 GB per worker.
What the Scenario-A answer does here
Writing the contract down still works. What breaks is the batch reading of "distinct" (collect everything, then set()): the contract never said whether the answer must be exact or live.
What flips at this scale
Exact versus approximate and streaming versus batch now choose the design. If a small error is fine, an approximate counter with kilobytes of state replaces 2 GB. If it must be exact, shard by customer-id hash: 8 shards × 2.5M ids ≈ 250 MB each.
The trade-off you'd defend
I would ask exact-or-approximate first and, if approximate is acceptable, defend the small sketch over the exact set, trading a bounded error for state that survives restarts.
Illustrative figures; not Razorpay-published numbers.
Gotchas
Sorting before checking position requirements
Your values are right, but the expected output wanted original positions and yours differ.
sorted() reorders elements, so positions come from the sorted copy.
Ask "positions or values?" first. If positions matter, sort enumerate(vals) or avoid sorting.
A set silently drops duplicates
len(set(xs)) is 3 where len(xs) is 4 and your result count is low, with no error.
A set keeps one copy per equal key, which is wrong if the contract counts duplicates separately.
Ask whether duplicates are meaningful; use collections.Counter when multiplicity matters.
Tricky questions
Yes, a thorough candidate leaves nothing open.
Only questions that change the algorithm are worth asking. State defaults for the rest. Ten questions with no restatement look like stalling.
Scenario question
You're handed: "Given a list of numbers, report the two biggest values." You have thirty seconds before you code. What do you ask?
Model answer
I would ask four things. How large can the list be? Can it have fewer than two elements, and what do I return? Do two equal 9s count as the two biggest? Is it in memory or a stream? Then I restate the contract aloud. The trade-off is half a minute against building the wrong design.
Interview corner
CommonWhat do you do first when given a coding problem?
TrickThe input says "sorted". What else do you check?
Experience checkTell me about a time an assumption about data broke a job.
Memory hook
Measure the customer before you cut the cloth.
Say the contract back before you name any pattern.
Self-check
Name three contract answers that can make a pattern illegal.
Sortedness, mutation permission and index preservation.
Why carry
(index, value)pairs when sorting?A sort moves elements, so original positions are lost unless stored beside each value.
When may you skip a clarifying question?
When you can state a default and every plausible answer leads to the same algorithm.
Invent three one-line problem statements from your ETL work. Fill all nine Contract fields for each and write inputs that break the answered ones. Paste the contracts and the check_input output. About 20 minutes.