Rule-Driven CSV Validator with Cross-Field Word Overlap
StringsModel answerLast updated
Design and implement a configurable validator that flags per-field rule violations and excessive word overlap across fields in a company CSV.
A batch of company records arrives as CSV text: the first line is a header naming the columns, and each subsequent line is one company. Build a validator that checks each record against a configurable rule set and reports, per record, every rule it violates. Nothing is fixed: the required columns, min/max length limits, forbidden words, words to ignore during comparison, which columns are compared for overlap, and the overlap threshold are all passed in as configuration.
Example input (columns and values are illustrative):
id,name,legal_name,description
1,Acme Widgets,Acme Widgets LLC,Industrial widgets for factories
2,,Bright Labs LLC,
3, ACME widgets , acme widgets llc,Widgets
Two stages of work:
Stage 1 — Single-field checks. For each record, verify (a) every required field is present and non-empty, (b) each field under a length rule satisfies its min and/or max, and (c) no checked field contains a forbidden word. Each failure must be reported with the record's identifier, the field name, and which rule failed.
Stage 2 — Word overlap across fields. Tokenize several configured fields of the same record, fold case, collapse whitespace, strip punctuation per an agreed rule, and remove ignored words (e.g. LLC). Compute an overlap measure (count of shared tokens or a ratio) and flag records that violate the threshold in the configured direction (too little or too much sharing). Merge these failures into the Stage 1 report without double-counting.
Expected outputs must be deterministic: same input, same report order.
Things to nail down with the interviewer: whether whitespace-only counts as missing; whether length is measured on raw or trimmed values and whether limits are one-sided or two-sided; whether forbidden words match whole words or substrings and whether they can be multi-word phrases; which columns are compared and the exact overlap formula and threshold direction; punctuation handling; whether to report all failures or just the first; and the output shape (per-failure list, per-record pass/fail, or both).
Hints
Hint 1
Parse with a real CSV reader — quoted commas and unbalanced columns must be handled explicitly, not split on commas.
Hint 2
Normalize once, reuse everywhere: a single function that lowercases, trims, strips punctuation and drops ignored tokens keeps both stages consistent.
Hint 3
Define overlap precisely (e.g. Jaccard = shared / union) and state what the threshold direction means; then test empty-after-normalization fields, which typically should not fire an overlap failure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Design philosophy. Treat rules as data, not code. A rule is a small object (scope, kind, params) — e.g. ("required", "name", None), ("length", "description", {"min": 10, "max": 200}), ("forbidden", "*", ["spam", "test"]). A record validator loops over rules, applies each to the relevant fields, and accumulates Failure(record_id, field, rule, detail). Adding a new check is then a config entry, not an edit to a growing if chain. The overall pipeline is: parse CSV → validate each row → emit deterministic report. Runtime is O(N·F·L) where N is rows, F fields per row, L average text length; normalization is linear and done once per field per record.
Parsing. Use a real CSV library (csv.reader in Python). Enforce or detect: header present; row length matches header length. For rows with too few columns, pad with None and let the required rule flag them; for too many, flag a malformed_row failure. Skip blank lines. Never reorder or repair data. Keep the original row index as the stable identity even if id is missing or blank.
Stage 1 details — the decisions that trip people up.
- Missing: a value of
None,"", or whitespace-only (after trimming) counts as missing. State this explicitly; interviewers probe it. Keep anid-like column required but not length-checked. - Length: measure after whitespace trimming by default; allow
strip=Falseconfig for the rare case where padding matters. Support bothminandmaxindependently; a field with onlymaxis common for descriptions. - Forbidden words: decide substring vs whole-word and case sensitivity. Whole-word, case-insensitive matching via tokenization is the safer default (avoids flagging "Scunthorpe"-style false positives inside legitimate words), but allow a
match: "substring"mode for things like URLs. Multi-word phrases mean you must search a normalized string with word boundaries, not a token set. Report the matched term and the offset optionally. - Do not deduplicate failures by field when two distinct rules fail — a missing field also fails a length
min; report both, since they're different rules. But do dedupe identical(field, rule)pairs if multiple forbidden words hit the same field — or report each hit; pick one and document it.
Stage 2 — normalization and overlap. One shared normalizer:
- Lowercase (casefold).
- Replace punctuation (
. , ; : ! ? ( ) / -) with spaces — unless the agreed rule keeps internal hyphens. - Split on whitespace (
\s+). - Drop tokens in the ignore set (
llc,inc,co,the). - Optionally drop empty tokens; if the field normalizes to nothing, treat it as having zero tokens.
Then for the configured field pair/set, compute the measure. Two sensible options:
- Shared-count:
|A ∩ B|(on sets, so repeats don't inflate). - Jaccard ratio:
|A ∩ B| / |A ∪ B|, in[0, 1], robust to length. Pick one and state why (Jaccard handles one long description vs. a short name better).
Threshold direction depends on the goal. To catch a description that just parrots the name, use max_ratio (flag if Jaccard > 0.8). To ensure a description actually adds words, use min_shared (flag if shared count < 3). Handle degenerate cases explicitly: if both fields are empty after normalization, or one is empty, decide — common choice is to skip the overlap rule (empty fields are already handled by Stage 1) or to treat as zero overlap and let the min rule fire. Document it.
Merging reports. Keep one list of Failure objects keyed by (record_index, field, rule_id). Stage 2 emits rule_id="overlap:name/description". Because the key includes the rule, Stage 2's overlap failure never collides with a Stage 1 empty-field failure on the same field, but you avoid emitting the same overlap failure twice when comparing multiple pairs. Sort output by (record_index, field, rule) for determinism, or preserve input order with stable per-record grouping — state which.
Testing matrix. Pass and fail for each rule; whitespace-only required field; quoted value containing a comma; row with too few/many columns; forbidden word in mixed case and as a substring vs. whole word; multi-word forbidden phrase; token normalization (ACME widgets vs acme widgets); fields that normalize to nothing; repeated tokens; Jaccard exactly equal to the threshold (inclusive or exclusive — define it); Unicode case/accents if relevant.
Common mistakes. Splitting on commas naively; forgetting .strip() before length checks; case-sensitive forbidden matching; recomputing tokens in Stage 2 causing drift from Stage 1; using a list instead of a set for intersection (over-counting repeats); ambiguous threshold boundary; non-deterministic output; silently repairing malformed rows instead of reporting them.
Complexity. Parsing O(input size); per-row validation O(F·L + shared tokens) with hash-set intersections giving near-linear overlap; memory O(max row width). Report is O(failures). Everything is a single pass, which matters for large batches.
Answering style. Lead with the config-driven design, then walk the two stages, explicitly stating each normalization and threshold decision you made (since the prompt leaves them open), then cover edge cases and the test matrix. Interviewers reward stated trade-offs (whole-word vs substring, count vs Jaccard, include vs exclude on the boundary) far more than a perfect but unexplained implementation.