Build a Holiday Gift Matcher from CSV Input
StringsModel answerLast updated
Parse participant data from a CSV string with quoted fields, validate entries, and create a round-robin assignment where no one gives a gift to themselves.
You're building a holiday gift exchange coordinator. Given participant information in CSV format, you need to parse the data, validate it, and generate assignments where each person gives exactly one gift and receives exactly one gift, with no one assigned to themselves.
Input Format
A CSV-formatted string where each line contains:
- Participant name (may contain commas if quoted)
- Email address
Example:
Alice,[email protected]
"Lee, Jordan",[email protected]
Taylor,[email protected]
Requirements
Parsing:
- Handle quoted fields correctly (commas inside quotes should not split fields)
- Support escaped quotes within quoted fields (
""represents a literal") - Ignore empty lines
- Handle both Unix (
\n) and Windows (\r\n) line endings
Validation:
- Each line must have exactly 2 fields (name and email)
- Email addresses must be unique (case-insensitive)
- Names and emails must be non-empty after trimming whitespace
- Emails must contain an
@symbol - Raise descriptive errors with line numbers for invalid input
- Require at least 2 participants
Assignment:
- Create a mapping from each email to another email (the gift recipient)
- No participant should be assigned to themselves
- Accept an optional
seedparameter for deterministic output
Output
Return a dictionary mapping each participant's email to their assigned recipient's email.
Example output:
{
"[email protected]": "[email protected]",
"[email protected]": "[email protected]",
"[email protected]": "[email protected]"
}
Constraints
- 2 ≤ number of participants ≤ 10,000
- Emails are the unique identifier for each participant
Hints
Hint 1
Build a character-by-character parser that tracks whether you're inside quotes to handle embedded commas correctly
Hint 2
Normalize email addresses by converting to lowercase and trimming whitespace before checking for duplicates
Hint 3
Once you have a valid list of participants, shuffle them and create a circular assignment pattern to guarantee no self-assignments
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem combines three distinct challenges: implementing a robust CSV parser, performing thorough data validation, and constructing a valid gift assignment algorithm. I'll walk through each component.
Approach
1. CSV Parsing with State Machine
The core parsing challenge is handling quoted fields that may contain commas. A simple split(',') fails for input like "Lee, Jordan",[email protected].
I implement a character-by-character parser with a boolean state variable in_quotes:
- Outside quotes: Commas delimit fields, newlines delimit rows
- Inside quotes: Commas and newlines are literal characters
- Escaped quotes: Two consecutive quotes (
"") represent a single literal quote - Error detection: If input ends while
in_quotesis true, raise an error for unclosed quotes
The parser returns a list of (line_number, fields) tuples, preserving line numbers for error reporting.
2. Validation
For each parsed row:
- Skip rows where all fields are empty or whitespace
- Verify exactly 2 fields exist
- Extract and normalize the email:
email.strip().lower() - Check that the name is non-empty and email contains
@ - Track seen emails in a set; reject duplicates
- After processing all rows, verify at least 2 participants remain
Each validation failure raises a ValueError with the specific line number and problem description.
3. Assignment Algorithm: Circular Permutation
The key insight is that we need a derangement (a permutation where no element maps to itself). Rather than shuffling and checking for self-assignments, I use a constructive approach:
- Shuffle the participant list using the provided seed
- Assign each person at index
ito the person at index(i + 1) % n
This creates a single cycle through all participants. For any n ≥ 2, (i + 1) % n never equals i, so no one is assigned to themselves. The assignment is guaranteed valid by construction—no retry logic needed.
Why This Works
Parsing correctness: Every character is consumed in exactly one state. The in_quotes flag ensures commas within quoted fields don't split the field. The after_quote flag catches malformed input like "Name"garbage.
Assignment correctness: The modular arithmetic creates a bijection (one-to-one mapping). Since (i + 1) mod n = i would require n to divide 1 (impossible for n ≥ 2), no participant maps to themselves.
Reproducibility: Using a local random.Random(seed) instance ensures the same seed always produces the same assignment without affecting global random state.
Trade-offs
This approach generates only single-cycle derangements. For n = 4, it never produces two mutual pairs like A↔B, C↔D. This is actually desirable for many gift exchanges—it creates no small cliques and makes the reveal sequence straightforward.
If uniformly random derangements are required, use rejection sampling: shuffle, then retry while any element maps to itself. The acceptance probability is approximately 1/e ≈ 0.368, so expected retries are about 2.7.
Complexity
- Time: O(L + n), where L is input length and n is participant count. Parsing is a single pass; shuffling and assignment are linear.
- Space: O(L + n) for parsed data, participant list, and output dictionary.
Common Mistakes
- Using
line.split(',')directly: Fails on quoted fields with embedded commas - Shuffle-and-swap algorithms: Checking for self-assignments and swapping pairs requires careful logic to avoid introducing new self-assignments. The cyclic approach avoids this entirely.
- Case-sensitive email comparison:
[email protected]and[email protected]should be treated as duplicates - Poor error messages: Validation errors should include line numbers to help debug large files
Implementation
import random
from typing import Optional
def _parse_csv(text: str) -> list[tuple[int, list[str]]]:
"""Parse CSV with RFC 4180-style quoting. Returns (line_number, fields) per row."""
rows = []
row, field = [], []
in_quotes = False
after_quote = False
line_num, row_start = 1, 1
i = 0
while i < len(text):
char = text[i]
if in_quotes:
if char == '"':
# Check for escaped quote
if i + 1 < len(text) and text[i + 1] == '"':
field.append('"')
i += 1
else:
in_quotes = False
after_quote = True
else:
if char == '\n':
line_num += 1
field.append(char)
elif char == ',':
row.append(''.join(field))
field, after_quote = [], False
elif char == '\n':
row.append(''.join(field))
rows.append((row_start, row))
row, field, after_quote = [], [], False
line_num += 1
row_start = line_num
elif char == '\r':
pass # Ignore carriage returns
elif after_quote:
if not char.isspace():
raise ValueError(f"Line {line_num}: unexpected content after closing quote")
elif char == '"':
if ''.join(field).strip():
raise ValueError(f"Line {line_num}: quote within unquoted field")
field, in_quotes = [], True
else:
field.append(char)
i += 1
if in_quotes:
raise ValueError(f"Line {row_start}: unclosed quote at end of input")
# Handle final row if exists
if field or row:
row.append(''.join(field))
rows.append((row_start, row))
return rows
def generate_exchange(csv_data: str, seed: Optional[int] = None) -> dict:
"""Generate gift exchange assignments from CSV participant data."""
participants = []
seen_emails = set()
for line_num, fields in _parse_csv(csv_data):
# Skip empty lines
if all(not field.strip() for field in fields):
continue
if len(fields) != 2:
raise ValueError(f"Line {line_num}: expected 2 fields, found {len(fields)}")
name, email = fields[0].strip(), fields[1].strip().lower()
if not name:
raise ValueError(f"Line {line_num}: name cannot be empty")
if '@' not in email:
raise ValueError(f"Line {line_num}: invalid email format")
if email in seen_emails:
raise ValueError(f"Line {line_num}: duplicate email {email}")
seen_emails.add(email)
participants.append(email)
if len(participants) < 2:
raise ValueError("At least 2 participants required for gift exchange")
# Create circular assignment
rng = random.Random(seed)
shuffled = participants[:]
rng.shuffle(shuffled)
n = len(shuffled)
return {shuffled[i]: shuffled[(i + 1) % n] for i in range(n)}
For the example input with 3 participants, this produces a 3-cycle where each person gives to the next in the shuffled order, and the last person gives back to the first. With seed=42, you might get alice→jordan→taylor→alice.