The first thing a strong candidate learns about Python interviews for data engineering roles is that the room is not really testing Python. It is testing what happens the morning after the code ships, when a file arrives twice as large as anyone expected, when a third of its rows carry a timestamp in the wrong format, and when the job that loaded it has to run again without loading everything twice. A sorting algorithm can be rehearsed. Judgement about messy data cannot, and it is judgement — about memory, about ordering, about what a rerun does to a table people already trust — that separates the engineer a team wants on call from the engineer whose scripts work beautifully on a laptop and quietly corrupt a warehouse in production.

That difference shapes the questions themselves. Where a software engineering interview might ask you to reverse a structure or find a pair that sums to a target, a data engineering interview hands you something deceptively ordinary: a log file too big to open, a feed in which the same customer appears four times with four different addresses, a join that returns more rows than either side put in. The task sounds clerical until you notice the traps folded inside it. Loading the whole file works, until memory runs out halfway through a load that has already written half its output. Keeping the first copy of a record works, until the business rule was to keep the latest. Sorting works, until two records share a timestamp and the tie decides which address a bill is sent to. Interviewers choose these problems because each compresses a week of production pain into twenty minutes, and because the wrong answer is rarely a syntax error. It is a plausible answer that would have passed a small test and failed at scale, in silence.
There is a second, quieter test underneath the first. Data pipelines are rerun — after failures, after late files arrive, after an upstream team republishes a day of data with corrections, and after someone in finance asks why Tuesday does not reconcile. Code that cannot be run twice safely is not finished, however elegant it looks, and interviewers listen for that instinct in every answer: Did the candidate close the file? Did they think about what happens when the input is empty, malformed, or ten times larger than the sample? Did they choose the structure that stays flat in memory over the one that merely reads more cleanly? Candidates who do well tend to narrate those choices as they go, not as decoration but as the substance of the work.
How this set is organised. This set works through ten questions in the order a pipeline itself tends to break: reading data without exhausting memory; removing duplicates without discarding the wrong copy; joining datasets whose keys do not quite agree; grouping and aggregating without distorting the result; handling dates, time zones and late-arriving records; coping with missing and malformed values; calling external sources politely and recoverably; making a load idempotent so a rerun is a repair rather than a duplication; choosing between row-by-row code and vectorised operations; and testing and logging well enough that the next failure announces itself instead of hiding. Each question is given in full, with a complete worked answer, an examination of the answer that most often fails, the follow-up that usually comes next, and a harder variant. The first two questions carry more weight than their simplicity suggests.
Question 1: Stream a Large File Line by Line Instead of Loading It Into Memory
The question
You are given access-log records from a busy web service. A single day produces a file of roughly eight gigabytes, far larger than the memory available to the job that processes it, and your task is to count how many requests returned each HTTP status code and to surface any lines that do not parse, without the job’s memory use growing with the size of the file.
A short sample of the file looks like this, one request per line:
The sample data.
2026-11-28T09:14:02Z GET /products 200 412
2026-11-28T09:14:03Z GET /products/184 200 388
2026-11-28T09:14:04Z POST /checkout 502 97
2026-11-28T09:14:05Z GET /search?q=linen 404 121
2026-11-28T09:14:05Z GET /products 200 405
MALFORMED LINE THAT SHOULD NOT COUNT
2026-11-28T09:14:07Z GET /account 301 64
Each well-formed line carries five fields: a timestamp, a method, a path, a status code, and a response size in bytes, separated by spaces. The interviewer asks you to write Python that reads a file in this format, yields each line as a structured record, counts the status codes, counts malformed lines rather than crashing on the first one, and reports the result. Then, usually with a slight smile, they ask the real question: what happens when the file is not six lines, or six thousand, but sixty million?
What they are really testing
The surface skill is file handling, but the interviewer is probing four deeper instincts, and a strong answer names all four while solving the problem rather than listing them in the abstract.
Memory as a design constraint. The central judgement is whether you reach instinctively for a structure whose size depends on the input. Reading an entire file into a list is wrong here not because lists are bad, but because the file was chosen to outgrow the machine. The processing should hold one line, or a small fixed number of lines, at a time, so doubling the input doubles the running time but leaves the memory footprint essentially unchanged. That property — flat memory against growing input — is the whole point of the exercise.
Separation of reading from counting. Candidates who write one long block that opens a file, splits strings, converts numbers and updates a counter in a single breath usually produce code that works and code that cannot be reused or tested when the follow-up changes the question. Separating turning lines into records from aggregating those records lets the same reader feed a status counter today and a per-path summary tomorrow. Interviewers notice the seam, or its absence.
Respect for failure inside the data. A malformed line in a production log is not an edge case invented to embarrass you; it is Tuesday. The question specifies that malformed lines should be counted and set aside rather than allowed to end the run, because a job that dies on line 4,000,001 after an hour has wasted the hour and left its output in an unknown state.
Ownership of resources. A file that is opened must be closed, including when something goes wrong partway through, and the idiomatic way to guarantee that is a context manager. Leaving this out rarely breaks the sample. It breaks, eventually, in a long-running service that leaks handles until the operating system refuses to open anything else.
The full worked answer
The cleanest solution has three small pieces: a generator that reads and parses, a counter that consumes it, and a main block that prints the result. Start with the generator, because it carries the idea the whole question turns on.
from collections import Counter
from pathlib import Path
def read_log_records(path):
"""Yield one structured record per well-formed line in the log file.
Malformed lines are yielded as None so the caller can count them
without this reader needing to know how they will be reported.
"""
with Path(path).open("r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
parts = line.split()
if len(parts) != 5:
yield None
continue
timestamp, method, request_path, status_text, size_text = parts
try:
status = int(status_text)
size = int(size_text)
except ValueError:
yield None
continue
yield {
"timestamp": timestamp,
"method": method,
"path": request_path,
"status": status,
"size": size,
}
Three decisions in those few lines deserve to be said out loud. First, iterating over the file object itself — `for line in handle` — asks Python to produce one line at a time; at no point does the file, or a list of its lines, exist in memory as a whole. Second, the function contains `yield` rather than `return`, which makes it a generator function: calling it does not run its body at all, but returns a generator object that runs only as far as the next `yield` each time the caller asks for another value, pausing there and resuming when asked again. Third, the `with` block guarantees the file is closed when the generator is exhausted or abandoned, releasing the hndle even if thecnsumer stops early
.The consumer can then stay deliberately small:
def summarise_log(path):
status_counts = Counter()
malformed = 0
total_bytes = 0
for record in read_log_records(path):
if record is None:
malformed += 1
continue
status_counts[record["status"]] += 1
total_bytes += record["size"]
return status_counts, malformed, total_bytes
if __name__ == "__main__":
counts, malformed, total = summarise_log("access.log")
for status in sorted(counts):
print(status, counts[status])
print("malformed", malformed)
print("total_bytes", total)Run against the sample above, saved as access.log, the output is:
200 3
301 1
404 1
502 1
malformed 1
total_bytes 1487
Walk through why that output is right, because interviewers often check the reasoning rather than the arithmetic. Of the seven lines, one is malformed and yields `None`, so it raises the malformed count and contributes nothing else. The remaining six parse cleanly: three carry status 200, and one each carries 301, 404 and 502. The byte total adds only the six well-formed responses: 412 + 388 + 97 + 121 + 405 + 64, which is 1,487. A `Counter` is the right aggregate here because it grows with the number of distinct status codes, not with the number of lines, so it stays tiny even when the file doesnot.
The contrast the interviewer is waiting for is with a list comprehension, and it is worth drawing explicitly, because the comprehension is not foolish code — in many settings it is the better code. Consider the alternative:
records = [parse(line) for line in open("access.log")]That single line builds, in memory, a list containing every parsed record at once. For a configuration file, or any input you know to be small and need to traverse several times, sort, index or pass around, materialising a list is entirely reasonable and often clearer. Lists can be measured with `len`, sliced and revisited; a generator can do none of those things, because it produces each value once and then it is gone. The trade-off is therefore not a rule but a judgement. When the input is bounded and you need random access or repeated passes, take the list. When the input is unbounded, or larger than the memory you can count on, or you need each item only once in order, take the generator and accept a single forward pass. The file here was specified at eight gigabytes precisely to force that judgement, and naming the conditions under which you would choose the other way is what turns a correct answer into a convincing ne.
The common wrong answer
The answer that fails this question most often looks efficient and reads well, which is exactly why it is dangerous. It begins by reading the whole file, either with `read().splitlines()` or with a list comprehension, then loops over the resulting list to parse and count. On the sample it produces the correct output, quickly, and the candidate moves on satisfied. The failure is visible not in the output but in the memory profile: the list holds every line, and if the code parses before counting, it then holds every record as well, so for a stretch the program carries the input twice. Pointed at the real file, the job slows as the machine begins swapping, then dies — and because it dies partway through a load, it can leave a partially written output that a downstream step may mistake for a complete one. This is the single most common way real log jobs fail, and the fix costs nothing once he habit is formed.
Two smaller faults usually travel with it: opening the file without a context manager, and letting the first malformed line end the run — or, at the opposite extreme, wrapping the whole loop in a broad `except that swallows genuine programming mistakes too.
The follow-up they ask next
The follow-up is usually a change of scale in a different direction:s of files rather than one, and you are asked how the code adapts. The reassuring answer is that it barely changes, which is the payoff for separating reading from counting. A thin wrapper can yield from several generators in turn:
def read_many(paths):
for path in paths:
yield from read_log_records(path)Because `yield from` delegates to each sub-generator in sequence, memory stays flat across the whole set — finishing one file and closing it before the next begins. The counter that consumes `read_many` does not need to know whether it was fed one path or four hundred. If the interviewer then asks about a file that never ends, such as a log being tailed, the same shape holds for as long as lines keep arriving, with the caveat that the summary can then only be reported periodically, since thereis no end.
A harder variant
The harder variant adds a second problem in disguise: return the ten paths with the highest total bytes served, from the same eight-gigabyte file, still without loading it into memory. The trap is to collect every path’s records and sort them, which rebuilds the memory problem in a new place. The way through is to notice that aggregating by path collapses the data as you go, just as counting by status did. A dictionary mapping each path to its running byte total grows with the number of distinct paths, not with the number of lines, and for most services that remains a small fraction of the request count.
from collections import defaultdict
def top_paths_by_bytes(path, limit=10):
bytes_by_path = defaultdict(int)
for record in read_log_records(path):
if record is None:
continue
bytes_by_path[record["path"]] += record["size"]
ranked = sorted(
bytes_by_path.items(), key=lambda item: item[1], reverse=True
)
return ranked[:limit]The honest caveat, and interviewers reward it, is that this depends on the cardinality of the key. If paths contain unique identifiers — a different session token in every URL, say — then the number of distinct paths approaches the number of lines and the dictionary stops being small. In that case, normalise the path first, stripping identifiers into a route template such as `/products/{id}`, before aggregating, or reach for an external store and say plainly that exact answers now cary a real cost.
Question 2: Deduplicate Records by a Composite Key, Keeping the Latest Update
The question
A customer feed arrives several times a day from an upstream system, and it does not send only the customers who changed. It resends overlapping slices of the whole population, so the same customer, at the same site, may appear many times in a single batch — sometimes identically, sometimes with a newer address, and occasionally with an older record arriving after a newer one because two source systems published out of order. Before the batch can be loaded, it must be reduced to one record per customer per site, and the survivor must be the most recently updated version.
The identity of a record is not a single column. A customer may legitimately appear at two sites, so the key is composite: customer identifier and site identifier together identify the thing that must be unique. A small version of the batch makes the problem concrete:
The sample data.
Record one. Customer C104, site north, updated 2026-11-20T08:30:00, email mara@example.com, plan standard
Record two. Customer C104, site north, updated 2026-11-27T11:15:00, email mara.new@example.com, plan standard
Record three. Customer C104, site south, updated 2026-11-21T09:00:00, email mara@example.com, plan premium
Record four. Customer C209, site north, updated 2026-11-25T14:40:00, email dev@example.com, plan standard
Record five. Customer C209, site north, updated 2026-11-25T14:40:00, email dev@example.com, plan enterprise
Record six. Customer C104, site north, updated 2026-11-22T10:05:00, email mara.mid@example.com, plan standard
The interviewer asks for two things. First, plain Python that returns one record per composite key — records one, two and six compete, and record two must win because its update time is the latest of the three, even though record six arrives after it in the file. Second, an explanation of records four and five, which share a key and an identical timestamp but disagree on plan, and of what your code does about them — because “keep the latest” does not, by itself, decide that case.
What they are really testing
Deduplication sounds like housekeeping, and interviewers use it precisely because candidates underestimate it. Underneath the tidy instruction sit four questions about how you think, each mapping to a failure that happens regularly in production pipelines.
Whether you understand what a key is. The first test is whether you treat identity as the business defines it. Deduplicating on customer alone would destroy record three, a legitimate second site, with no error raised while the data quietly went missing. Deduplicating on every field would keep all six records, because no two are wholly identical. Getting the composite key right — customer and site together, nothing more and nothing less — is the decision on which everything else depends.
Whether “latest” means latest, or merely last seen. The second test is subtler and is the heart of the question. File order is not time order, as record six demonstrates: it arrives last and was written earlier than record two. Code that simply overwrites, or keeps the final occurrence, returns the stale address confidently. An interviewer wants the timestamp compared explicitly, so the survivor is chosen by when the change happened rather than by where it landed in a batch.
Whether you plan for ties. The third test is what you do when the stated rule runs out. Records four and five tie exactly, and any real feed will eventually produce a tie — two systems writing in the same second, a timestamp truncated to the day, a republished record with a field corrected and its timestamp untouched. A candidate who has never considered the case will let it be decided by input order without noticing a decision was made. A candidate who names the ambiguity and picks a deterministic rule prevents a class of irreproducible bugs, where rerunning the same job on a differently ordered file produces a different warehouse.
Whether you know where deduplication belongs. The fourth test appears in the follow-up, but strong candidates raise it early: deduplicating at the wrong point in a pipeline, particularly on the wrong side of a join, does not merely waste effort. It changes the answer.
The full worked answer
Begin with plain Python, because it forces every decision into the open. The natural structure is a dictionary keyed by the composite key, holding the best record seen so far for each key. Each new record challenges the incumbent and replaces it only if it wins under the rule you have stated.
from datetime import datetime
PLAN_RANK = {"standard": 1, "premium": 2, "enterprise": 3}
def parse_timestamp(value):
return datetime.fromisoformat(value)
def deduplicate_latest(records):
"""Return one record per (customer_id, site_id), latest update wins.
Ties on updated_at are broken by source_priority when present,
then by plan precedence, so the result does not depend on input order.
"""
best = {}
for record in records:
key = (record["customer_id"], record["site_id"])
incumbent = best.get(key)
if incumbent is None:
best[key] = record
continue
challenger_time = parse_timestamp(record["updated_at"])
incumbent_time = parse_timestamp(incumbent["updated_at"])
if challenger_time > incumbent_time:
best[key] = record
elif challenger_time == incumbent_time:
challenger_rank = (
record.get("source_priority", 0),
PLAN_RANK.get(record["plan"], 0),
)
incumbent_rank = (
incumbent.get("source_priority", 0),
PLAN_RANK.get(incumbent["plan"], 0),
)
if challenger_rank > incumbent_rank:
best[key] = record
return list(best.values())Feed the six sample records through it, as dictionaries with the fields shown, and the result is three records:
C104 / north -> 2026-11-27T11:15:00, mara.new@example.com, standard
C104 / south -> 2026-11-21T09:00:00, mara@example.com, premium
C209 / north -> 2026-11-25T14:40:00, dev@example.com, enterpriseEach line of that output is a small argument. The north record for C104 is the one dated November 27, not the one dated November 22 that arrived later in the file, because the comparison was made on the parsed timestamp rather than on position. The south record survives untouched, because the composite key treats it as a different thing from the north record. And the C209 record carries the enterprise plan, not because the business necessarily prefers that plan, but because the tie needed a rule and the one chosen here — after a source_priority field if the source provides one, a stated plan precedence, enterprise above premium above standard — resolves the same way regardless of input order. Note that the precedence has to be stated: sorting plan names alphabetically would keep standard, because s comes after e, which is a reminder that a tie-break borrowed from whatever ordering happens to be nearby is still an accident, just a quieter one. In the room, say clearly that this tie-break is a placeholder for a business decision: perhaps corrections always come from one named system, which should win, or perhaps tied records should be flagged for review rather than resolved silently. Any explicit, deterministic rule beats an accidental one.
Two details are worth drawing out. Parsing the timestamp into a datetime before comparing, rather than comparing raw strings, matters once formats vary: strings sort correctly only while every value shares exactly the same format and offset, an assumption that breaks the first time one source writes 2026-11-27T11:15:00+00:00 and another writes 2026-11-27T11:15:00Z. And returning list(best.values()) makes no promise about ordering; if the caller needs sorted output, so successive runs produce diffable files, sort it explicitly.
The same logic in pandas is shorter, and it is the version most working data engineers would write, but its brevity conceals the identical decisions, which is why interviewers often ask for it second. The pattern is to sort by the tie-breaking columns and the timestamp, then keep the last row in each key group:
import pandas as pd
def deduplicate_latest_pandas(frame):
frame = frame.assign(
plan_rank=frame["plan"].map(PLAN_RANK).fillna(0)
)
ordered = frame.sort_values(
by=["updated_at", "plan_rank"],
ascending=[True, True],
kind="mergesort",
)
deduped = ordered.drop_duplicates(
subset=["customer_id", "site_id"],
keep="last",
)
return (
deduped.drop(columns=["plan_rank"])
.sort_values(by=["customer_id", "site_id"], kind="mergesort")
.reset_index(drop=True)
)Read it as the dictionary version wearing different clothes. The subset argument is the composite key, stated in one place. Sorting ascending by updated_at and then calling drop_duplicates with keep=”last” makes the latest record the survivor — the sort places it last within its group, and keep=”last” retains exactly that row. The secondary sort by plan_rank — the plan precedence from the plain version, mapped into a column — plays the role of the tie-break: when two rows share a timestamp, the higher-precedence plan sits last and is kept, which reproduces the enterprise outcome above. Using a stable sort, requested here with kind=”mergesort”, ensures rows equal on all sort keys keep their relative order. The final sort by the key columns gives the output a defined order that tests can assert and reviewers can read.
The pandas version carries one hazard the plain version does not. Sorting requires the timestamps to be genuine datetimes, or at least uniformly formatted strings; if the column arrives as mixed-format text, the sort will succeed, produce an answer, and be wrong. Converting first with pd.to_datetime, and deciding what to do with values that fail to parse, is part of the answer rather than a refinement of it. There is also a scale consideration: the dictionary version streams, holding one incumbent per key, while the pandas version holds the whole frame and sorts it. For a batch that fits in memory, that is a fair price for clarity; for one that does not, the streaming version is the honest recommendation.
The common wrong answer
The most frequent failing answer is a single line — drop_duplicates on the key with its default settings, or a dictionary built by looping and assigning unconditionally — and it fails in a way small tests rarely catch. drop_duplicates by default keeps the first occurrence, so on unsorted input it preserves the oldest record and discards the update, the precise opposite of the requirement. The unconditional dictionary assignment keeps the last record in file order, which on the sample returns the November 22 address for C104 at north — neither the first nor the latest, merely the last to arrive. Both versions return exactly three records, so a test that counts rows passes. Both return plausible-looking data, so a test that checks for empty fields passes. Only a test that checks which record survived catches the error. Deduplication bugs are almost never about the number of rows; they are about the identity of the rows that remain.
Two related patterns fail the same way: deduplicating on customer alone, which produces a tidy table and a support ticket weeks later when the second site’s orders stop reconciling, and dropping exact duplicate rows only, which removes true resends but leaves every genuine update as a separate row.
The follow-up they ask next
The follow-up that matters most is a question of placement: does it change anything whether you deduplicate before or after joining this feed to another table — say, a sites table that adds region and timezone to each record, or an orders table that attaches purchases to customers? It changes a great deal, and walking through why is usually the moment the interview turns in a candidate’s favour.
Deduplicate before the join, and each key contributes exactly one record, so each key produces at most one joined row per matching row on the other side. The latest address is the one that acquires a region; the stale copies never reach the join at all. Deduplicate after the join, and the duplicates multiply first. If the sites table itself held two rows for a site — a current row and a historical one, a common pattern — then three versions of a customer at that site joined against two versions of the site produce six rows, from which a later deduplication must now choose, and the timestamp it chooses on describes the customer record, not the site record, so the survivor may pair the newest address with the older region. No single step looks wrong; each did something defensible, and the composition is incorrect.
The general rule is that a dataset should be reduced to the grain its key promises before it is combined with anything else, because joins preserve and multiply whatever grain they are given. There is a legitimate exception: if the information needed to decide which duplicate is correct lives in the other table — if only the sites table records which source system is authoritative for a given site — then the join must happen first so the tie-break can be made at all, and the deduplication that follows must be written with unusual care. The point is not that one order is always right. It is that the order is a decision with consequences for the answer.
A harder variant
The harder variant removes the comfort of a batch. Records now arrive as a continuous stream of updates and corrections, the table already holds millions of customers, and you are asked how deduplication works when you cannot reprocess everything each time, and when a correction may arrive for a record loaded last week.
The outline of a sound answer has three parts. First, keep the same rule, but apply it incrementally: each incoming record is compared against the stored record for its composite key, and replaces it only if it wins under the timestamp and tie-break rule — the dictionary challenge from the worked answer, with the dictionary replaced by the target table, and the comparison performed as an upsert. Second, protect the comparison from the stream’s disorder: because a delayed older record must not overwrite a newer stored one, the update has to be conditional on the incoming timestamp being later, enforced in the write itself rather than checked and then written in two steps that another writer can slip between. Third, keep the losers. Retaining superseded versions in a separate history, with the time each was received and replaced, is what makes the current table explainable — when a figure is disputed, the question is never only what the value is now, but what it was when a report ran.
The key code for the conditional write, expressed against a simple in-memory store so the logic stands alone, looks like this:
def apply_update(store, record):
key = (record["customer_id"], record["site_id"])
existing = store.get(key)
if existing is None:
store[key] = record
return "inserted"
incoming_time = parse_timestamp(record["updated_at"])
existing_time = parse_timestamp(existing["updated_at"])
if incoming_time > existing_time:
store[key] = record
return "updated"
if incoming_time < existing_time:
return "ignored_stale"
return "needs_tie_break"Returning a word for what happened, rather than writing silently, is the detail to emphasise as you close. A stream in which a third of arrivals are being ignored as stale is telling you something about an upstream publisher, and it can only tell you if each decision is counted and reported. Deduplication is not the removal of rows but a series of decisions that should leave evidence behind.
Question 3: Parse Messy JSON-Lines Into Flat Records — and Quarantine the Bad Rows Instead of Crashing
The question
You are handed a file that arrived overnight from a partner system. The real file has about two million lines, is roughly 900 megabytes, and cannot simply be loaded and trusted. Each line is supposed to be one JSON object describing a completed order. Most lines look like this:
{"order_id": 101, "customer": {"id": 7, "tier": "gold"}, "amount": 129.50, "currency": "USD", "items": 3}
{"order_id": 102, "customer": {"id": 8, "tier": "silver"}, "amount": 42.00, "currency": "USD", "items": 1}Some lines do not. In the sample, line 3 is truncated in the middle of a string, line 4 is valid JSON but its amount is the word “unknown” instead of a number, line 5 is missing the customer object entirely, line 6 is a blank line, and line 7 carries an extra nested object nobody warned you about. The downstream table wants flat records — one row per order, with columns order_id, customer_id, customer_tier, amount, currency and items — and the data team wants to know, for every rejected line, which line it was and exactly why.
Write Python that produces the flat records for the good lines, writes the bad lines to a quarantine file with line numbers and reasons, and reports how many lines were good and how many were bad. The job must never crash because of one bad line. If the whole file is bad, it should still finish, report zero good records, and hand back a quarantine file that explains the disaster line by line. That last sentence is the one candidates miss: they write a parser for the file they wish they had been given, not the file that arrives in production at three in the morning.
What they are really testing
This is not, at its core, a JSON question. Anyone can call a JSON parser. What the interviewer is listening for is whether you treat untrusted input as untrusted — whether your first instinct is to isolate failure to the smallest possible unit, preserve evidence about what failed, and keep the rest of the pipeline moving. Four skills are being probed.
The first is failure isolation. In a line-delimited format, the natural unit of failure is one line. A try block that wraps the whole file turns one corrupt line into a total outage. A try block that wraps one line turns the same corruption into one quarantined record and a job that completes.
The second is the difference between two kinds of bad data. A line can fail to parse at all — it is not JSON, or it is cut off — and that is a syntax failure. Or it can parse perfectly and still be unusable: a required field is absent, a field has the wrong type, a value is out of range. That is a schema failure. Conflating the two produces quarantine files that say “invalid” two thousand times. Separating them produces a file an engineer can act on: syntax failures point at the producer’s writer, schema failures point at a contract that changed or was never enforced.
The third is flattening as a deliberate transformation. A generic recursive flattener will work on the sample and then surprise you in production, when a nested key collides with a top-level key or an unexpected object explodes into forty sparse columns. Writing out the fields you expect, by name, is more code and far fewer surprises — and it makes the extraction code and the validation code the same code.
The fourth is accounting. A pipeline that silently drops bad rows is worse than one that crashes, because the crash at least announces itself. The counts at the end — lines read, records written, rows quarantined — are what let an operator decide whether a run is healthy. Two bad rows in two million is noise. Two hundred thousand is an incident, and the summary should make that obvious even though, mechanically, the job “succeeded.”
There is a performance subtext too: 900 megabytes should be streamed one line at a time, not read into a single string, and good records should be written out as they go rather than accumulated into a list of two million dictionaries.
The full worked answer
Start by stating the contract in code: which fields are required, and what type each must have. Then process the file line by line — parse inside a narrow try block, validate and flatten as a second step, and never let an exception for one line escape the loop.
import json
REQUIRED_FIELDS = ("order_id", "customer", "amount", "currency", "items")
def flatten_order(record):
"""Return a flat dict for one parsed order, or raise ValueError."""
for field in REQUIRED_FIELDS:
if field not in record:
raise ValueError(f"missing required field: {field}")
customer = record["customer"]
if not isinstance(customer, dict):
raise ValueError("field 'customer' must be an object")
if "id" not in customer:
raise ValueError("missing required field: customer.id")
if "tier" not in customer:
raise ValueError("missing required field: customer.tier")
amount = record["amount"]
# bool is a subclass of int in Python, so exclude it explicitly.
if isinstance(amount, bool) or not isinstance(amount, (int, float)):
raise ValueError(
f"field 'amount' must be a number, got {type(amount).__name__}"
)
if amount < 0:
raise ValueError(f"field 'amount' must not be negative, got {amount}")
order_id = record["order_id"]
if isinstance(order_id, bool) or not isinstance(order_id, int):
raise ValueError(
f"field 'order_id' must be an integer, got {type(order_id).__name__}"
)
items = record["items"]
if isinstance(items, bool) or not isinstance(items, int):
raise ValueError(
f"field 'items' must be an integer, got {type(items).__name__}"
)
return {
"order_id": order_id,
"customer_id": customer["id"],
"customer_tier": customer["tier"],
"amount": float(amount),
"currency": record["currency"],
"items": items,
}
def parse_json_lines(lines):
"""Parse an iterable of raw lines.
Returns (good_records, quarantine), where quarantine is a list of
dicts with line_number, reason and raw content for each bad line.
"""
good = []
quarantine = []
for line_number, raw_line in enumerate(lines, start=1):
line = raw_line.strip()
if not line:
quarantine.append({
"line_number": line_number,
"reason": "blank line",
"raw": raw_line.rstrip("\n"),
})
continue
try:
record = json.loads(line)
except json.JSONDecodeError as exc:
quarantine.append({
"line_number": line_number,
"reason": f"invalid JSON: {exc.msg} (column {exc.colno})",
"raw": raw_line.rstrip("\n"),
})
continue
if not isinstance(record, dict):
quarantine.append({
"line_number": line_number,
"reason": f"top-level value must be an object, got {type(record).__name__}",
"raw": raw_line.rstrip("\n"),
})
continue
try:
good.append(flatten_order(record))
except ValueError as exc:
quarantine.append({
"line_number": line_number,
"reason": f"schema error: {exc}",
"raw": raw_line.rstrip("\n"),
})
return good, quarantineFor a real file, the same function streams it — a file object is an iterable of lines — and the caller writes both lists out as JSON-lines and prints the accounting. In production, note, you would write each record as it is processed rather than holding the lists; the loop body does not change, only where its results go.
Run against the interviewer’s seven-line sample, the in-memory version gives a result you can check by eye:
sample = [
'{"order_id": 101, "customer": {"id": 7, "tier": "gold"}, "amount": 129.50, "currency": "USD", "items": 3}',
'{"order_id": 102, "customer": {"id": 8, "tier": "silver"}, "amount": 42.00, "currency": "USD", "items": 1}',
'{"order_id": 103, "customer": {"id": 9, "tier": "gol',
'{"order_id": 104, "customer": {"id": 10, "tier": "gold"}, "amount": "unknown", "currency": "USD", "items": 2}',
'{"order_id": 105, "amount": 19.99, "currency": "USD", "items": 1}',
'',
'{"order_id": 106, "customer": {"id": 11, "tier": "bronze"}, "amount": 7.25, "currency": "USD", "items": 1, "promo": {"code": "X1"}}',
]
good, quarantine = parse_json_lines(sample)
for record in good:
print(record)
print(f"good: {len(good)}")
print(f"bad: {len(quarantine)}")
for entry in quarantine:
print(entry["line_number"], "-", entry["reason"])Expected output:
{'order_id': 101, 'customer_id': 7, 'customer_tier': 'gold', 'amount': 129.5, 'currency': 'USD', 'items': 3}
{'order_id': 102, 'customer_id': 8, 'customer_tier': 'silver', 'amount': 42.0, 'currency': 'USD', 'items': 1}
{'order_id': 106, 'customer_id': 11, 'customer_tier': 'bronze', 'amount': 7.25, 'currency': 'USD', 'items': 1}
good: 3
bad: 4
3 - invalid JSON: Unterminated string starting at (column 49)
4 - schema error: field 'amount' must be a number, got str
5 - schema error: missing required field: customer
6 - blank lineWalk through the result line by line. Lines 1 and 2 parse, validate and flatten cleanly: the nested customer object is unpacked into customer_id and customer_tier, and the amount is normalised to a float so an integer amount elsewhere does not create a mixed-type column downstream. Line 3 fails inside the JSON parser itself, before any schema logic runs, and the reason captures the parser’s message and column. Line 4 parses — it is perfectly legal JSON — and fails only at validation, which is exactly why the two failure kinds are handled in two places. Line 5 fails on the missing-field sweep, and its reason names the field. Line 6 is a judgment call worth stating: a blank line is counted as bad rather than silently skipped, because a file that suddenly contains ten thousand blank lines is telling you something about the producer. Line 7 is the quiet success: it carries an extra nested promo object the target table does not want, and because the flattener extracts named fields instead of expanding everything it finds, the extra data is ignored and no stray promo_code column appears downstream.
Two details repay a sentence each. The check against booleans looks fussy until you remember that in Python True is an instance of int with value 1, so without it ”amount”: true would land in the table as 1.0. And enumeration starts at 1, not 0, because line numbers will be read by a human opening the source file in an editor, and editors count from one.
The common wrong answer
The most common wrong answer is short, confident and catastrophic:
import json
records = []
with open("orders.jsonl") as f:
for line in f:
record = json.loads(line)
records.append({
"order_id": record["order_id"],
"customer_id": record["customer"]["id"],
"customer_tier": record["customer"]["tier"],
"amount": record["amount"],
"currency": record["currency"],
"items": record["items"],
})It works beautifully on the happy path, which is why candidates trust it. On the sample it dies on line 3 with an unhandled decode error, having written nothing and preserved no evidence of which line killed it — the two good records already processed are lost with it. In production the overnight job fails, the table is stale by morning, and the on-call engineer gets a traceback saying a string was unterminated somewhere in a 900-megabyte file.
The autopsy has four findings. First, there is no error handling, so the unit of failure is the entire file. Second, candidates who do add a try block often wrap the whole loop instead of one iteration — the same failure in a costume, with a tidier traceback. Third, direct indexing means the first missing field raises a KeyError that says nothing about which line caused it; catching that with a bare except: and continuing builds the opposite disaster, a job that silently swallows every error, including bugs in its own code, and reports success over an empty table. Fourth, there is no accounting: nobody can tell whether it processed two million lines or twelve.
A subtler wrong answer comes from stronger candidates: a generic recursive flattener used as a substitute for a contract. It handles line 7 by inventing a column and a nested address by inventing twelve, and when the producer renames a field the downstream schema changes without anyone deciding it should. The fix is a change of posture more than of syntax: assume every line is guilty until it parses and validates, give each failure a place to go, and count everything.
The follow-up they ask next
The follow-up is usually about scale and evidence: “Your quarantine file — what exactly do you put in it, and what do you do when the bad rows turn out to be ten percent of the file?”
Answer both halves. The quarantine record should contain the line number, a reason specific enough to act on, and the raw line itself, unaltered — the reason is your interpretation, the raw bytes are the evidence the producer team will replay. Write the quarantine file in the same line-delimited JSON format as the input, so it can be counted, filtered by reason and, after the producer fixes their writer, re-run through the same parser as a recovery file. A quarantine file in the right format is not a graveyard; it is a reprocessing queue.
On proportion, the code does not change but the operational response does. The summary should break bad rows down by reason, and a sensible pipeline sets an alert threshold — commonly between one and five percent — above which the run is flagged for review and the load into the production table may be held even though the parse succeeded. Ten percent bad with one dominant reason almost always means the contract changed upstream. Offer the small addition that produces the breakdown:
from collections import Counter
reason_counts = Counter()
# inside the loop, wherever a row is quarantined:
reason_counts[reason.split(":")[0]] += 1Report the counter alongside the totals. It is the difference between “the job had errors” and “the job had 41,208 schema errors, nearly all a missing customer object” — the second sentence gets the right team paged.
A harder variant
The interviewer now changes the ground rules: “The nesting is not fixed. Different record types nest to different depths, keys repeat at different levels, and lists appear inside objects. Flatten any record generically — but a list should stay together as a single value, not exploded into one column per element. And two keys that flatten to the same name must not silently overwrite each other.”
This tests whether you can write the generic flattener correctly now that it is genuinely required — recursion, path tracking and collision awareness — while keeping the quarantine machinery wrapped around it.
import json
def flatten_generic(record, parent_key="", sep="_", out=None):
"""Recursively flatten nested dicts.
Lists are kept as single values. If two paths flatten to the
same key, the later one is stored under a suffixed name rather
than overwriting the first.
"""
if out is None:
out = {}
for key, value in record.items():
flat_key = f"{parent_key}{sep}{key}" if parent_key else str(key)
if isinstance(value, dict):
flatten_generic(value, flat_key, sep=sep, out=out)
else:
target = flat_key
suffix = 2
while target in out:
target = f"{flat_key}_{suffix}"
suffix += 1
out[target] = value
return outTest it on something with real nesting, a list and a deliberate collision, where a top-level address_city meets an address object that also contains a city:
record = {
"order_id": 201,
"address_city": "top-level value",
"address": {"city": "nested value", "zip": "60601"},
"customer": {"id": 7, "contact": {"email": "a@example.com"}},
"tags": ["priority", "gift"],
}
print(flatten_generic(record))Expected output:
{'order_id': 201, 'address_city': 'top-level value', 'address_city_2': 'nested value', 'address_zip': '60601', 'customer_id': 7, 'customer_contact_email': 'a@example.com', 'tags': ['priority', 'gift']}Three things to explain. First, the recursion carries the path so far in parent_key, which turns customer, then contact, then email into the single column customer_contact_email — depth stops mattering because each level adds only its own segment. Second, a list is not a dictionary, so it is stored whole; exploding lists into positional columns creates a schema whose width depends on the longest list in the file, which no downstream table can survive. Third, the collision loop is the part most flatteners omit. Without it, whichever city value is visited second silently destroys the first. Suffixing is not the only defensible policy — raising an error and quarantining the record is stricter — but silently overwriting is the one indefensible policy.
Wrap the generic flattener in the same per-line try block, quarantine writes and counters as the main answer. The parsing machinery and the resilience machinery are separate concerns: the transformation can get ten times harder and the loop around it should not change by a line.
Question 4: Count Event Frequencies and Find the Top-K Users — Without Holding Everything in Memory
The question
The second file is bigger: an event log, one JSON object per line, each with a user_id and an event type, running to tens of millions of lines — far more than you would want to load or turn into a list. A trimmed sample looks like this:
{"user_id": "u104", "event": "login", "ts": "2026-12-01T09:14:02Z"}
{"user_id": "u077", "event": "click", "ts": "2026-12-01T09:14:03Z"}
{"user_id": "u104", "event": "click", "ts": "2026-12-01T09:14:05Z"}
{"user_id": "u231", "event": "login", "ts": "2026-12-01T09:14:07Z"}
{"user_id": "u104", "event": "purchase", "ts": "2026-12-01T09:14:11Z"}
{"user_id": "u077", "event": "login", "ts": "2026-12-01T09:14:12Z"}Two questions are asked. First, how many events did each user produce? Second — the deliverable the product team actually wants — who are the ten most active users, the top K with K set to 10, and how many events does each have? If two users are tied at the boundary, say how you handle the tie, because the team has been burned by a report that quietly picked one tied user over another for no reason anyone could reconstruct.
The constraint is stated plainly: do not hold everything in memory. The interesting part is not whether you can count. It is what, exactly, you claim you are not holding — because counting every distinct user has a memory cost of its own, and an answer that pretends otherwise will be pressed until it admits it.
What they are really testing
This question separates candidates who have processed data larger than a laptop’s comfort zone from candidates who have only ever processed samples of it. The counting is trivial on a small file; the difficulty is entirely in the constraints.
First, do you stream the input? Reading line by line, updating a running count and discarding the line costs memory proportional to nothing about the file’s length. Building a list of tens of millions of user IDs costs memory proportional to everything. On the sample both print the same answer, which is the trap: choose the approach whose correctness does not depend on the file staying small.
Second, do you understand what still grows? A counter with one entry per distinct user is unavoidable in an exact solution — to know a user seen first on line thirty million is new, you must remember every user seen before. Its memory grows with distinct users, not with events, and in most real logs those differ by orders of magnitude: tens of millions of events from four hundred thousand users is a counter that fits comfortably. Stating that distinction unprompted is the strongest signal in this question. If distinct users genuinely cannot fit either, the honest continuation is an approximate structure, an external sort or a database aggregation — naming that escape hatch earns more credit than any cleverness with the counter.
Third is the top-K selection: algorithmic judgment, not library recall. Sorting every user to keep ten sorts hundreds of thousands of entries unnecessarily. A heap retaining only the ten best does the selection in one pass with memory proportional to K — but it is more code, and for a hundred distinct users it buys nothing. The mature answer knows both and picks deliberately.
Fourth is ties, which sounds like pedantry and is actually reproducibility. When the tenth and eleventh users both have 4,812 events, any top-10 list contains an arbitrary choice, and different tools make it differently and silently. Deciding a tie policy — a secondary ordering, or reporting all tied users — and stating it is what the interviewer is listening for.
The full worked answer
The counting core is a single streaming pass with a Counter, which is a dictionary specialised for exactly this job: missing keys start at zero, and the update reads the way the operation feels.
import json
from collections import Counter
def count_users(lines):
"""Stream lines, return a Counter of events per user_id."""
counts = Counter()
skipped = 0
for raw_line in lines:
line = raw_line.strip()
if not line:
skipped += 1
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
skipped += 1
continue
user_id = record.get("user_id")
if user_id is None:
skipped += 1
continue
counts[user_id] += 1
return counts, skippedNotice that the defensive habits travel with it: blank and malformed lines are skipped and counted rather than allowed to kill a thirty-million-line run near the end, and the skip count is returned so the caller can judge whether the file was clean. On the sample the counts are easy to verify by eye — u104 three times, u077 twice, u231 once — and you should say so before running anything.
With the counts in hand, the top-K step has two honest implementations: the library shortcut first, then the heap version, with a statement of when each is right.
# Version A: the Counter's own shortcut.
top_a = counts.most_common(10)
# Version B: a bounded heap, via heapq.
import heapq
top_b = heapq.nlargest(10, counts.items(), key=lambda pair: pair[1])Both return a list of (user_id, count) pairs in descending order of count. On the sample:
lines = [
'{"user_id": "u104", "event": "login"}',
'{"user_id": "u077", "event": "click"}',
'{"user_id": "u104", "event": "click"}',
'{"user_id": "u231", "event": "login"}',
'{"user_id": "u104", "event": "purchase"}',
'{"user_id": "u077", "event": "login"}',
]
counts, skipped = count_users(lines)
print(counts)
print("skipped:", skipped)
print(heapq.nlargest(2, counts.items(), key=lambda pair: pair[1]))Expected output:
Counter({'u104': 3, 'u077': 2, 'u231': 1})
skipped: 0
[('u104', 3), ('u077', 2)]Under the surface, most_common does the respectable thing for small K: recent Python versions implement it with heap selection rather than a naive full sort, so reaching for it is not a performance sin. Still, spell out the general trade-off. A full sort of N distinct users costs on the order of N log N comparisons and produces a complete ordering — wasteful if the top ten is all anyone will read, exactly right if the next question turns out to be the top hundred or a full ranked table. Heap selection costs on the order of N log K: each entry is compared against a heap holding at most K candidates, so as K stays small and N grows, the saving grows. With ten slots and ninety users the difference is unmeasurable and the sort is clearer code. The rule: when K is much smaller than the number of distinct keys, select with a heap; when K is a substantial fraction of the keys, or you need the full ordering anyway, sort.
What nlargest maintains internally is a bounded heap of the K best candidates seen so far, which is why its memory stays proportional to K however many distinct users stream past. The heap is a min-heap, for a reason worth explaining: the smallest of your current top ten sits at the top, because that is the entry a newcomer must beat, and the one evicted when one does. Note also what tuple ordering does for ties. Entries are (count, user_id) pairs, so equal counts fall through to the user ID, and the heap keeps the lexicographically larger IDs among the tied group. That is deterministic, but it is not meaningful — a strong answer says so rather than dressing an accident of tuple ordering up as a policy. The defensible policies are to impose a stated secondary key the business cares about — first to reach the count, lower user ID, alphabetical order — and implement it explicitly, or, where exclusion at the boundary would mislead, to return everyone tied at the cutoff and label the result honestly as eleven names for a top-10 report. With most_common or nlargest keyed only on count, tie order follows first-seen order in the counter — again deterministic, again worth stating rather than discovering in a dispute months later.
For completeness, the same job in pandas, because half the teams you join will ask for it in that form:
import pandas as pd
def top_k_pandas(path, k=10):
events = pd.read_json(path, lines=True)
counts = events["user_id"].value_counts()
return counts.head(k)value_counts counts occurrences of each distinct value in a column and returns them already sorted descending, so the top K is simply the head of the result. On a small or medium file already destined for further analysis in a data frame — joins against a user table, filtering by event type, grouping by day — this is the right tool: two readable lines, inside the library the rest of the analysis uses. Its cost is the mirror image of the streaming version’s virtue: read_json loads the whole file into memory, every column and row, before a single count is taken — on the thirty-million-line file, exactly what the constraint forbade. The bridge, worth naming if pushed, is chunked reading: read_json with a chunk size yields the file in pieces, each chunk’s value_counts is added into a running counter, and memory collapses back to the distinct-user footprint while the analysis stays in pandas idiom.
The common wrong answer
The canonical wrong answer loads everything and sorts it:
import json
user_ids = []
with open("events.jsonl") as f:
for line in f:
user_ids.append(json.loads(line)["user_id"])
user_ids.sort()
# ... followed by a hand-rolled run-length count, or a sort of
# (count, user) pairs built from the full list ...
top10 = sorted(
{(u, user_ids.count(u)) for u in set(user_ids)}, reverse=True
)[:10]The autopsy finds three injuries. The first is the list itself: every event’s user ID retained for the whole run, so memory grows with the number of events — the one quantity the question said was enormous. The real file exhausts the machine or pushes it into swapping and turns a two-minute job into a forty-minute one that still dies. The second is subtler: calling a counting method inside a comprehension over the whole collection rescans it once per distinct user. Four hundred thousand users rescanning thirty million entries is an accidental quadratic, presenting in production as a job that handled the test file instantly and ran all night on the real one. The third is the full sort used as a selection tool — survivable, but the mark of reaching for the familiar tool instead of the fitting one.
A fourth wrong answer is wrong in the opposite direction. A candidate who has heard streaming is virtuous sometimes keeps only ten counters — incrementing a user already in the ten, starting a counter when a slot is free. It is incorrect. A user whose events are spread evenly may never occupy an early slot, have most events go uncounted while the slots are held by users merely busy in the first hour, and finish with a true total higher than several of the reported ten. Exact top-K requires exact counts, and exact counts require remembering every distinct key — or an approximate algorithm with stated error bounds, which is a different conversation. The candidate who explains why the tempting version fails understands the problem.
The follow-up they ask next
The follow-up almost always changes one word of the question: “Now do it per event type — top ten users for purchases, top ten for logins — and tell me what changes.” Or its close cousin: “The file no longer fits the distinct-user assumption either. Four hundred million distinct users. Now what?”
Take the per-type version first: nothing about the streaming pass changes except the key. Count pairs — event type and user ID as a tuple — or keep one counter per event type in a dictionary of counters. The second form is clearer and makes the final step trivial, since each counter goes to the same top-K function unchanged:
from collections import Counter, defaultdict
counts_by_event = defaultdict(Counter)
for raw_line in lines:
record = json.loads(raw_line)
counts_by_event[record["event"]][record["user_id"]] += 1
for event_type, counter in counts_by_event.items():
print(event_type, counter.most_common(10))Memory now grows with distinct user-and-type combinations: a user who logs in, clicks and purchases occupies three entries instead of one. For a handful of event types that multiplier is trivial; the general principle is that the multiplier is the cardinality of whatever you add to the key.
The oversized version has no exact in-memory answer, and the correct response is to say so, then offer the real options. If the data can go through a system built for this — a database, a warehouse, a distributed data frame — the aggregation belongs there. If it must stay in one Python process, write counted pairs out in sorted runs to disk and merge them, trading disk and time for memory. And if an approximate answer is acceptable — for a “most active users” dashboard it often is — sketch-based algorithms track heavy hitters in fixed memory with bounded error, at the price of possibly missing a user near the cutoff. Presenting those three honestly beats pretending the counter scales forever.
A harder variant
The final twist: “The events arrive as a live stream that never ends, one parsed event at a time. Every hour, on demand, report the current top ten. You may not restart the counting, and you may not keep the events themselves. Show me the shape of that program.”
The shape is a small class that owns the counter and the tie policy, with one method for consuming an event and one for reporting, and keeps nothing else:
from collections import Counter
class TopKTracker:
"""Consume events one at a time; report the top K users on demand."""
def __init__(self, k=10):
self.k = k
self.counts = Counter()
self.total = 0
def consume(self, event):
user_id = event.get("user_id")
if user_id is None:
return
self.counts[user_id] += 1
self.total += 1
def top(self):
# Descending count; ascending user_id among ties.
ranked = sorted(
self.counts.items(),
key=lambda pair: (-pair[1], pair[0]),
)
return ranked[: self.k]Sorting by negative count gives descending activity; sorting by user ID as the second element gives ascending, deterministic order among ties; slicing takes the top K. Drive it like this:
tracker = TopKTracker(k=2)
stream = [
{"user_id": "u104", "event": "login"},
{"user_id": "u077", "event": "click"},
{"user_id": "u104", "event": "click"},
{"user_id": "u231", "event": "login"},
{"user_id": "u104", "event": "purchase"},
{"user_id": "u077", "event": "login"},
]
for event in stream:
tracker.consume(event)
print("total events:", tracker.total)
print("top:", tracker.top())Expected output:
total events: 6
top: [('u104', 3), ('u077', 2)]Explain the three decisions being scored. First, events are never stored — consume extracts the one field it needs, increments, and lets the event be discarded, so a year-long stream costs the same memory on its last day as on its first, apart from growth in distinct users. Second, reporting is a separate, repeatable operation that reads the counter without disturbing it: the hourly report is a snapshot, not a checkpoint, and counting continues from exactly where it was. Third, the tie policy is written in the sort key, in the class, where the next engineer will find it. If asked about the cost of sorting on every report, concede it and offer the bounded heap from the main answer as the replacement for that one method — the rest of the design survives unchanged. That is the note to end on: the tools are small, and none of them is the point. The point is knowing what each one costs, what it quietly assumes, and where it breaks.
Question 5: The Merge That Quietly Inflated Revenue
The question
You own the nightly orders pipeline for a mid-sized retailer. This morning the finance report shows revenue up sharply overnight, but order volume is flat, no campaign ran, and the warehouse shipped nothing unusual. Your manager hands you a small extract that reproduces the problem exactly and asks you to explain what happened, prove it, and fix it so it cannot happen silently again.
The transactions extract has eight rows, one per order line. The customers extract has six rows but only five distinct customers.
import pandas as pd
transactions = pd.DataFrame({
"txn_id": [101, 102, 103, 104, 105, 106, 107, 108],
"customer_id": [1, 1, 2, 3, 4, 5, 5, 2],
"amount": [50.0, 30.0, 120.0, 75.0, 200.0, 45.0, 60.0, 90.0],
})
customers = pd.DataFrame({
"customer_id": [1, 2, 3, 4, 5, 5],
"customer_name": ["Asha Patel", "Ben Okafor", "Carla Ruiz",
"Dev Nair", "Erin Walsh", "Erin Walsh"],
"segment": ["retail", "retail", "wholesale",
"retail", "retail", "retail"],
})The analyst who built the report ran one line — transactions.merge(customers, on=”customer_id”, how=”left”) — and expected eight rows totalling 670.00. She got ten rows totalling 775.00. No error, no warning, a green pipeline. Explain, with numbers, where the two extra rows and the extra 105.00 came from. Show how you would catch the problem before the merge, how you can make pandas itself refuse a merge like this, and how you would repair the customers table. One condition: do not just delete rows until the total looks right. Show your working.
What they are really testing
This is not a syntax question — everyone in the room knows how to call merge. The interviewer is testing whether you understand what a join computes underneath the friendly API, and whether you distrust a join that ran without complaint.
First, cardinality. A join is not a lookup. A lookup promises one answer per key; a join promises every combination of matching rows. Two left rows and two right rows for one key produce four joined rows, not two. Candidates who picture a merge as a spreadsheet lookup will blame “the data” vaguely. Candidates who picture it as a per-key product of row counts will predict the ten rows before running anything, and name the exact customer who caused them.
Second, diagnostic discipline. The dangerous pipeline bugs are the silent ones. A merge that raises an error costs ten minutes; a merge that quietly inflates revenue costs a quarter of bad decisions. The interviewer wants a repeatable routine: count rows before and after, check whether keys you assumed were unique actually are, and reconcile a measure that should be invariant across the join. Revenue before a fact-to-dimension join and revenue after it must be identical. The moment they disagree, the join is guilty until proven innocent.
Third, whether you use the seatbelts pandas provides. The validate argument exists for exactly this failure mode, and indicator=True for auditing what a merge actually did. Many working engineers have used neither. Showing the exact error validate=”many_to_one” raises on this data, and why that is the right contract for a fact-to-dimension join, separates a strong answer from a correct-looking one. Finally, how you repair a dimension table: here the duplicated rows are identical, so deduplication is safe — but only after you have looked. In the follow-up the duplicates will disagree, and the candidate whose whole method is “drop duplicates” will destroy real information.
The full worked answer
State the expectation first, because the diagnosis hangs on it. Transactions are the fact table: eight order lines, each belonging to exactly one customer. Customers are the dimension: descriptive attributes, exactly one row per customer. Joining facts to a dimension must never change the fact row count or any measure on the facts.
Step 1: Do the row-count maths by hand. For each key, the joined row count is left_count × right_count, because every left row pairs with every matching right row.
Customer 1: 2 transactions × 1 customer row = 2 rows
Customer 2: 2 × 1 = 2 rows
Customer 3: 1 × 1 = 1 row
Customer 4: 1 × 1 = 1 row
Customer 5: 2 × 2 = 4 rows
Total: 2 + 2 + 1 + 1 + 4 = 10 rows — the ten the analyst saw, predicted exactly. When the right side is truly unique, right_count is 1 everywhere and the product collapses to the left count, which is why healthy fact-to-dimension joins preserve rows. The money follows the same maths: customer 5’s transactions, 45.00 and 60.00, each appear twice, so customer 5 contributes 210.00 instead of 105.00. The inflation is exactly one extra copy of that subtotal: 105.00. Now confirm against the machine, printing the frame sorted by transaction so the duplication is visible row by row rather than hidden inside an aggregate:
merged = transactions.merge(customers, on="customer_id", how="left")
print("rows:", len(transactions), "->", len(merged))
print("amount:", transactions["amount"].sum(), "->", merged["amount"].sum())
print(merged.sort_values("txn_id").to_string(index=False))Expected output:
rows: 8 -> 10
amount: 670.0 -> 775.0
txn_id customer_id amount customer_name segment
101 1 50.0 Asha Patel retail
102 1 30.0 Asha Patel retail
103 2 120.0 Ben Okafor retail
104 3 75.0 Carla Ruiz wholesale
105 4 200.0 Dev Nair retail
106 5 45.0 Erin Walsh retail
106 5 45.0 Erin Walsh retail
107 5 60.0 Erin Walsh retail
107 5 60.0 Erin Walsh retail
108 2 90.0 Ben Okafor retailTransactions 106 and 107 each appear twice, wearing identical names and segments — which is why nobody spotted them in a spreadsheet.
Step 2: Prove the key is duplicated, on the inputs, before merging. Never diagnose from the output alone when you can interrogate the inputs. Two checks should precede every consequential merge:
print("rows:", len(customers),
" distinct keys:", customers["customer_id"].nunique())
print("key is unique:", customers["customer_id"].is_unique)
dup_keys = customers["customer_id"].value_counts()
print(dup_keys[dup_keys > 1])
mask = customers["customer_id"].duplicated(keep=False)
print(customers[mask].to_string(index=False))Expected output:
rows: 6 distinct keys: 5
key is unique: False
customer_id
5 2
Name: count, dtype: int64
customer_id customer_name segment
5 Erin Walsh retail
5 Erin Walsh retailEach line earns its place. is_unique is the yes-or-no contract check. value_counts filtered above 1 shows the scale — one duplicated key is a data-entry slip; four thousand is a broken upstream load. And duplicated(keep=False) marks every member of a duplicate set, not just the later copies, so you can judge whether the rows agree; with the default keep=”first” the first Erin Walsh row stays hidden, and a harmless exact duplicate is indistinguishable from two conflicting records. Here the rows are identical in every column, which is what makes deduplication safe — a conclusion you are entitled to only after looking. Check the left side too: transactions[“txn_id”].is_unique should be True; a duplicated transaction ID would mean the fact table itself double-counts orders, a different and worse bug.
Step 3: Make pandas enforce the contract with validate. Checks you run by eye in a notebook evaporate when the code moves into a 2 a.m. schedule. validate turns the assumption into an assertion that travels with the merge:
transactions.merge(customers, on="customer_id", how="left",
validate="many_to_one")MergeError: Merge keys are not unique in right dataset; not a many-to-one mergeThe vocabulary maps straight onto Step 1’s cardinality language. ”many_to_one” says the left may repeat keys freely — many transactions per customer is the point of a fact table — but the right must hold at most one row per key. ”one_to_one” fits two tables both unique on the key. ”one_to_many” is the mirror image, for deliberate fan-out such as joining customers to their transactions, where row growth is intended and should equal the transaction count. ”many_to_many” checks nothing at all; occasionally legitimate for bridge tables, it more often confesses that nobody thought about cardinality. In a pipeline, let the MergeError fail the run loudly: a failed job is an inconvenience; a wrong number delivered confidently to finance is an incident.
Step 4: Audit the join with indicator=True. Validation says the merge was legal; the indicator says what it did, including the unmatched-key problem validation does not cover:
audited = transactions.merge(
customers.drop_duplicates(subset="customer_id"),
on="customer_id", how="outer", indicator=True)
print(audited["_merge"].value_counts())Expected output:
_merge
both 8
left_only 0
right_only 0
Name: count, dtype: int64On this clean data everything matched. In the full nightly data, right_only rows are customers who bought nothing in the period — harmless for revenue, essential for churn. left_only rows are the dangerous ones under the original left join: they keep their amounts, so the total reconciles, but they carry empty names and segments and fall out of every segment breakdown, so the parts stop adding to the whole — the second most common join bug in reporting, right behind fan-out itself.
Step 5: Repair the dimension, then re-verify everything. Only now — duplicates inspected, found identical — deduplicate, on the key, explicitly:
customers_clean = (customers
.drop_duplicates(subset="customer_id", keep="first")
.reset_index(drop=True))
assert customers_clean["customer_id"].is_unique
final = transactions.merge(customers_clean, on="customer_id",
how="left", validate="many_to_one")
assert len(final) == len(transactions)
assert final["amount"].sum() == transactions["amount"].sum()
print(len(final), final["amount"].sum())Expected output:
8 670.0Close by naming the four guards — the deliverable that outlives the incident: key uniqueness asserted on the dimension, the merge validated, row count preserved, measure total preserved. Any one would have caught this bug. Then raise the upstream question: why did the extract emit Erin Walsh twice? A customer table joined to an address table holding two addresses will do exactly this; the durable fix may belong in the extract query, and the checks are the guardrail until it lands.
The common wrong answer
It comes in three flavours. The first is the shrug: “there was a duplicate, so I dropped duplicates on the merged frame.” That works here only because the fanned-out rows are fully identical. The moment duplicate dimension rows differ in any attribute — two segments, two spellings of a name — the output rows are no longer identical, drop_duplicates keeps them all, and the candidate declares the data unfixable. It also mops the symptom downstream while every other report on the same customers table stays broken. Deduplicate the dimension, on its key, before the join — never mop the fact table after it.
The second is blaming the join type: the analyst should have used an inner join, or a different how. She should not. An inner join here produces the same ten rows and the same 775.00; it merely also discards unmatched rows. Join type governs which unmatched rows survive; cardinality governs how matched rows multiply. Confusing the two tells the interviewer the candidate memorised a cheat sheet instead of building a model of what a join computes.
The third is fixing the total instead of the rows — dividing by two, or deduplicating the dashboard on transaction ID. Each produces the right headline while leaving a corrupted intermediate table that poisons the next calculation: an average order value over ten rows, a segment split that double-counts one customer, a buyer count of six where five exist. Interviewers probe for this by asking, immediately, for the average transaction value in the fixed table. The row-level fix answers 83.75 without hesitation. The total-level fix kept ten rows and answers 77.50, and the game is up.
The follow-up they ask next
Almost always: “Your two Erin Walsh rows were identical, so dropping one was easy. What if they disagree — one says retail, the other wholesale, with different signup dates?”
The brief worked answer: do not pick one silently. Surface the conflict, decide by a stated rule, and record the decision. First find which columns actually vary within a key; constant columns are safe, varying columns are the decision:
customers2 = pd.DataFrame({
"customer_id": [5, 5],
"customer_name": ["Erin Walsh", "Erin Walsh"],
"segment": ["retail", "wholesale"],
"signup_date": ["2023-04-11", "2024-01-19"],
})
print(customers2.groupby("customer_id").nunique().gt(1).to_string(index=False))Expected output:
customer_name segment signup_date
False True TrueWith a genuine conflict, the resolution is a business rule, not a pandas trick. Most-recent-record-wins is the usual default for slowly changing attributes, implemented transparently as sort_values(“signup_date”).drop_duplicates(“customer_id”, keep=”last”), with the losing rows written to a quarantine table for the data owner. If the attribute drives pricing or statutory reporting, escalate instead of guessing: a customer who is somehow both retail and wholesale is a question for whoever owns the customer master, and the pipeline should quarantine, never coin-flip. Deduplication is a policy decision with a one-line implementation, and the interview is testing whether you know which half of that sentence matters.
A harder variant
“Now it happens at scale, in the other direction. You join a shipments table of 1,000,000 rows to a products table of 40,000 rows to attach product weights, and the result has 1,040,000 rows. The products table holds only 39,850 distinct product IDs. Find every cause, quantify each one, and return exactly 1,000,000 shipments whose total weight you can defend.”
The routine is the same, executed without panic. First, the arithmetic of blame: a duplicated product ID only inflates the join for products that actually appear in shipments, each contributing left_count × (right_count − 1) extra rows. Attribute all 40,000 extra rows to named keys; if they do not sum to exactly 40,000, a second cause is hiding.
right_counts = products["product_id"].value_counts()
dup_ids = right_counts[right_counts > 1].index
left_counts = shipments["product_id"].value_counts()
extra = sum(left_counts.get(pid, 0) * (right_counts[pid] - 1)
for pid in dup_ids)
print("duplicated product IDs:", len(dup_ids))
print("extra rows explained: ", extra)Second, repair by policy, never on faith at a million rows. Split duplicated IDs into exact duplicates, which collapse safely, and conflicting duplicates, which go to quarantine ranked by shipment impact:
dup_rows = products[products["product_id"].isin(dup_ids)]
is_exact = dup_rows.duplicated(subset=list(products.columns), keep=False)
quarantine_ids = set(dup_rows.loc[~is_exact, "product_id"])
products_clean = (products[~products["product_id"].isin(quarantine_ids)]
.drop_duplicates(subset="product_id", keep="first"))
fixed = shipments.merge(products_clean, on="product_id", how="left",
validate="many_to_one", indicator=True)
print(fixed["_merge"].value_counts())
print("rows:", len(fixed), "of", len(shipments))Shipments whose products sit in quarantine return as left_only with empty weights — visible and countable, rather than silently doubled or guessed. The defensible total weight is computed over matched rows only and reported with its coverage: a number, its denominator, and its known gap. The variant is not testing bigger code; it is testing whether the routine survives scale: count, attribute every extra row to a named cause, repair by policy, quarantine what policy cannot settle, and validate the merge so the failure can never again be silent.
Question 6: One dropna() Deleted Half the Deliveries
The question
A pipeline ingests delivery events for a grocery logistics company. Each row is one delivery, and the columns matter very differently. delivery_id and promised_date must always be present. delivered_at is empty for deliveries still in transit. customer_rating is optional — customers rate roughly three deliveries in five. driver_note is free text the driver may or may not leave. And units_delivered is the number billing charges on, so a missing value there is an alarm, not a gap to paper over.
Told to “clean the data before the analysis,” a junior engineer added one line: clean = events.dropna(). On the twelve-row extract below, that line deletes six of the twelve rows, including completed deliveries billing needs — without raising any error. The analysis that follows is not wrong in its arithmetic. It is wrong in its population: it describes only deliveries that happened to have every optional field filled in, a group systematically different from the deliveries as a whole.
import pandas as pd
import numpy as np
events = pd.DataFrame({
"delivery_id": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
"customer_id": [21, 22, 21, 23, 24, 22, 25, 23, 26, 24, 27, 21],
"promised_date": ["2026-11-02"] * 12,
"delivered_at": ["08:14", "09:02", None, "07:48", "10:31", None,
"11:05", "08:57", None, "09:44", "12:20", "08:03"],
"units_delivered": [12, 8, np.nan, 20, 5, np.nan,
14, 9, np.nan, 11, 6, 17],
"customer_rating": [5.0, 4.0, np.nan, 4.0, np.nan, np.nan,
3.0, 5.0, np.nan, 5.0, np.nan, 4.0],
"driver_note": ["gate code used", None, None, "left at porch", None,
None, " lift broken ", "", None, "fragile - ok",
None, " "],
})What they are really testing
Missing-value questions look like housekeeping and are actually about judgement. “Missing” is not one thing. A value can be missing because it does not exist yet — the delivery has not happened; because nobody was asked — the rating was optional; or because something broke — a completed delivery with no unit count points to a scanner or an upstream system failing. The three situations have three different correct responses: keep the row, analyse what exists with its denominator stated, and escalate the defect. A blanket dropna treats all three identically, which is a polite way of saying it understands none of them.
They are also testing whether you measure before you cut. The professional reflex is isna().mean() before any deletion: missingness as a proportion, per column, printed and read. A column 2 percent missing invites a different conversation from one 40 percent missing — and rows with complete data are rarely a random sample of all rows. Customers who rate deliveries differ from customers who do not. Complete-case analysis does not just shrink the data; it tilts it.
Third, whether you know how nulls move through everyday operations. groupby drops null keys by default. Aggregations skip nulls — mostly, and the exceptions have shipped real bugs. A comparison against a null is never true, so filters quietly exclude the very rows you may be hunting. Finally, dtype literacy: in real extracts, missing arrives in disguise — a true NaN in a float column, a None in an object column, an empty string, a string of spaces, occasionally the word “NULL” typed by another system. isna catches the first two and walks straight past the rest. The driver_note column here is the trap laid for exactly that.
The full worked answer
Step 1: Profile the missingness before touching a row.
profile = pd.DataFrame({
"missing": events.isna().sum(),
"pct_missing": (events.isna().mean() * 100).round(1),
"dtype": events.dtypes.astype(str),
})
print(profile.to_string())
print("rows:", len(events),
" complete rows:", events.notna().all(axis=1).sum())Expected output:
missing pct_missing dtype
delivery_id 0 0.0 int64
customer_id 0 0.0 int64
promised_date 0 0.0 object
delivered_at 3 25.0 object
units_delivered 3 25.0 float64
customer_rating 5 41.7 float64
driver_note 6 50.0 object
rows: 12 complete rows: 6Read it column by column. Identity and schedule columns are complete — the ingestion contract holds there. delivered_at is missing on exactly the three in-transit deliveries, 3, 6 and 9, and units_delivered is missing on those same three rows, which is coherent: nothing has been delivered, so there is no count and no time. Two columns missing together, on the same rows, with a business explanation, is structural missingness — information, not dirt. customer_rating is missing on five of twelve, 41.7 percent, matching the stated reality that rating is optional. And only six rows are complete across every column, which is the whole story of the junior engineer’s line: default dropna keeps a row only if every column is present, so it kept half the extract — and on the full data, with more optional fields, it kept far less. The notebook did not crash. It started describing an unrepresentative minority of deliveries as if they were the operation. Profile jointly as well as marginally: the in-transit rows share their missingness pattern exactly, while ratings are missing across completed and in-transit rows alike — and that difference is what decides the handling.
Step 2: Separate the populations before deciding anything. Stop thinking of the frame as one dataset with holes. It is two populations plus a defect queue, and one split organises every later decision:
in_transit = events[events["delivered_at"].isna()]
completed = events[events["delivered_at"].notna()].copy()
print("in transit:", len(in_transit), " completed:", len(completed))
print("completed but units missing:",
int(completed["units_delivered"].isna().sum()))Expected output:
in transit: 3 completed: 9
completed but units missing: 0On this extract the defect queue is empty: every completed delivery has its unit count, and every missing count belongs to a delivery that has not happened yet. Say why you ran the check anyway. In the full data it earns its keep — a completed delivery with no units_delivered is a billing hole, routed to a quarantine frame with its delivery ID intact, counted and reported. Never averaged away, never filled with a plausible number: inventing units bills a customer for a guess, and dropping the row means never billing them and never knowing. Quarantine is the only honest third option.
Step 3: Give each column its own rule, and say each rule out loud. For units_delivered: keep in-transit rows with their nulls intact — the null is the truthful value — quarantine completed rows that lack it, and impute nowhere. If a downstream model needs a numeric placeholder for in-transit rows, it creates one in its own feature frame, never written back over the source of truth.
For the sparse optional column, customer_rating at 41.7 percent missing: drop no rows for it, impute nothing for descriptive reporting, and always state the denominator. The average rating is a statement about the customers who rated, phrased that way:
rated = completed.dropna(subset=["customer_rating"])
print("ratings available:", len(rated), "of", len(completed), "completed")
print("mean rating (rated only):", round(rated["customer_rating"].mean(), 2))Expected output:
ratings available: 7 of 9 completed
mean rating (rated only): 4.29If a later modelling step truly requires a filled rating column, the defensible fill is a stated constant plus an indicator column — rating_was_missing set wherever the fill was applied — so a model can learn that absence itself carries signal: unrated deliveries are not average deliveries. Argue explicitly against bare mean imputation: it manufactures neutral deliveries out of silence, shrinks the variance, and makes invented rows indistinguishable from real observations in every later audit.
For the contract columns, dropna finally has its legitimate home — with an explicit subset. A delivery with no ID or no promised date cannot be joined, billed or audited, so it leaves the analysis frame for quarantine, reason recorded:
analysis = completed.dropna(subset=["delivery_id", "promised_date"])
print("analysis rows:", len(analysis))Expected output:
analysis rows: 9The final frame holds nine completed deliveries — two unrated, several without a driver note, every one a real, billable event — half again as many as the blanket drop kept.
Step 4: Show what nulls do inside groupby and aggregations, because that is where the quiet damage happens:
by_customer = events.groupby("customer_id").agg(
deliveries=("delivery_id", "count"),
units_total=("units_delivered", "sum"),
units_mean=("units_delivered", "mean"),
ratings=("customer_rating", "count"),
rating_mean=("customer_rating", "mean"),
)
print(by_customer.round(2).to_string())Expected output:
deliveries units_total units_mean ratings rating_mean
customer_id
21 3 29.0 14.5 2 4.5
22 2 8.0 8.0 1 4.0
23 2 29.0 14.5 2 4.5
24 2 16.0 8.0 1 5.0
25 1 14.0 14.0 1 3.0
26 1 0.0 NaN 0 NaN
27 1 6.0 6.0 0 NaNEvery row teaches something. count on delivery_id counts rows; count on customer_rating counts ratings — the gap between them is the missingness, made visible, and why count and size are not interchangeable. mean skips nulls, so customer 21’s mean of 14.5 averages the two completed deliveries, 12 and 17, with the in-transit row silently excluded — correct here only because we established why that row is absent; the function neither knows nor cares. Customer 26 has a single delivery, still in transit, so units_mean is null, the honest answer, while units_total is 0.0, because sum over an all-null group returns zero by default. That asymmetry has shipped real bugs: “customer 26 received 0 units” states a fact the data does not contain. The guard is min_count=1 — events.groupby(“customer_id”)[“units_delivered”].sum(min_count=1) returns null for customer 26 and leaves genuine totals unchanged. Two more behaviours deserve naming: null group keys disappear from groupby output unless dropna=False is passed, so gaps in customer_id would vanish from per-customer tables while remaining in the grand total; and filtering is not neutral — events[events[“customer_rating”] >= 4] excludes every unrated row, because a comparison with a null is never true. “Not rated poorly” and “rated at least 4” are different questions.
Step 5: Disarm the text column. The profile said driver_note is 50 percent missing. It is lying by omission: isna recognises only genuine nulls. Delivery 8’s note is an empty string and delivery 12’s is two spaces — neither null, both content-free — while delivery 7’s “ lift broken “ is real information in untidy clothes:
notes = events["driver_note"]
blank = notes.notna() & notes.astype(str).str.strip().eq("")
print("isna missing: ", int(notes.isna().sum()))
print("blank/whitespace: ", int(blank.sum()))
print("genuinely present: ", int((notes.notna() & ~blank).sum()))Expected output:
isna missing: 6
blank/whitespace: 2
genuinely present: 4Only four of twelve deliveries carry a usable note — yet under the blanket dropna, the two blank-but-not-null notes kept their rows alive for the wrong reason while completed rows died over optional ratings. Normalise text explicitly:
events = events.copy()
events["driver_note"] = events["driver_note"].str.strip().replace("", np.nan)
print("note missing after cleaning:", int(events["driver_note"].isna().sum()))Expected output:
note missing after cleaning: 8Now the count is honest — and the brief’s requirement holds: the note column appears in no subset that decides row survival. Notes enrich rows; they never gate them. The same disguise appears with numbers arriving as text: a units_delivered column read as object dtype because one upstream file wrote “NULL” into it defeats isna, sum and every comparison until pd.to_numeric(…, errors=”coerce”) turns the impostor strings into true nulls. The dtype column in the Step 1 profile was not decoration; an unexpected object dtype on a numeric column is the smoke that leads to this fire.
The common wrong answer
The first is the line that created the problem — dropna() with no arguments, defended as “removing the bad rows.” Its autopsy has three findings. It applies the strictest column’s standard to every column, so one optional field at 41.7 percent missing acquires veto power over the whole dataset. It never looks at what it deleted, so it cannot distinguish in-transit rows it should have kept from broken rows it should have escalated; both are simply gone, and gone rows leave no trace in any log or total. And it biases the survivors, because completeness is not random. When the interviewer asks “your average rating rose after cleaning — good news?” the blanket-drop candidate has no answer. The profiling candidate says: no, the population changed; unrated deliveries left the denominator.
The second wrong answer is the mirror image: imputing everything. Fill ratings with the mean, units with the median, times with the mode, produce a frame with no nulls and call it complete. On the billing column this fabricates charges; on in-transit rows it asserts deliveries have happened which have not. A frame with no nulls is not a clean frame — very often it is a frame whose uncertainties have been hidden from everyone downstream.
The third catches competent engineers: dropna(subset=[“customer_rating”]) — targeted, modern-looking — used to prepare an operations analysis because the analysis “is about ratings.” If the same frame also reports delivery counts or unit totals, those numbers now describe rated deliveries only. The preventive rule: each analysis gets the population its question defines, derived from the preserved full frame — never from a frame another question already filtered.
The follow-up they ask next
Usually a scenario: “Next month the same table arrives daily, and the rating column is 95 percent missing instead of 41.7. What changes?”
The brief worked answer: the column stops being an analysis input and becomes a data-quality incident. At 41.7 percent, ratings are a sparse but usable signal with a stated denominator. At 95 percent, an average is five percent of customers — almost certainly those with extreme experiences — describing the whole. The honest report says coverage collapsed, dates the collapse, and checks the mechanical causes first: an app release that buried the rating prompt, a schema change, one platform’s events arriving without the field. In code, the response is a coverage guard, not a cleverer imputation:
coverage = events["customer_rating"].notna().mean()
print(f"rating coverage: {coverage:.1%}")
if coverage < 0.20:
print("BELOW REPORTING FLOOR - raise a data-quality incident; "
"do not publish a mean rating")The threshold is a team decision; the point is that the guard exists, is computed from the data, and fails loudly. Sparse columns also earn a permanent place in the daily profile output, so a slide from 41.7 to 95 percent is a trend seen in week one, not a surprise found in a quarterly review.
A harder variant
“This events table feeds a model that predicts late deliveries. A colleague proposes preparing the training data by dropping every row with any missing value, then imputing the test data with the training means. Take the proposal apart, then prepare the data properly.”
Three faults, in descending order of damage. First, the training population. Dropping incomplete rows trains the model on completed, rated, annotated deliveries only, while the model will be used on deliveries in flight — precisely the rows with missing delivered_at and units_delivered. The proposal deletes the deployment population from the training data. Worse, several fields are missing because of the outcome itself: a delivery has no delivered time because it is late or still out. Dropping those rows teaches the model a world in which late deliveries barely exist.
Second, the target-adjacent trap. Any feature derived from delivered_at — delivery duration, say — is unknowable at prediction time for an in-flight delivery. A preparation that quietly requires it guarantees the model cannot be served honestly, however good its offline score looks. The correct preparation defines, feature by feature, what is knowable at the moment of prediction, and builds the training frame from only that.
Third, the imputation asymmetry. Filling test gaps with training statistics is the right instinct executed too loosely. Fill values must be computed on training data only — computing them on all data leaks test information into training — then applied identically to training, test and production, ideally inside a single fitted pipeline so the three can never drift apart. Each imputed column also gets its missingness indicator, because here absence is predictive: “no scan yet” is itself a signal about a delivery’s state.
train = events.sample(frac=0.8, random_state=7)
test = events.drop(train.index)
fill_value = train["customer_rating"].median()
for name, frame in (("train", train), ("test", test)):
frame = frame.assign(
rating_was_missing=frame["customer_rating"].isna().astype(int),
customer_rating=frame["customer_rating"].fillna(fill_value),
)
print(name, "rows prepared:", len(frame))In a full solution that hand-applied fill becomes a fitted preprocessing pipeline, but the interview is won on the reasoning: preserve the deployment population, refuse features that borrow from the future, compute every fill on training data alone, carry the missingness indicators, and keep billing-grade columns out of the imputer’s reach. Close on the principle the question was built to surface. Missing values are not dirt to be swept out before the real work starts. They are part of the data’s testimony — about what has not happened yet, what nobody was asked, and what broke — and the engineer’s job is to give each kind of absence its own honest handling, in the open, where the next engineer can see it.
Question 7: Process a CSV Far Larger Than Memory in Chunks and Still Produce a Correct Total
The question
You are given a file called orders_2025.csv. It is 38 gigabytes, with roughly 210 million rows. Your laptop for this exercise has 8 gigabytes of RAM, and the interviewer is watching your screen. The file has these columns:
order_id,order_date,region,channel,units,unit_price,status
1001,2025-01-03,North,web,2,49.99,completed
1002,2025-01-03,South,store,1,129.00,completed
1003,2025-01-03,North,web,5,9.50,refunded
...The business question is simple to state and easy to get wrong: what is the total revenue from completed orders, broken down by region, and what is the average order value — revenue divided by number of completed orders — for each region?
The interviewer adds three constraints. First, you may not load the whole file into memory; a plain pd.read_csv(“orders_2025.csv”) will die, and they want to see that you know that before it happens rather than after. Second, the answer has to be exactly right, not approximately right — finance will reconcile it against the warehouse. Third, they want you to talk through what you are doing as you go: why each parameter is there, what you are accumulating, and what could still bite you when a file this size meets real-world messiness — mixed types, a region that appears in every chunk, a status column with values you did not expect.
A small slice of the data, which the interviewer pastes into the prompt so you can sanity-check your logic by hand, looks like this:
order_id,order_date,region,channel,units,unit_price,status
1,2025-03-01,North,web,2,10.00,completed
2,2025-03-01,North,store,1,30.00,completed
3,2025-03-01,South,web,4,5.00,completed
4,2025-03-01,South,web,1,100.00,refunded
5,2025-03-02,North,web,3,10.00,completed
6,2025-03-02,South,store,2,20.00,completed
7,2025-03-02,East,web,1,50.00,cancelled
8,2025-03-02,East,web,2,25.00,completedOn this slice, the correct answer is easy to verify with a pencil. Completed revenue in the North is 20 plus 30 plus 30, which is 80.00 across three orders, for an average order value of about 26.67. The South has 20 plus 40, which is 60.00 across two orders, averaging 30.00. The East has a single completed order worth 50.00. The refunded and cancelled rows contribute nothing. If your chunked code does not reproduce those three numbers on the small slice, it will not magically become right on 210 million rows. The interviewer knows this, and the slice is there precisely so that a careful candidate proves the logic small before running it large.
What they are really testing
This question is not really about read_csv. Any candidate can name the chunksize parameter after enough revision. What the interviewer is probing is whether you think in aggregates the way a data engineer has to: as quantities that can be combined correctly from pieces, or as quantities that cannot.
The first thing being tested is memory discipline. Do you reach for streaming or chunking unprompted, do you cut the data down to only the columns and types you actually need, and can you do rough memory arithmetic out loud — so many rows, so many bytes per row in memory, therefore this chunk size and not that one? Interviewers for data engineering roles have all watched a candidate write elegant pandas that would require 60 gigabytes of RAM to execute. They are listening for the opposite instinct.
The second thing is the single most common statistical error in chunked processing: averaging averages. A mean is not combinable from means alone. If one chunk has 10 orders averaging 100 dollars and the next has 990 orders averaging 10 dollars, the true average is nowhere near 55 dollars, yet that is exactly what averaging the two chunk averages produces. The correct habit — carry a sum and a count, divide once at the end — is trivial to state and, under interview pressure, surprisingly easy to fumble. This question is engineered to catch the fumble.
The full worked answer
The memory maths deserves thirty seconds of arithmetic, because it justifies the chunk size instead of leaving it as a magic number. A CSV row here is roughly 45 bytes on disk, but that is not what it costs in memory. Once parsed, a row in a DataFrame carries Python and NumPy overhead: an integer column costs 8 bytes per row, a float column 8 bytes, and object columns for strings cost far more — a pointer per value plus the string object itself, easily 50 to 70 bytes per short string. Four retained columns, with the two string columns converted to the category dtype, land somewhere around 25 to 40 bytes per row in practice. A chunk of one million rows therefore occupies roughly 30 to 40 megabytes for the retained columns, plus temporary copies while filtering and computing — call it 100 megabytes of working room per chunk to be safe. That is comfortable in 8 gigabytes, leaves room for the operating system and everything else, and still means only about 210 iterations for the whole file. A chunk of 100,000 rows would also work but pays the per-chunk overhead ten times as often; a chunk of 50 million rows would need several gigabytes and defeat the entire exercise. One million is not a guess. It is the output of the arithmetic.
Here is the complete solution:
import pandas as pd
PATH = "orders_2025.csv"
CHUNK = 1_000_000
revenue_by_region: dict[str, float] = {}
count_by_region: dict[str, int] = {}
reader = pd.read_csv(
PATH,
chunksize=CHUNK,
usecols=["region", "units", "unit_price", "status"],
dtype={
"region": "category",
"units": "int32",
"unit_price": "float64",
"status": "category",
},
)
for chunk in reader:
completed = chunk.loc[chunk["status"] == "completed"]
if completed.empty:
continue
revenue = completed["units"] * completed["unit_price"]
chunk_totals = revenue.groupby(completed["region"], observed=True).sum()
chunk_counts = completed.groupby(completed["region"], observed=True).size()
for region, total in chunk_totals.items():
revenue_by_region[region] = revenue_by_region.get(region, 0.0) + float(total)
for region, n in chunk_counts.items():
count_by_region[region] = count_by_region.get(region, 0) + int(n)
result = pd.DataFrame(
{
"region": list(revenue_by_region),
"revenue": [revenue_by_region[r] for r in revenue_by_region],
"orders": [count_by_region[r] for r in revenue_by_region],
}
)
result["avg_order_value"] = result["revenue"] / result["orders"]
print(result.sort_values("region").to_string(index=False))Run against the interviewer’s eight-row slice, with the chunk size temporarily set to 3 so the slice is forced across three chunks — a trick worth mentioning, because it proves the accumulation logic rather than merely the arithmetic — the output is:
region revenue orders avg_order_value
East 50.00 1 50.000000
North 80.00 3 26.666667
South 60.00 2 30.000000Those are the pencil numbers. The logic is verified small, and because nothing in the code depends on chunk boundaries, it is verified large as well.
Walk through the decisions one at a time, the way you would narrate them in the room. usecols comes first in importance even though it sits quietly in the call: the file has seven columns and the question needs four. Dropping order_id, order_date and channel at read time means those bytes are never parsed, never stored and never carried through 210 iterations. On a file this size, column pruning is not a micro-optimisation; it can halve both memory and runtime. Note in particular that order_date is excluded, so the code never pays to parse 210 million date strings it would never use. If a later question needed monthly totals, the date would come back in — parsed once, deliberately, with an explicit format — not by accident.
The dtype argument does two jobs. It saves memory: int32 for units instead of the default int64 halves that column, and category for region and status stores each distinct string once plus a small integer code per row, instead of a full string object per row. With four regions and a handful of statuses repeated 210 million times, the saving is enormous. It also buys consistency. Without an explicit dtype, pandas infers types chunk by chunk; a column that looks integer in the first million rows and contains one stray decimal or blank in chunk 87 will change type mid-file, producing a warning at best and a DtypeWarning or a failed concatenation of results at worst. Declaring the types up front turns a whole class of surprises into either correct behaviour or one loud error at the start, where errors are cheap.
The accumulation itself is the heart of the answer, so be explicit about it. Inside each chunk, groupby produces that chunk’s revenue total and order count per region. Those partial results are then added into two plain dictionaries keyed by region. Dictionaries are the right tool here because the number of regions is tiny and fixed; the accumulator’s memory footprint is proportional to the number of groups, not the number of rows, which is exactly the property that makes the whole approach scale. Whether the file has two million rows or two billion, the dictionaries hold four regions. The average is computed exactly once, after the loop, from the final sum and the final count. At no point does a per-chunk average exist anywhere in the program, so the averaging-averages error is not merely avoided — it is made structurally impossible.
What breaks when a category spans chunks? For this question, nothing, and it is worth saying precisely why: sum and count are both additive, so a region split across 210 chunks accumulates to the same total as a region sitting in one. But name the neighbouring cases where the same skeleton fails, because the interviewer is deciding whether you know where the cliff edge is. A median or a percentile cannot be accumulated from partial medians at all; you would need a sketching algorithm or a full sort elsewhere. A distinct count cannot be accumulated from per-chunk distinct counts, because the same customer in five chunks gets counted five times; exact distinct counts at this scale belong in a database, a sort, or a probabilistic structure such as HyperLogLog with its error bounds stated. A top-ten-products query can be accumulated, but only if you keep full per-product totals in the accumulator rather than each chunk’s local top ten — a product ranked eleventh in every chunk could easily be first overall. The pattern to articulate is that chunked aggregation is safe exactly when the final statistic can be rebuilt from combinable partials, and naming which statistics qualify is the senior-level part of this answer.
The common wrong answer
The common wrong answer loads the file — or, when the candidate has been warned about memory, chunks the file — and then averages the averages. It looks like this:
import pandas as pd
averages = []
for chunk in pd.read_csv("orders_2025.csv", chunksize=1_000_000):
completed = chunk[chunk["status"] == "completed"]
completed = completed.assign(
revenue=completed["units"] * completed["unit_price"]
)
averages.append(completed.groupby("region")["revenue"].mean())
answer = sum(averages) / len(averages) # or averages averaged per regionThe autopsy has three findings. The fatal one is mathematical: a mean of chunk means weights every chunk equally, but chunks do not contain equal numbers of orders for a region. Suppose the North appears 900,000 times in chunk one with an average order value of 20 dollars, because that section of the file is a January sale, and 100,000 times in chunk two with an average of 80 dollars. The true average is (900,000 × 20 + 100,000 × 80) ÷ 1,000,000, which is 26 dollars. The wrong code reports 50 dollars — nearly double — with no error, no warning and clean-looking output. Silent numerical wrongness is the worst failure mode in data engineering, worse than any crash, because a crash at least announces itself. This code would pass a casual eyeball, ship, and be discovered by finance weeks later, at which point every number the pipeline produced in the interval is suspect.
The third finding is everything the wrong answer omits: no usecols, so all seven columns are parsed for 210 million rows; no dtype, so strings are stored as objects and inference is left to chance per chunk; and, in the version candidates write before the interviewer mentions memory at all, no chunking whatsoever — just a read_csv, a groupby and a long silence while the kernel is killed by the operating system. The interview lesson is that this question’s wrong answer is rarely a syntax error. It is a correct-looking program built on a statistic that does not combine.
The follow-up they ask next
The follow-up is usually delivered with a smile: “Fine. Now I don’t want regional totals. I want the total revenue per calendar month, and the file isn’t sorted by date. Same constraints.”
The point of the follow-up is to check that your skeleton generalises and that you handle the one new cost honestly — the date column now has to come back in and be parsed. The worked answer keeps the identical accumulation pattern, changes the key, and parses dates once with an explicit format:
import pandas as pd
revenue_by_month: dict[str, float] = {}
count_by_month: dict[str, int] = {}
reader = pd.read_csv(
"orders_2025.csv",
chunksize=1_000_000,
usecols=["order_date", "region", "units", "unit_price", "status"],
dtype={"units": "int32", "unit_price": "float64", "status": "category"},
parse_dates=["order_date"],
date_format="%Y-%m-%d",
)
for chunk in reader:
completed = chunk.loc[chunk["status"] == "completed"]
if completed.empty:
continue
month = completed["order_date"].dt.to_period("M").astype(str)
revenue = completed["units"] * completed["unit_price"]
for m, total in revenue.groupby(month).sum().items():
revenue_by_month[m] = revenue_by_month.get(m, 0.0) + float(total)
for m, n in revenue.groupby(month).size().items():
count_by_month[m] = count_by_month.get(m, 0) + int(n)Say the two things the interviewer is listening for. First, nothing about correctness changed: month is just another low-cardinality key, twelve values, so the accumulators stay tiny and sum-plus-count still combines exactly. Second, the honest cost: parsing 210 million dates is now the slowest part of the job, which is why the explicit date_format matters — it lets the parser take the fast path instead of guessing the format row by row — and why, if only the month were needed and the format were guaranteed, a cheaper trick exists: slice the first seven characters of the raw string, YYYY-MM, without parsing at all, and say clearly that you would only do that behind a validation check on the format, because trading correctness for speed without naming the trade is how pipelines rot.
A harder variant
The harder variant removes the comfort of a small key space: “Now give me total revenue and order count per customer. There are about 40 million distinct customers. Same machine.”
This changes the problem’s nature, and the strong answer starts by saying so. A dictionary keyed by customer no longer has a tiny footprint: 40 million keys, each a string plus a float and an integer, will run to many gigabytes — plausibly more than the machine has. The accumulator itself has become the memory problem. Candidates who simply swap region for customer_id in the previous solution have not noticed that the ground moved.
The worked solution processes the file in chunks exactly as before, but writes each chunk’s per-customer partial aggregates to disk and then combines the partials with an external, disk-backed step, keeping memory bounded by design rather than by hope. In practice, the cleanest version uses SQLite, which ships with Python, as the combining engine:
import sqlite3
import pandas as pd
conn = sqlite3.connect("partials.db")
conn.execute("DROP TABLE IF EXISTS partials")
conn.execute(
"CREATE TABLE partials (customer_id TEXT, revenue REAL, orders INTEGER)"
)
reader = pd.read_csv(
"orders_2025.csv",
chunksize=1_000_000,
usecols=["customer_id", "units", "unit_price", "status"],
dtype={"units": "int32", "unit_price": "float64", "status": "category"},
)
for chunk in reader:
completed = chunk.loc[chunk["status"] == "completed"]
if completed.empty:
continue
revenue = completed["units"] * completed["unit_price"]
partial = pd.DataFrame(
{
"revenue": revenue.groupby(completed["customer_id"]).sum(),
"orders": completed.groupby(completed["customer_id"]).size(),
}
).reset_index()
partial.to_sql("partials", conn, if_exists="append", index=False)
final = pd.read_sql(
"""
SELECT customer_id,
SUM(revenue) AS revenue,
SUM(orders) AS orders,
SUM(revenue) / SUM(orders) AS avg_order_value
FROM partials
GROUP BY customer_id
""",
conn,
)Explain why this is right. Each chunk collapses a million rows into at most a million, and usually far fewer, per-customer partial rows; those partials live on disk, where there is room for them. SQLite then performs the final grouped sum with its own disk-aware machinery, spilling as needed, so no step ever requires the full key space in RAM. Sum and count are still the quantities being combined — the statistics have not changed, only the storage of the accumulator has.
Question 8: Ingest From a REST API Safely
The question
A vendor exposes your company’s product catalogue over a REST API, and the pipeline you are hired to maintain pulls the full catalogue into the warehouse every night. The interviewer sketches the API on the whiteboard:
GET https://api.vendor.example/v1/products?page=3&page_size=200
Authorization: Bearer <token>
Response: 200 OK
{
"page": 3,
"page_size": 200,
"total_pages": 42,
"results": [ { "id": 601, "sku": "A-100", "price": 19.99, ... }, ... ]
}There are about 8,400 products, so a full pull is 42 pages at the maximum page size of 200. The vendor’s documentation says the API allows 120 requests per minute per token, returns 429 Too Many Requests with a Retry-After header when you exceed it, and occasionally returns 500 and 503 errors “during maintenance windows,” which the interviewer mentions with the flat tone of someone who has been paged during several of them. The token is issued per environment — one for development, one for production — and a security review last quarter found a production token hardcoded in a notebook, which is why, the interviewer adds, this question is now in the interview loop at all.
Your task: write the ingestion function. It must fetch every page, survive the failures this API is known to produce without losing the run or hammering the vendor, keep credentials out of the code, and leave behind enough raw evidence that, when a downstream number looks wrong next week, someone can establish whether the API sent bad data or the pipeline mangled good data. The interviewer is explicit that a bare loop with requests.get inside it is the beginning of an answer, not an answer.
Assume a small concrete case for checking your logic: the development environment has 7 products over 4 pages at a page size of 2, and the third page fails twice with a 503 before succeeding. Your code, run against that environment, should still return all 7 products, in page order, having made 6 requests in total for the pages plus the retries — and it should be obvious from the code, and from what it writes to disk, that this is what happened.
What they are really testing
Nobody interviews on pagination because pagination is hard. They interview on it because an API client concentrates, in about sixty lines, nearly every judgement call that separates a data engineer from someone who can merely call a library.
The first judgement is failure taxonomy. Some failures deserve a retry, some deserve a pause, and some deserve an immediate, loud stop. A 503 or a dropped connection is transient almost by definition; a 429 is the server telling you, precisely, how long to wait; a 401 will fail identically a thousand times if you retry it, because the token is wrong, and a 404 on page one means your URL or resource is wrong, not unlucky. Candidates who retry everything are as dangerous as candidates who retry nothing: the first group turns a bad token into a self-inflicted denial-of-service against a vendor and a very awkward email, the second group builds a nightly job that dies at 2 a.m. because one page hiccupped.
The full worked answer
import json
import logging
import os
import random
import time
from functools import wraps
from pathlib import Path
import requests
log = logging.getLogger("catalogue_ingest")
BASE_URL = os.environ.get("VENDOR_API_BASE", "https://api.vendor.example/v1")
PAGE_SIZE = 200
RAW_DIR = Path("raw/products")
def get_token() -> str:
token = os.environ.get("VENDOR_API_TOKEN")
if not token:
raise RuntimeError(
"VENDOR_API_TOKEN is not set; export it or inject it via the "
"scheduler's secret store — never hardcode it."
)
return token
def retry_with_backoff(max_attempts=5, base_delay=1.0, max_delay=60.0):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
delay = base_delay
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except (requests.ConnectionError, requests.Timeout) as exc:
if attempt == max_attempts:
raise
sleep_for = min(delay, max_delay) * (0.5 + random.random())
log.warning(
"attempt %d failed (%s); retrying in %.1fs",
attempt, exc, sleep_for,
)
time.sleep(sleep_for)
delay *= 2
raise RuntimeError("unreachable")
return wrapper
return decorator
@retry_with_backoff()
def fetch_page(session: requests.Session, page: int) -> dict:
resp = session.get(
f"{BASE_URL}/products",
params={"page": page, "page_size": PAGE_SIZE},
timeout=(5, 30),
)
if resp.status_code == 429:
wait = float(resp.headers.get("Retry-After", "30"))
log.warning("rate limited on page %d; honouring Retry-After %.0fs", page, wait)
time.sleep(wait)
resp = session.get(
f"{BASE_URL}/products",
params={"page": page, "page_size": PAGE_SIZE},
timeout=(5, 30),
)
if resp.status_code in (500, 502, 503, 504):
raise requests.ConnectionError(f"server error {resp.status_code} on page {page}")
resp.raise_for_status()
return resp.json()
def ingest_catalogue(run_date: str) -> list[dict]:
RAW_DIR.mkdir(parents=True, exist_ok=True)
session = requests.Session()
session.headers.update(
{
"Authorization": f"Bearer {get_token()}",
"Accept": "application/json",
}
)
records: list[dict] = []
page = 1
total_pages = None
while total_pages is None or page <= total_pages:
payload = fetch_page(session, page)
total_pages = int(payload["total_pages"])
raw_path = RAW_DIR / f"{run_date}_page_{page:03d}.json"
raw_path.write_text(json.dumps(payload), encoding="utf-8")
results = payload["results"]
log.info("page %d/%d: %d records", page, total_pages, len(results))
records.extend(results)
page += 1
log.info("ingest complete: %d records across %d pages", len(records), total_pages)
return recordsAgainst the development case — 7 products, 4 pages, page three failing twice with a 503 — this returns all 7 products in order. The two 503s are converted inside fetch_page into the retryable exception, the decorator waits, retries, and succeeds on the third attempt for that page, and four raw files sit on disk afterwards, one per page, exactly as received.
Now narrate the decisions, because the code alone earns only half the marks. Pagination first. The loop is driven by the API’s own total_pages, read from the first response and re-read on every page, rather than by the fragile alternative of fetching until an empty page appears; some APIs return an empty page mid-sequence during deployments, and stopping there would silently truncate the catalogue. The alternative contract — following a next URL or cursor token when the API offers one — deserves a mention: if the API gives you a cursor, use it and never construct page numbers, because offset pagination over a catalogue that changes mid-pull can skip or double-count rows as items are inserted, while a cursor pins your position. Knowing which contract you are under, and saying which one this API uses, is the point.
The retry policy is the centrepiece, so slow down for it. The decorator retries connection errors and timeouts — the transient network layer — and the code converts the transient server statuses, 500, 502, 503 and 504, into that same retryable path, so policy lives in one place rather than smeared across the function. Delays double each attempt from a one-second base, are capped at sixty seconds, and are multiplied by a random factor between 0.5 and 1.5 — that multiplication is the jitter, and you should explain it unprompted: without jitter, every client that failed together retries together, in waves, and a recovering API gets flattened by its own polite customers. Just as important is what is not retried. A 400, 401, 403 or 404 falls straight through to raise_for_status() and kills the run immediately, because no amount of waiting repairs a malformed request or a dead token, and retrying one only delays the page-out and multiplies the noise. Retrying a 401 five times with backoff is not resilience; it is five unauthorised requests and a later alarm.
Credentials are handled the way the security review demands. The token is read from the VENDOR_API_TOKEN environment variable at call time, the base URL is likewise overridable per environment, and the code fails immediately with an explanatory error if the variable is absent — failing at startup, in the first second, rather than after 41 pages. Nothing secret appears in the source, in the logs (note that the code logs pages and counts, never headers), or in the raw files, which contain response bodies only. In production the variable is injected by the scheduler’s secret store or the deployment platform; in development it lives in the developer’s shell or a local, uncommitted .env that is named in .gitignore. If an interviewer presses on the notebook incident, the complete answer adds that tokens which have been committed must be treated as compromised and rotated, not merely deleted from the file — deleting the line does not delete the git history.
The raw-before-transform discipline closes the answer. Every page’s payload is written to disk, dated and page-numbered, before a single record is extended into the combined list, and no transformation happens in this function at all — parsing, deduplication, schema checks and loading belong to a separate step that reads the raw files. That separation buys three concrete things: a rerun after a transformation bug does not re-hit the vendor’s API at all; a dispute about a price next week is settled by opening the raw file and looking, not by arguing from memory; and a schema change by the vendor is detected against stored evidence, with the run’s logs showing exactly which page first arrived in the new shape. State the idempotency corollary too: raw files are keyed by run date and page, so a retried run overwrites its own partial output rather than appending duplicates to it, and the downstream load should key on product id for the same reason — ingestion that cannot be safely rerun will, eventually, not be rerun when it should be, out of fear.
The common wrong answer
The common wrong answer is the bare loop, and it deserves a careful autopsy rather than mockery, because it works in the demo — which is precisely what makes it dangerous.
import requests
token = "prod_9f27_EXAMPLE_TOKEN_DO_NOT_USE" # pasted from the portal
all_products = []
page = 1
while True:
r = requests.get(
f"https://api.vendor.example/v1/products?page={page}&page_size=200",
headers={"Authorization": f"Bearer {token}"},
)
data = r.json()
if not data["results"]:
break
all_products.extend(data["results"])
page += 1Count the failures. There is no timeout, so one stalled connection on page 31 ends the night silently — no exception, no alert, just a job that appears to be running until someone checks. There is no status handling at all: a 503 body is handed to .json(), which either raises an opaque decoding error far from its cause or, worse, parses an error envelope successfully and treats its empty or absent results as the end of the catalogue — the loop breaks, the run “succeeds,” and the warehouse loads a partial catalogue with every downstream report quietly wrong. A 429 receives the same treatment, and the loop’s response to being told to slow down is to immediately ask again, harder, until the vendor’s limit hardens into a longer ban. The token is hardcoded — the exact finding from the security review, reproduced in the interview — which means it is now in source control, in the notebook, in the screen share and in this transcript. Pagination terminates on an empty page rather than the API’s stated page count, so one anomalous empty response mid-sequence truncates the pull without a trace. Nothing is written to disk, so when the prices are wrong on Thursday there is no evidence, only opinions. And there is no count check anywhere: the code never compares the number of records received against anything, so a pull of 6,100 products out of 8,400 raises no eyebrow. The interview lesson is that API ingestion fails by inches — each omission is small, survivable and common — and the marks in this question are awarded for the number of inches you refuse to give.
The follow-up they ask next
The follow-up is short: “The vendor adds a second endpoint — prices change during the day, and a full nightly pull is no longer acceptable. They offer GET /products?updated_since=<timestamp>. What changes?”
The expected answer keeps the entire skeleton — the decorated fetch, the timeouts, the raw writes, the environment-based token — and changes the state management. The job now persists a high-water mark: the timestamp of the last successful run, stored somewhere durable such as a small table in the warehouse or a state file written only after the load commits. Each run requests only records updated since that mark, and advances the mark only on success; a failed run leaves the mark untouched, so the next run re-fetches the same window and nothing falls through the crack between a failed fetch and a moved marker.
A harder variant
The harder variant turns the volume up and the reliability down: “The catalogue grows to two million products — 10,000 pages. The vendor’s maintenance windows now last twenty minutes, several times a week, and your job’s slot is forty minutes. A run that restarts from page one will not finish. What do you change?”
The core realisation to state first is that the problem is no longer fetching; it is resumability. The unit of work must become the page, durably recorded, so that any run can pick up where any previous run stopped, and the governing principle is that progress is written down before it is relied upon.
The worked solution restructures the orchestrator around a checkpoint. Each successfully fetched page is written raw to disk, as before, and its page number is recorded in a small checkpoint store — a table, or a JSON state file rewritten atomically — in the same breath. The run begins by reading the checkpoint and starting from the first unfetched page, not from page one. Retries keep their backoff, but the cap and the attempt budget are now tuned to the reality of a twenty-minute outage: rather than failing the run after five attempts inside a window the vendor has announced, in effect, by returning 503 with Retry-After, the fetcher honours long Retry-After values on server errors too, parking on that page while the window passes, because re-entering later costs nothing once checkpoints exist. Concurrency enters, carefully: pages are independent, so a small pool of workers — small enough that the aggregate request rate stays comfortably under 120 per minute, enforced by a shared rate limiter rather than by hope — cuts the wall-clock time, while the checkpoint logic, not the completion order, defines what “done” means; page order in the raw store is preserved by filename, so out-of-order completion is harmless. The load step changes with it: it loads from the raw page files, not from an in-memory list, and it refuses to publish the new catalogue until a completeness check passes — pages 1 through 10,000 all present, record count reconciled against the API’s stated total — so a half-finished night yields yesterday’s complete catalogue in the warehouse, never today’s partial one. Here is the checkpointing core:
import json
from pathlib import Path
STATE = Path("raw/products/checkpoint.json")
def load_checkpoint(run_date: str) -> set[int]:
if STATE.exists():
data = json.loads(STATE.read_text(encoding="utf-8"))
if data.get("run_date") == run_date:
return set(data["done_pages"])
return set()
def save_checkpoint(run_date: str, done: set[int]) -> None:
tmp = STATE.with_suffix(".tmp")
tmp.write_text(
json.dumps({"run_date": run_date, "done_pages": sorted(done)}),
encoding="utf-8",
)
tmp.replace(STATE) # atomic rename: a crash never leaves a torn state file
def ingest_resumable(run_date: str) -> None:
done = load_checkpoint(run_date)
session = requests.Session()
session.headers.update(
{"Authorization": f"Bearer {get_token()}", "Accept": "application/json"}
)
first = fetch_page(session, 1)
total_pages = int(first["total_pages"])
if 1 not in done:
(RAW_DIR / f"{run_date}_page_001.json").write_text(
json.dumps(first), encoding="utf-8"
)
done.add(1)
save_checkpoint(run_date, done)
for page in range(2, total_pages + 1):
if page in done:
continue
payload = fetch_page(session, page)
(RAW_DIR / f"{run_date}_page_{page:03d}.json").write_text(
json.dumps(payload), encoding="utf-8"
)
done.add(page)
save_checkpoint(run_date, done)
log.info("all %d pages present for %s", total_pages, run_date)Question 9: Make a Load Idempotent, So Rerunning It Is Safe
The question
You inherit a nightly job that loads yesterday’s orders from a CSV file into a reporting table. Last Tuesday the job failed halfway through, an engineer reran it from the top, and by morning the revenue report showed almost exactly twice the correct total for that date. Nobody had changed the source file. The interviewer asks: explain what went wrong, and rewrite the load so that running it once, twice, or ten times — including after a failure in the middle — always leaves the table in exactly the same state. You may assume a simple table called orders with a business key order_id, a column order_date, and amount columns, and you may use plain Python with a database connection that supports transactions.
What they are really testing
This question is not really about SQL syntax. It is about whether you have ever been paged for a doubled number. A candidate who has only written loads that ran once, on a laptop, will reach for INSERT and stop there. A candidate who has operated a pipeline knows failure is the normal condition of the job: schedulers retry, engineers rerun, networks drop, and a load that cannot survive a rerun will eventually corrupt the one report the business actually reads.
Three ideas are being probed, and a strong answer names all three. First, the definition: a load is idempotent when applying it more than once has the same effect as applying it once. Second, the mechanism — either replacing a well-defined slice of the table, such as one date’s partition, or merging rows by their business key so a second arrival updates rather than duplicates. Third, atomicity: the replacement must happen inside a single transaction, so a crash halfway through leaves either the old state or the new state, never a blend. There is a quieter test underneath, too: whether you ask what the business key is. If the source has no stable key — no order_id that means the same order every time it appears — no amount of clever SQL makes the load safely rerunnable, and saying so plainly is often the moment the interview turns in your favour.
The full worked answer
Start with the diagnosis, because it is short. The original job almost certainly appended. Every run inserted the file’s rows on top of whatever was already in the table. On a normal night that is invisible, because the table was empty for that date. On the rerun night, the first attempt had already committed some or all of its rows before it failed, so the second run added a second copy. Totals doubled because totals are sums, and a sum has no way of knowing that two identical rows are one order seen twice rather than two orders.
The fix has two layers, and the worked answer below shows both. The first layer is delete-and-reload by partition: before inserting, delete exactly the slice the file represents — here, one order_date — and do the delete and the insert in the same transaction. The second layer is an upsert by business key for the rows themselves, which protects you when a file overlaps a date boundary or when the same order arrives corrected in a later file. In production you often need only one of the two, but showing both, and saying when each applies, is what separates a complete answer from a memorised one.
import csv
import sqlite3
CREATE_TABLE = """
CREATE TABLE IF NOT EXISTS orders (
order_id TEXT PRIMARY KEY,
order_date TEXT NOT NULL,
customer TEXT NOT NULL,
amount REAL NOT NULL
)
"""
UPSERT = """
INSERT INTO orders (order_id, order_date, customer, amount)
VALUES (?, ?, ?, ?)
ON CONFLICT(order_id) DO UPDATE SET
order_date = excluded.order_date,
customer = excluded.customer,
amount = excluded.amount
"""
def load_orders(csv_path, load_date, conn):
"""Load one day's orders idempotently.
Safe to rerun any number of times: the delete of the day's
partition and the insert of the file happen in ONE transaction,
and each row is upserted by its business key.
"""
with open(csv_path, newline="", encoding="utf-8") as f:
rows = [
(r["order_id"], r["order_date"], r["customer"], float(r["amount"]))
for r in csv.DictReader(f)
]
# Guard: refuse to load a file that is not the partition we
# are about to replace. This catches wrong-file mistakes early.
bad = [r for r in rows if r[1] != load_date]
if bad:
raise ValueError(f"{len(bad)} rows are not for {load_date}")
with conn: # one transaction: commit on success, rollback on error
conn.execute(
"DELETE FROM orders WHERE order_date = ?", (load_date,)
)
conn.executemany(UPSERT, rows)
return len(rows)
if __name__ == "__main__":
conn = sqlite3.connect(":memory:")
conn.execute(CREATE_TABLE)
# A tiny stand-in file written inline for the demonstration.
import io, os, tempfile
data = (
"order_id,order_date,customer,amount\n"
"A1,2026-12-01,Meera,120.00\n"
"A2,2026-12-01,Jonas,80.50\n"
"A3,2026-12-01,Priya,200.00\n"
)
with tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as tmp:
tmp.write(data)
path = tmp.name
print("first run: ", load_orders(path, "2026-12-01", conn))
print("second run:", load_orders(path, "2026-12-01", conn))
print("third run: ", load_orders(path, "2026-12-01", conn))
count, total = conn.execute(
"SELECT COUNT(*), SUM(amount) FROM orders"
).fetchone()
print("rows in table:", count)
print("total amount: ", total)
os.unlink(path)Expected output:
first run: 3
second run: 3
third run: 3
rows in table: 3
total amount: 400.5Walk through it step by step. First, the whole file is read and validated before the database is touched at all: if the file is malformed, or belongs to the wrong date, the job fails while the table still holds yesterday’s good state. The date check makes the partition explicit — a delete-and-reload is only safe when you can state precisely which slice of the table the file fully represents, and any row that disagrees is a reason to stop rather than to load. Second, the with conn: block is the transaction boundary. The delete and the inserts commit together or roll back together; if the process is killed after the delete but before the inserts finish, nothing commits, the old rows remain, and the next rerun starts from a known state. That is the line that fixes the original incident, and it is worth saying so out loud. Third, the upsert handles what the partition delete cannot: if a corrected A2 arrives tomorrow at 85.00, the ON CONFLICT … DO UPDATE clause turns the second arrival into a correction of the first rather than a duplicate beside it. Finally, after three runs the table holds three rows and a total of 400.5 — the same as after one run. That equality, stated as a check you would automate, is idempotency made testable. Add that you would also reconcile row count and sum against a control total from the source, because idempotency protects against duplication, not against a source file that was wrong in the first place.
The common wrong answer
The most common wrong answer is to deduplicate at read time only: load the file into a set, or call drop_duplicates() in pandas, and declare the problem solved. It solves a different problem. Deduplication inside one file stops the same row appearing twice in a single run. The incident in the question happened across runs, in the gap between what the first attempt committed and what the second attempt assumed. A candidate who dedupes the file and still appends to the table will double the revenue again on the next rerun, only now with cleaner data.
The second wrong answer is a delete with no transaction and no scope discipline: DELETE FROM orders for the whole table, followed by a reload of everything. A crash between the delete and the reload leaves an empty table — worse than a doubled one, because a doubled report at least looks wrong, while an empty one can be mistaken for a quiet day. Deleting by date but committing the delete before inserting in a second transaction has the same hole, one layer down. The third wrong answer sounds sophisticated: keep the load append-only and deduplicate later, in the reporting query, with a ROW_NUMBER() window keeping the latest copy of each key. That is a legitimate architecture when it is chosen deliberately, with the report logic rebuilt around it — but offered as a shortcut, it moves the corruption from the table into every future query written against it.
The follow-up they ask next
The usual follow-up is: “Your delete-and-reload works for one day’s file. What if the source sends corrections for the last thirty days in one file, and some orders have moved dates?” The brief answer is to lean entirely on the key: upsert every row by order_id, as the code above does. That is precisely why the primary key is order_id alone rather than the pair of date and ID — with the key on the ID alone, the update overwrites the row wherever it sits, date included, and no orphan survives under the old date. Then reconcile: count the distinct keys in the file and compare the table’s totals for the affected range against the source’s control totals. If the interviewer pushes further — “and if there is no order_id?” — build a key from the combination of fields that identifies an order, raise the missing key with the source team as a data contract problem, and meanwhile load into a staging table and merge on that composite.
A harder variant
The harder variant adds concurrency to partial failure: two instances of the job start at once — a scheduler retry overlapping a manual rerun — each processing the same file. Idempotency alone does not stop the two from interleaving: the upsert prevents duplicate rows, but a report reading mid-flight can still see wrong totals, and the two transactions can deadlock. The standard solution is a lock keyed to the partition, taken before touching it, so the second run detects that the work is under way and exits. The sketch below uses a lock table; the same idea is an advisory lock in PostgreSQL or a lease in a scheduler.
def load_with_lock(csv_path, load_date, conn, owner):
conn.execute(
"CREATE TABLE IF NOT EXISTS load_locks ("
" load_date TEXT PRIMARY KEY, owner TEXT NOT NULL)"
)
with conn:
cur = conn.execute(
"INSERT INTO load_locks (load_date, owner) VALUES (?, ?) "
"ON CONFLICT(load_date) DO NOTHING",
(load_date, owner),
)
if cur.rowcount == 0:
# Another run holds this partition. Its load is
# idempotent, so the safe action is to stop, not retry.
raise RuntimeError(f"{load_date} is already being loaded")
try:
n = load_orders(csv_path, load_date, conn)
finally:
conn.execute(
"DELETE FROM load_locks WHERE load_date = ? AND owner = ?",
(load_date, owner),
)
return nTwo details earn the marks. The lock is released in a finally block, so a failed load does not leave a stale lock blocking every future run — and a thoughtful candidate adds that a production version timestamps the lock and treats very old locks as abandoned, because processes die without running their finally blocks. And the second run raises rather than queues: because the load is idempotent, either run’s completed work is the correct final state, so the duplicate run has nothing to add.
Question 10: Sort and Rank Records by Several Keys at Once
The question
You are given a list of sales records. Each record is a dictionary with a salesperson’s name, a region, a revenue figure, and a deals count, and some records have no revenue figure yet because the quarter has not closed for that person. The interviewer asks for three things, in order. First, sort the records by region in ascending order, then by revenue in descending order, then by name in ascending order as a tie-breaker. Second, explain what happens to the records whose revenue is missing, and place them last within their region rather than letting them float to the top. Third, using pandas, produce the top three salespeople by revenue in each region, with a rank column that handles ties the way a league table would. Plain Python first, pandas second — and the interviewer will run your code.
What they are really testing
Sorting sounds elementary, and that is the trap. What is actually being tested is whether you understand that a sort key is a function, that Python’s sort is stable, and that “descending” means something different for numbers and for strings — three facts that account for a large share of the subtly wrong leaderboard code in production. The naive attempt fails quietly: negating a whole tuple reverses every field, sorting three times in the wrong order scrambles the earlier passes, and a missing value, left alone, sorts exactly where you did not want it and distorts a top-three list in a way nobody notices until a commission is paid on it. The pandas half tests whether you reach for rank and groupby as understood tools rather than incantations. Ranking has more than one legitimate definition — two people tied for second can both be ranked 2 with the next person ranked 4, or both ranked 2 with the next ranked 3 — and the business usually has an opinion. A candidate who states the convention they have chosen, and why, is demonstrating the judgement the question is fishing for.
The full worked answer
The clean plain-Python answer sorts once, with a single key function returning a tuple, and handles both complications — mixed directions and missing values — inside that tuple. Numbers can be negated to reverse them; strings cannot, which is why only the revenue is transformed and the ascending fields are left alone. The missing-value problem is solved with a flag placed before the revenue: present values get 0, missing values get 1, so every missing revenue sorts after every present one within its region, whatever the figures are.
records = [
{"name": "Meera", "region": "North", "revenue": 95000, "deals": 31},
{"name": "Jonas", "region": "North", "revenue": 95000, "deals": 28},
{"name": "Priya", "region": "North", "revenue": 120000, "deals": 35},
{"name": "Tomas", "region": "North", "revenue": None, "deals": 12},
{"name": "Aisha", "region": "South", "revenue": 88000, "deals": 26},
{"name": "Diego", "region": "South", "revenue": 143000, "deals": 40},
{"name": "Chen", "region": "South", "revenue": 143000, "deals": 38},
{"name": "Fatima", "region": "South", "revenue": None, "deals": 9},
]
def sort_key(record):
revenue = record["revenue"]
return (
record["region"], # region: ascending
1 if revenue is None else 0, # missing revenue: last
-(revenue) if revenue is not None else 0, # revenue: descending
record["name"], # name: ascending tie-break
)
ranked = sorted(records, key=sort_key)
for r in ranked:
print(r["region"], r["name"], r["revenue"])Expected output:
North Priya 120000
North Jonas 95000
North Meera 95000
North Tomas None
South Chen 143000
South Diego 143000
South Aisha 88000
South Fatima NoneRead the output the way the interviewer will. Within North, Priya leads; Jonas and Meera are tied at 95,000 and the name tie-breaker puts Jonas first, so the sort is deterministic — the same code produces the same leaderboard tomorrow. Tomas, whose revenue is missing, sits at the bottom of North rather than floating to the top, and in South, Chen and Diego’s tie at 143,000 is likewise settled by name, with Fatima last. Two explanations belong in the spoken answer. The first is stability: Python’s sorted is guaranteed stable, so records equal on the whole key keep their original relative order — which is also what makes the alternative approach work, sorting by the least significant key first and the most significant last, in three passes. The second is the negation trick’s limit: it works for numbers only. A descending string field cannot be negated; the honest options are the multi-pass stable sort or mapping the values to numbers through a dictionary that encodes the intended order, as the harder variant below does.
Now the pandas half. The same logic translates directly, with sort_values taking a list of columns, a matching list of directions, and — the argument candidates forget — na_position=”last”, because pandas by default puts missing values last in a sort regardless of direction, but relying on a default you cannot name is luck, not method. Ranking within each region is a groupby transform of rank, and the method chosen here is ”min”, the league-table convention: tied competitors share the better rank, and the following rank is skipped.
import pandas as pd
df = pd.DataFrame(records)
df_sorted = df.sort_values(
by=["region", "revenue", "name"],
ascending=[True, False, True],
na_position="last",
).reset_index(drop=True)
df_sorted["rank_in_region"] = df_sorted.groupby("region")["revenue"].rank(
method="min", ascending=False, na_option="bottom"
)
top3 = df_sorted[df_sorted["rank_in_region"] <= 3]
print(top3[["region", "name", "revenue", "rank_in_region"]].to_string(index=False))Expected output:
region name revenue rank_in_region
North Priya 120000.0 1.0
North Jonas 95000.0 2.0
North Meera 95000.0 2.0
South Chen 143000.0 1.0
South Diego 143000.0 1.0
South Aisha 88000.0 3.0Notice what the tie does to the shape of the answer, because the interviewer will. South’s top three contains ranks 1, 1 and 3 — there is no rank 2, because Chen and Diego share rank 1 under the ”min” convention. And if the question had meant top three rows rather than everyone ranked third or better, the filter would be groupby(…).head(3) after sorting, which can split a tie on row order. Naming that difference — a rank filter can return more or fewer than three rows per group when ties sit on the boundary, and the business must choose — is the strongest sentence in the answer. Finish by noting that na_option=”bottom” keeps the missing-revenue records below every real rank, rather than risking a configuration that hands a person with no closed revenue a rank of 1 at the top of a pay table.
The common wrong answer
The canonical wrong answer is one line: sorted(records, key=lambda r: (r[“region”], r[“revenue”], r[“name”]), reverse=True). It looks efficient and it is wrong in three directions at once. reverse=True reverses the entire comparison, so the regions come out descending, the names come out descending, and only the revenue — the one field the candidate was thinking about — happens to land the way they wanted. Worse, on the data as given it does not even run far enough to be wrong gracefully: comparing None with an integer raises a TypeError in Python 3, so the code crashes on the very records the question included on purpose. A crash is at least honest; the version of this mistake that survives code review is the one where the missing values were silently filled with zero beforehand, which places a salesperson who has not closed the quarter below everyone in a way that looks plausible — or, in an ascending sort somewhere else in the system, at the very top.
The second wrong answer sorts with three separate statements in the order the requirements were listed — region, then revenue, then name — forgetting that each later sort, stable though it is, becomes the primary ordering. The final pass wins, so sorting in the listed order leaves the list ordered mainly by name: the requirement read backwards. Candidates who debug this live, out loud, often recover well; candidates who glance at the tidy, alphabetical output and declare it correct do not. The third wrong answer lives in the pandas half: df[“revenue”].rank() on the ungrouped data, producing a single national ranking when the question asked for a rank within each region. It is the grouping, not the ranking, that carries the business meaning — and its absence is easy to miss, because the resulting column is full of plausible numbers.
The follow-up they ask next
The follow-up is usually about scale or the tie rule. On ties — “Two people share third place and there is one bonus” — the code as written pays both, because the filter keeps everyone ranked 3 or better, and whether that is right is a business decision the code should make visible, not bury. If the rule is one bonus, the deterministic name tie-breaker already in the sort provides an explainable decider. On scale — “This list is ten million records” — the algorithm does not change, and sorted computes each key once, up front, so the tuple approach stays cheap; what changes is memory, and the honest move is to sort in the database, in chunks, or in the query that produced the records, where an index may already hold the order you need.
A harder variant
The harder variant makes the descending field a string and the tie rule stricter at the same time: rank support engineers by region ascending, then by certification level descending, where the levels are the strings ”Expert”, ”Advanced”, ”Intermediate” and ”Foundation” — an order that is not alphabetical — and then by cases closed descending, keeping only the single top engineer per region, with ties on every field broken by whoever joined earliest.
Because the levels cannot be negated and do not sort alphabetically into the right order — alphabetically, ”Advanced” would beat ”Expert” — the key must translate each level into its position in the intended order. A dictionary does that translation, and everything else in the pattern carries over unchanged.
LEVEL_ORDER = {"Expert": 0, "Advanced": 1, "Intermediate": 2, "Foundation": 3}
engineers = [
{"name": "Ruth", "region": "West", "level": "Advanced", "cases": 140, "joined": 2019},
{"name": "Omar", "region": "West", "level": "Expert", "cases": 110, "joined": 2021},
{"name": "Lena", "region": "West", "level": "Expert", "cases": 110, "joined": 2018},
{"name": "Kenji", "region": "East", "level": "Expert", "cases": 132, "joined": 2020},
{"name": "Ana", "region": "East", "level": "Advanced", "cases": 160, "joined": 2022},
]
ordered = sorted(
engineers,
key=lambda e: (
e["region"], # ascending
LEVEL_ORDER[e["level"]], # Expert first, Foundation last
-e["cases"], # most cases first
e["joined"], # earliest joiner wins a full tie
),
)
best_per_region = {}
for e in ordered:
best_per_region.setdefault(e["region"], e)
for region, e in best_per_region.items():
print(region, e["name"], e["level"], e["cases"])Expected output:
East Kenji Expert 132
West Lena Expert 110What candidates are reporting about Python rounds
Ask a room of data engineers what a Python interview actually consists of, and the accounts do not quite agree with each other — which is itself the most useful thing a candidate can know before walking in. What follows is a picture of the discussion as candidates themselves describe it in forums, community threads and post-interview write-ups. It is reported conversation, not a survey, and no single thread should be read as the rule for any particular company. But the same arguments recur often enough, across enough hiring seasons, that preparing for the argument is nearly as valuable as preparing for any one side of it.
The longest-running debate concerns weight: how much of the round belongs to generators, iterators and the plain standard library, and how much to pandas. One camp reports rounds that never opened pandas at all — file parsing, dictionaries, grouping by hand — on the stated reasoning that a candidate who can aggregate with a dictionary understands what a groupby is doing, while the reverse is not always true. The other camp reports screens built entirely around a dataframe, with the plain-Python questions dismissed as trivia. Candidates caught between the two describe the same frustration from both directions: they prepared for the round they had read about and were given the other one. The conclusion most threads converge on is unglamorous — the two skill sets are not substitutes, and an hour spent on dictionary-based grouping is rarely wasted even in a pandas-heavy shop, because debugging a pipeline still happens one row at a time.
A second argument runs between the take-home and the live round, and it is as much about fairness as about skill. Supporters of the take-home describe it as the only format that resembles the job: real files, real documentation, time to test. Its critics reply that take-homes expand to fill the weekend, and that an unbounded task quietly selects for whoever has the fewest obligations outside work. Live coding draws the mirror-image complaint — that it measures performance under observation — alongside a defence candidates repeat often: a forty-five-minute live round, honestly scoped, respects the candidate’s time in a way a six-hour take-home does not. The hybrid comes up repeatedly in these discussions: a short live round for fluency, a bounded take-home or a walkthrough of the candidate’s own past code for depth. Candidates would do well to rehearse both tempos — the narrated, talk-while-you-type answer, and the quiet, tested, documented submission.
Whether data structures and algorithms questions belong in a data engineering loop is the third theme, and the one where reported practice varies most by company size. Candidates at the largest technology firms describe full algorithm rounds alongside the pipeline rounds; candidates at smaller companies describe something closer to this set — SQL, a Python round about files and records, and a design conversation. The middle position recurs: the algorithm questions that survive in data loops are usually the ones wearing work clothes. Grouping, deduplication, top-k selection, merging sorted streams — each is a textbook problem and each is also Tuesday.
The newest theme, and the least settled, is AI assistance in take-homes. Candidates report a genuine split in stated policy: some employers forbid assistance outright, some permit it and ask for disclosure, and some say nothing at all, which candidates describe as the hardest policy to navigate. Where assistance is permitted, candidates are still expected to explain every line they submit, and several report follow-up rounds built entirely around walking through their own take-home — a format in which pasted code, however correct, becomes a liability within minutes. Where the policy is silent, the advice repeated most often is to ask, in writing, before starting. Almost no one in these threads defends submitting work they could not reproduce unaided in the room, because the room, in one form or another, tends to come next.
Three interview rooms
The three scenes below are composite, illustrative examples. They are not accounts of named candidates or named companies; they are built from the situations interviewers describe setting and candidates describe meeting, and each is included because the decision points in it recur. Read them for the moments where the round was won or lost, which are rarely the moments the candidate expected.
The merge that doubled the revenue
Consider a data engineer who, forty minutes into a live round, joined an orders table to a shipments table and watched total revenue climb to almost exactly twice the figure the interviewer had mentioned at the start. The cause is a standard trap: the shipments table held two rows for many orders — a label created and a label reprinted — so the join fanned out, duplicating each affected order and its amount. What decided the round was not the mistake, which the interviewer had engineered and expected, but the recovery. The candidate stopped typing, said the number was wrong, and narrated a row count at each step: orders in, shipments in, rows out of the join, rows out after grouping. The count after the join exceeded the count of orders, which located the fault in the join rather than the aggregation, and from there the fix was a short conversation — aggregate shipments to one row per order before joining, or deduplicate on the shipment key, with a sentence about which she would choose if partial shipments were real. The interviewer’s conclusion, in the way these debriefs are usually described, was that she debugged the way the job requires: by comparing counts at boundaries instead of re-reading code that had already fooled her once. A wrong intermediate number, announced early and investigated aloud, can raise an evaluation; the same number, defended or unnoticed, ends the discussion.
The take-home that died on the larger file
Consider a data engineer who submitted a take-home he was quietly proud of: clean functions, tidy output, every figure on the sample file correct. The assessment used two files, the visible sample and a hidden evaluation file roughly fifty times larger, and his solution — which read the entire input into a list, then built two further lists from it — exhausted the memory available to the grader before it produced a single row. The decision points were all in the first hour. He had taken the sample file’s size as his mental model of the problem, had not asked what “large” might mean for the real version, though the task description used the word, and had never paused on the one structural choice — streaming the input row by row, holding only running aggregates — that costs almost nothing on a small file and is the difference between finishing and not finishing on a large one. The interviewer’s conclusion was not that the candidate lacked knowledge; his code showed the opposite. It was that he had optimised for the test he could see. The standing advice from this scene: treat every take-home input as a sample of something bigger, state your assumptions about scale in the submission’s notes, and prefer the streaming shape whenever the computation allows it — which, for grouping, counting, summing and top-k work, is nearly always.
The rerun that saved the candidate
Consider a data engineer in a systems-leaning Python round who was handed a broken loader, much like the one in Question 9, and told the job had already failed once that morning and been rerun by hand. Where several candidates before her had begun by rewriting the parsing code — the part that was not broken — she began by asking two questions: what identifies a row, and what did the first run manage to commit before it died. She built the rest of the round on the answers: a delete scoped to the load date, the insert in the same transaction, an upsert on the key for late corrections. Then she did the thing that, by the interviewer’s later account, settled the evaluation. Unprompted, she described how she would prove the fix rather than assert it: run the load three times, compare row count and totals after each run, kill the process halfway through a fourth run, run it a fifth time, and compare again. It is the verification habit, more than any individual clause, that interviewers in these accounts say they are hiring for — because the engineer who designs the test for idempotency will also design the reconciliation check nobody asked for, on the pipeline nobody is watching, in the month when it matters. In data work, the correct answer is the one that is still correct after something has gone wrong.
Keeping the notebook that makes the next round easier
Every question in this set becomes easier the second time you meet it, but only if the first meeting left a record. Candidates who improve fastest between interview loops keep a personal question-and-answer notebook: the question as it was actually posed, the dataset it came with, the answer they gave, the place it broke, and the corrected version they worked out afterwards. Ten questions written up that way are worth more than a hundred skimmed in a list, because the notebook captures the part no public guide can — your own wrong answers, in your own words, with the fix attached.
That notebook is also, quietly, a career file. The worked answers in it are evidence of how you think, and they belong with the rest of the record you would want to keep if a laptop went back to an employer tomorrow: your best project write-ups, the reviews that mention your work, the promotion case you assembled. Keeping that file in a private, local-first vault you control — VaultBook is built for exactly that kind of personal record-keeping — means the preparation compounds across employers instead of scattering across browser tabs, chat windows and machines you no longer own. Build the notebook question by question, and the next loop starts from your answers, not from zero.
A seven-day study plan
Seven days will not make anyone a different engineer, but a focused week is enough to convert broad familiarity into answers that hold up when someone runs the code. The plan below assumes roughly two hours a day alongside a job or a job search, and it is ordered so that each day’s work is used by the days after it. Adjust the hours, not the order.
Day 1 — Files and the shape of data. Read CSV and JSON with the standard library until it is boring:
csv.DictReader,json.loadsline by line for newline-delimited JSON, explicit encodings, context managers every time. End by writing one parser that skips malformed rows, counts them, and reports the count — the most reusable pattern in this set.Day 2 — Dictionaries, grouping and counting. Rebuild every pandas instinct by hand: group-and-sum with a dictionary, counting with
collections.Counter, indexing records by key, detecting duplicates by tracking seen keys. Finish with three grouping problems done without importing pandas at all.Day 3 — pandas with intent. Repeat Day 2’s problems in pandas and compare the versions line by line:
groupbywith named aggregations,mergewithvalidateandindicator,sort_valueswith mixed directions andna_position, andrankunder”min”,”dense”and”first”until you can predict each output before running it.Day 4 — Memory and generators. Rewrite Day 1’s parser as a generator, chain it into a grouping generator, and process the largest file you can find while watching memory stay flat. Learn to say precisely when a pipeline must materialise — sorting, joins against an indexed side — and when it must not.
Day 5 — Loads, keys and failure. Work Question 9 until the pattern is reflexive: transactions, delete-and-reload by partition, upsert by key, a reconciliation check. Then deliberately break your own loader — kill it mid-run, run it twice, feed it a wrong-date file — and confirm each failure leaves the table correct.
Day 6 — Timed rehearsal. Sit two full questions from this set under interview conditions, narrating out loud from the first minute. Afterwards, mark yourself as an interviewer would: not on whether the code eventually worked, but on when you stated your assumptions, checked a row count, and named your edge cases.
Day 7 — The explanation round, and rest. Spend the morning on the skill the other days do not test: explaining a technical decision in writing, in one page, to a senior reader outside your specialty. Hiring-manager rounds increasingly include exactly this — a short written account of a pipeline you built, a trade-off you chose, a failure you owned — and candidates who write fluently about their work are remembered differently from candidates who only code fluently.
That last exercise deserves a method rather than a hope. Take one decision from your Day 5 work — why the delete is scoped to a partition, say, or why an upsert rather than an append — and write it as a structured explanation: the situation, the options, the choice, the evidence that the choice worked. Short timed drills help here; working through Great Gatsby essay practice is one way to rehearse the underlying muscle of building a clear, structured written answer under a prompt, the same muscle a one-page pipeline explanation draws on. Then close the laptop for the rest of the day; a rested candidate explains better than a crammed one, and explanation, by Day 7, is most of the job.
Frequently asked questions
Q: How much pandas do I need if the role is mostly pipelines and SQL?
Enough to be dangerous in the specific ways interviews probe: grouping with named aggregations, merging with validation, handling missing values deliberately, and ranking within groups. Most pipeline-heavy roles will not test obscure reshaping, but they will test whether a join can silently multiply rows and whether you would notice. Pair pandas fluency with the plain-Python equivalent of each operation, because the strongest answers move between the two — a dictionary grouping to explain the logic, a groupby to express it at scale. If a job description names a dataframe tool, practise in that tool, but learn the concepts in pandas first, since the concepts transfer and the interview questions are usually written against them.
Q: Should I solve problems with generators even when a list would pass?
Use the generator when the data’s size is unknown, unbounded, or described as large, and say why while you write it; use the list freely when the data is plainly small and a list is clearer. Interviewers rarely reward a generator used as decoration, and a generator carries real costs — it can be consumed only once, it cannot be indexed, and its errors surface late, at consumption rather than creation. The judgement being tested is the match between tool and situation. The strongest pattern is to build the pipeline as generators, then materialise exactly once, at the point where the answer is needed, and to name that point out loud as you reach it.
Q: What if I cannot finish a question in the time given?
A well-explained partial answer, with correct code for the parts you completed and a clear account of what remains, regularly outscores a rushed, complete answer that fails on the edge cases you never mentioned. Protect the structure: state the approach first, write the straightforward version, name the edge cases even if you handle only some of them, and keep narrating so the interviewer can see the reasoning they are actually scoring. If you are stuck, say where, precisely — “I know the grouping is right and I am unsure of the tie-break” is a sentence that invites a useful hint. Silence, by contrast, gives the interviewer nothing to credit and nothing to help with.
Q: Do I need algorithms practice for data engineering interviews?
Some, of a particular kind. The large-company loops may include a general algorithms round, and for those there is no substitute for practising the standard patterns. But across data-focused loops, the recurring questions are algorithms in work clothes: grouping and counting, deduplication, top-k selection, merging sorted inputs, and two-pointer or dictionary-based lookups over records. Practise those until they are reflexes, in the shapes this set uses, before investing heavily in exotic structures you are unlikely to meet outside a generalist loop. A useful test for any practice problem is whether you can describe a pipeline you have seen that contains it; if you can, it belongs in your preparation, and if you cannot, it belongs after the ones you can.
Q: How should I talk about a pipeline failure from my own work?
Plainly, specifically, and with the numbers attached. Choose a real incident — a duplicated load, a silent schema change, a join that fanned out — and walk through the symptom, how you localised it, the root cause, and what you changed so that class of failure now announces itself instead of hiding. Interviewers rate these accounts highly because they are nearly impossible to fabricate in detail, and the follow-ups — what check would have caught it sooner, what did the reconciliation show — reward exactly the habits this set tests. Never blame a colleague or a tool without naming what your own code contributed; ownership is the quality the story is meant to demonstrate.
Q: What should I do in the first five minutes of a Python round?
Clarify, in this order: the input’s shape and size, what identifies a record, what should happen with missing and duplicate values, and what the output must look like. Write those answers where the interviewer can see them, because half of them will decide your approach — streaming or in memory, dictionary or dataframe, sort or heap — and because asking them signals the habit every question in this set is designed to detect. Then state your plan in two or three sentences before writing code, including the edge cases you intend to handle. Candidates often fear that questions consume coding time; in practice, the five minutes spent here are the cheapest in the round, because they prevent the twenty-minute rewrite that an unasked question about duplicates so often causes.
Sources and last checked
The ten questions in this set are original variants written in the patterns candidates report meeting in Python rounds for data engineering roles; they are not reproduced from any company’s interview, and any resemblance to a specific employer’s question reflects how standardised these patterns have become. The references for language and library behaviour are the official Python documentation — in particular the sections on sorting, generators, the csv and sqlite3 modules, and the collections library — and the official pandas documentation, in particular the guides to grouping, merging, sorting and ranking. Statements about what candidates discuss reflect recurring themes in public candidate discussion, presented as discussion rather than as findings. Last checked 4 December 2026.
— Pinnacle Report. That closes Python for Data Engineering Set 1. If a Python question caught you out in a recent round — the join that multiplied, the sort that lied, the load that doubled — reply and tell us the question, exactly as it was put to you. The best of them, anonymised and rebuilt as worked variants, will anchor the next set.

