Katkat

Parse a CSV and Generate a Gift Exchange

ShopifySoftware Engineer · Technical Screen

Last updated

This problem tests string parsing, data validation, and algorithm design by requiring the implementation of a secret-santa style matching system from unstructured CSV data.

Problem Statement

You are tasked with building a gift-exchange generator. You receive a CSV-formatted string where each line contains a user's name and email, separated by a comma. The CSV may contain quoted fields (e.g., "Doe, John",[email protected]) to handle commas within names.

Your task is to write a function generate_exchange(csv_data: str) -> dict that returns a mapping where each participant is assigned exactly one unique person to give a gift to.

Requirements

  1. Parsing: Properly handle quoted fields in the CSV.
  2. Validation: Ensure each participant has a unique email. Ignore empty lines. Raise an error if fewer than 2 participants are provided.
  3. Assignment Logic: Assign each person a gift recipient such that no one is assigned to themselves (a derangement).
  4. Reproducibility: Allow an optional seed parameter to ensure the matching is deterministic for testing purposes.

Constraints

  • Input size: 2 to 10,000 participants.
  • Emails are unique identifiers.

Example

Input:

Alice,[email protected]
"Smith, Bob",[email protected]
Charlie,[email protected]

Output (Possible mapping):

{
  "[email protected]": "[email protected]",
  "[email protected]": "[email protected]",
  "[email protected]": "[email protected]"
}

Edge Cases

  • Invalid CSV formats (e.g., unclosed quotes).
  • Duplicate email addresses across different lines.
  • Minimal number of participants (n=2).

Hints

Hint 1

Use a state machine or a regex-based parser to handle commas trapped inside quoted fields before splitting the lines.

Hint 2

For the matching logic, shuffle the list of participants and try to assign each to the next person in the list, handling the wrap-around case to ensure no one is their own recipient.

Hint 3

If a person is assigned to themselves after shuffling, try swapping their recipient with another person to satisfy the derangement constraint.

Follow-up questions

  • How would you modify your solution to support 'forbidden pairs' (e.g., partners who should not be assigned to each other)?
  • How would you ensure the privacy of the participants so that the gift-giver cannot determine who is receiving the gift until the reveal?
  • If this were a high-scale service, how would you persist the exchange mappings to prevent losing the assignments if the server crashes?