Link Order User IDs to Customer Names

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You receive three headerless 2D tables — customers, orders, and products — and must return a dictionary mapping each matched order's userId to the customerName who placed that order.

The row layout of each table is:

  • customers: [customerName, email, productName, quantity], where quantity is an integer encoded as a string, email may be blank ("" or None), and each customer orders only one productName.
  • orders: [userId, email, orderTotal], where email may be missing (None or "") and orderTotal is an integer or decimal amount encoded as a string.
  • products: [productName, unitPrice], where unitPrice is an integer or decimal price encoded as a string.

Resolve each row [userId, email, orderTotal] in orders using two mutually exclusive rules:

  1. Present email (email is neither None nor ""): Match strictly to customers whose email equals orders.email. Never fall back to bill-amount matching if the provided email is unknown.
  2. Missing email (email is None or ""): Match to customers whose expected bill quantity * unitPrice (computed with exact decimal arithmetic after joining customers.productName to products.productName) equals orderTotal.

Whenever multiple customers match a single order (either sharing the same email or yielding the same expected bill), break ties deterministically by choosing the lexicographically smallest customerName (standard ASCII code-point order, e.g. "Nadia" < "Tariq"). If an order matches zero customers, omit its userId from the output dictionary.

def join_user_ids_to_names(
    customers: List[List[str]],
    orders: List[List[Optional[str]]],
    products: List[List[str]],
) -> Dict[str, str]:
    ...

Examples

Example 1

Input:
  customers = [["Elena", "elena@shop.io", "Lamp", "3"], ["Marco", "marco@shop.io", "Mug", "4"]]
  orders    = [["ord_1", "elena@shop.io", "45"], ["ord_2", None, "28"]]
  products  = [["Lamp", "15"], ["Mug", "7"]]
Output:
  {"ord_1": "Elena", "ord_2": "Marco"}

"ord_1" includes "elena@shop.io", matching "Elena" directly by email. "ord_2" has None for its email, so we compare its total "28" against each customer's expected bill (Elena: 3 * 15 = 45; Marco: 4 * 7 = 28), matching "Marco".

Example 2

Input:
  customers = [["Tariq", "tariq@shop.io", "Poster", "3"], ["Nadia", "nadia@shop.io", "Frame", "2"]]
  orders    = [["ord_9", None, "24"]]
  products  = [["Poster", "8"], ["Frame", "12"]]
Output:
  {"ord_9": "Nadia"}

"ord_9" has no email and total "24". Both Tariq (3 * 8 = 24) and Nadia (2 * 12 = 24) match that exact bill, and alphabetical tie-breaking selects "Nadia" ("Nadia" < "Tariq").

Example 3

Input:
  customers = [["Priya", "", "Tea", "3"], ["Owen", "owen@shop.io", "Scone", "2"]]
  orders    = [["ord_4", "", "6.75"], ["ord_5", "owen@shop.io", "3.50"]]
  products  = [["Tea", "2.25"], ["Scone", "1.75"]]
Output:
  {"ord_4": "Priya", "ord_5": "Owen"}

An empty string "" also denotes a missing email. "ord_4" reconciles "6.75" against 3 * 2.25 = 6.75 to match "Priya", while "ord_5" matches "Owen" by email.

Constraints

  • All three inputs are well-formed 2D lists (with no header row)
  • email fields in orders (and customers) may be None or ""; blank customer emails never match by email
  • Numeric strings (quantity, unitPrice, orderTotal) represent valid non-negative integers or terminating decimals that may differ in trailing zeros (e.g., "7.5" vs. "7.50")
  • Break ties by picking the smallest customerName under <, and omit any userId with no matching customer

Step-by-step walkthrough

  1. Understand the three tables and the two matching paths

    We receive three tables as lists of rows (with no header row) and want to build a dictionary mapping each order's userId to the customerName who placed it:

    • customers: [customerName, email, productName, quantity]
    • orders: [userId, email, orderTotal]
    • products: [productName, unitPrice]

    Every order connects to a customer through one of two paths depending on whether the order's email is filled in:

    orders: [userId, email, orderTotal]
                       |         |
           (email is   |         | (email is None or "")
            present)   v         v
            customers.email    orderTotal == customers.quantity * products.unitPrice
                       \         /
                        v       v
                   customerName  --->  result[userId] = customerName
    

    Before writing code, let's settle four important edge behaviors from the rules and examples:

    1. Missing emails: Both None and "" count as missing. On an order, a missing email triggers Rule 2 (match by total). On a customer (such as Priya in Example 3), a missing email simply means that customer can only be found by total, never by email.
    2. Tie-breaker: Multiple customers can produce the same expected total (3 * 8 == 24 and 2 * 12 == 24 in Example 2) or share an email. Whenever two candidates tie, we keep the lexicographically smallest name ("Nadia" < "Tariq" in alphabetical / character-code order).
    3. No fallback when email is present: Rule 2 applies only when orders.email is missing. If an order provides an unknown email, we do not fall back to matching its total.
    4. Unmatched orders: If an order matches no customer, we leave its userId out of the output dictionary.
  2. Why scanning every row per order is too slow

    A straightforward brute-force approach loops over every order, scans every customer to check the email or compute their total, and scans products to look up unitPrice.

    If there are O orders, C customers, and P products, nested loops take O(O * C * P) time. Even if we put products in a dictionary first, scanning all C customers for every order still takes O(O * C) time.

    Notice that every order asks one of two fixed questions: - "Which customer owns this email?" - "Which customer's quantity * unitPrice equals this orderTotal?"

    Neither answer changes from one order to the next. If we precompute two lookup dictionaries once up front, every order becomes a single O(1) dictionary lookup.

  3. Represent money exactly with fractions

    All numbers arrive as strings like "24", "2.25", and "3.50". How should we store keys in our expected-total dictionary? Neither raw strings nor floating-point numbers (float) are safe:

    Why strings fail:
      Customer: 2 * 1.75 = 3.5       -> string "3.5"
      Order:                         -> string "3.50"
      "3.5" == "3.50"  is False! (Same dollar amount, different text.)
    
    Why binary floats fail:
      Customer: 3 * 0.1              -> float 0.30000000000000004
      Order:    "0.30"               -> float 0.3
      0.30000000000000004 == 0.3  is False! (Binary rounding error.)
    

    Python's built-in fractions.Fraction solves both problems cleanly. Fraction("6.75") and Fraction("3") * Fraction("2.25") both simplify to the exact rational number 27/4. Equal Fraction values compare equal (==) and produce the exact same dictionary hash, making Fraction ideal as a dictionary key.

  4. Write helpers for missing emails and tie-breaking

    Let's put the "null or empty" check and the "smallest name wins" tie-breaker into two tiny, self-explanatory helper functions. Resolving ties at insertion time means our lookup dictionaries always hold the winning name right away.

    from fractions import Fraction
    from typing import Any, Dict, Optional
    
    
    def is_missing_email(email: Optional[str]) -> bool:
        """Return True when an email field is null (None) or an empty string."""
        # Both None and "" indicate that the email was not recorded.
        return email is None or email == ""
    
    
    def store_smaller_name(lookup: Dict[Any, str], key: Any, candidate_name: str) -> None:
        """Insert candidate_name under key, keeping the lexicographically smallest name on ties."""
        # Break ties deterministically using alphabetical (ASCII code-point) order.
        if key not in lookup or candidate_name < lookup[key]:
            lookup[key] = candidate_name
    
  5. Precompute the email and expected-total lookup tables

    Now we build the two customer indexes in two linear passes:

    1. Product price lookup (unit_price_by_product): Map each productName to Fraction(unitPrice).
    2. Customer lookups (name_by_email and name_by_total): For each customer:
      • If their email is non-empty, record customer_email -> customer_name via store_smaller_name. (Skipping empty emails ensures an empty string never enters name_by_email.)
      • If their productName has a known price, compute Fraction(quantity_str) * unit_price_by_product[product_name] and record expected_total -> customer_name via store_smaller_name.

    Here is how those tables look for Example 2 (Tariq buys 3 Poster at 8; Nadia buys 2 Frame at 12):

    unit_price_by_product:
      "Poster" -> Fraction(8, 1)
      "Frame"  -> Fraction(12, 1)
    
    Building name_by_total:
      1. Process Tariq: 3 * 8  = Fraction(24, 1) -> name_by_total[24] = "Tariq"
      2. Process Nadia: 2 * 12 = Fraction(24, 1) -> "Nadia" < "Tariq", so name_by_total[24] = "Nadia"
    
    from fractions import Fraction
    from typing import Dict, List, Tuple
    
    
    def build_customer_indexes(
        customers: List[List[str]],
        products: List[List[str]],
    ) -> Tuple[Dict[str, str], Dict[Fraction, str]]:
        """Build two O(1) lookup maps: email -> smallest name, and expected total -> smallest name."""
        # Phase 1: Index product prices as exact fractions.
        # unit_price_by_product: {product_name: Fraction}, e.g. {"Tea": Fraction(9, 4)}
        unit_price_by_product: Dict[str, Fraction] = {}
        for product_name, unit_price_str in products:
            # Fraction parses decimal strings like "2.25" or "6.75" without float rounding error.
            unit_price_by_product[product_name] = Fraction(unit_price_str)
    
        # Phase 2: Index every customer by email (when present) and by quantity * unitPrice.
        # name_by_email: {email_str: smallest_customer_name}, e.g. {"owen@shop.io": "Owen"}
        # name_by_total: {expected_total_fraction: smallest_customer_name}, e.g. {Fraction(27, 4): "Priya"}
        name_by_email: Dict[str, str] = {}
        name_by_total: Dict[Fraction, str] = {}
    
        for customer_name, customer_email, product_name, quantity_str in customers:
            # Never index empty customer emails, or an empty order email could match by mistake.
            if not is_missing_email(customer_email):
                store_smaller_name(name_by_email, customer_email, customer_name)
    
            # Only compute an expected total if the customer's product exists in the products table.
            if product_name in unit_price_by_product:
                expected_total = Fraction(quantity_str) * unit_price_by_product[product_name]
                store_smaller_name(name_by_total, expected_total, customer_name)
    
        return name_by_email, name_by_total
    
  6. Match every order and trace Example 3

    With both lookup dictionaries ready, we loop through orders once. Each order checks its own order_email: - Missing (None or "") -> look up Fraction(order_total_str) in name_by_total. - Present -> look up order_email in name_by_email.

    Let's trace Example 3 to watch both paths work together:

    Inputs (Example 3):
      customers = [["Priya", "", "Tea", "3"], ["Owen", "owen@shop.io", "Scone", "2"]]
      products  = [["Tea", "2.25"], ["Scone", "1.75"]]
      orders    = [["ord_4", "", "6.75"], ["ord_5", "owen@shop.io", "3.50"]]
    
    Built indexes:
      name_by_email = {"owen@shop.io": "Owen"}             (Priya skipped: email is "")
      name_by_total = {Fraction(27, 4): "Priya",           (3 * 9/4 = 27/4)
                       Fraction(7, 2):  "Owen"}            (2 * 7/4 = 7/2)
    
    Order scan:
      - Order "ord_4": email is "" (missing)
          -> Fraction("6.75") == Fraction(27, 4)
          -> name_by_total[Fraction(27, 4)] == "Priya" => user_to_name["ord_4"] = "Priya"
      - Order "ord_5": email is "owen@shop.io" (present)
          -> name_by_email["owen@shop.io"] == "Owen"   => user_to_name["ord_5"] = "Owen"
    
    Result: {"ord_4": "Priya", "ord_5": "Owen"}
    
  7. Full solution

    Putting the helpers, index builder, and order loop together gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from fractions import Fraction
    
    
    def is_missing_email(email: Optional[str]) -> bool:
        """Return True when an email field is null (None) or an empty string."""
        # Both None and "" indicate that the email was not recorded.
        return email is None or email == ""
    
    
    def store_smaller_name(lookup: Dict[Any, str], key: Any, candidate_name: str) -> None:
        """Insert candidate_name under key, keeping the lexicographically smallest name on ties."""
        # Break ties deterministically using alphabetical (ASCII code-point) order.
        if key not in lookup or candidate_name < lookup[key]:
            lookup[key] = candidate_name
    
    
    def build_customer_indexes(
        customers: List[List[str]],
        products: List[List[str]],
    ) -> Tuple[Dict[str, str], Dict[Fraction, str]]:
        """Build two O(1) lookup maps: email -> smallest name, and expected total -> smallest name."""
        # Phase 1: Index product prices as exact fractions.
        # unit_price_by_product: {product_name: Fraction}, e.g. {"Tea": Fraction(9, 4)}
        unit_price_by_product: Dict[str, Fraction] = {}
        for product_name, unit_price_str in products:
            # Fraction parses decimal strings like "2.25" or "6.75" without float rounding error.
            unit_price_by_product[product_name] = Fraction(unit_price_str)
    
        # Phase 2: Index every customer by email (when present) and by quantity * unitPrice.
        # name_by_email: {email_str: smallest_customer_name}, e.g. {"owen@shop.io": "Owen"}
        # name_by_total: {expected_total_fraction: smallest_customer_name}, e.g. {Fraction(27, 4): "Priya"}
        name_by_email: Dict[str, str] = {}
        name_by_total: Dict[Fraction, str] = {}
    
        for customer_name, customer_email, product_name, quantity_str in customers:
            # Never index empty customer emails, or an empty order email could match by mistake.
            if not is_missing_email(customer_email):
                store_smaller_name(name_by_email, customer_email, customer_name)
    
            # Only compute an expected total if the customer's product exists in the products table.
            if product_name in unit_price_by_product:
                expected_total = Fraction(quantity_str) * unit_price_by_product[product_name]
                store_smaller_name(name_by_total, expected_total, customer_name)
    
        return name_by_email, name_by_total
    
    
    def join_user_ids_to_names(
        customers: List[List[str]],
        orders: List[List[Optional[str]]],
        products: List[List[str]],
    ) -> Dict[str, str]:
        name_by_email, name_by_total = build_customer_indexes(customers, products)
    
        # Phase 3: Match each order using email when present, or exact expected total when missing.
        # user_to_name: {user_id: matched_customer_name}, e.g. {"ord_1": "Elena", "ord_2": "Marco"}
        user_to_name: Dict[str, str] = {}
        for user_id, order_email, order_total_str in orders:
            if is_missing_email(order_email):
                # Rule 2: Email is missing, so reconcile using exact Fraction arithmetic.
                matched_name = name_by_total.get(Fraction(order_total_str))
            else:
                # Rule 1: Email is present, so match strictly by email with no fallback to total.
                matched_name = name_by_email.get(order_email)
    
            # Omit orders that do not match any known customer.
            if matched_name is not None:
                user_to_name[user_id] = matched_name
    
        return user_to_name
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine you run a small shop with a stack of paper receipts (orders), a roster of regular customers (customers), and a price sheet (products). Some receipts have the buyer's email printed right on them, while others left the email blank and only show the final dollar total. Instead of flipping through the entire customer roster and price sheet from top to bottom for every single receipt, you prepare two quick-reference phonebooks (hash maps, which are Python dictionaries that find a key in constant O(1) average time) once before you start:

  1. name_by_email: maps each customer's email address to their name.
  2. name_by_total: performs a relational join (combining rows from two tables that share a matching column, here productName) between customers and products to compute each customer's expected bill quantity * unitPrice, mapping that exact bill amount to their name.

Why do the obvious shortcuts fail? First, scanning all C customers and P products for every one of the O orders takes O(O * C * P) time instead of linear time. Second, storing money as strings or standard floating-point numbers (float) silently misses real matches: "3.50" and "3.5" are unequal strings, while binary floating-point rounding error (the tiny imprecision caused when decimals like 0.1 cannot be written finitely in base 2) makes 3 * 0.1 equal 0.30000000000000004 instead of 0.3. Representing prices and totals with fractions.Fraction — an exact rational number stored as an integer numerator over an integer denominator, like 27/4 for 6.75 — guarantees exact arithmetic and reliable dictionary lookups. Whenever two customers share the same total or email, we keep the smaller name in lexicographical order (alphabetical / character-code order, where "Nadia" < "Tariq").

Here is a trace of Example 1 with two customers, two products, and two orders:

Products:
  ["Lamp", "15"] -> unit_price_by_product["Lamp"] = 15
  ["Mug",  "7"]  -> unit_price_by_product["Mug"]  = 7

Customers:
  ["Elena", "elena@shop.io", "Lamp", "3"] -> email "elena@shop.io" -> "Elena", total 45 -> "Elena"
  ["Marco", "marco@shop.io", "Mug",  "4"] -> email "marco@shop.io" -> "Marco", total 28 -> "Marco"

Orders:
  1. ["ord_1", "elena@shop.io", "45"] -> email present -> name_by_email["elena@shop.io"] = "Elena"
  2. ["ord_2", None,            "28"] -> email missing -> Fraction("28") = 28
                                                       -> name_by_total[28]              = "Marco"

Output: {"ord_1": "Elena", "ord_2": "Marco"}

Complexity

Let P be the number of products, C be the number of customers, and O be the number of orders (treating individual price and quantity strings as short, bounded-length numbers so each Fraction parse takes constant time).

  • Time: O(P + C + O) average. We scan products once in O(P) to populate unit_price_by_product, scan customers once in O(C) doing at most two O(1) average dictionary updates per customer, and scan orders once in O(O) doing a single O(1) average dictionary lookup per order.
  • Space: O(P + C + O). unit_price_by_product stores up to P entries, name_by_email and name_by_total each store at most C entries, and the output dictionary user_to_name stores at most O entries.

Edge cases

  • Both None and "" on orders.email: Both represent a missing email and route the order to name_by_total.
  • Empty email on a customer row: Excluded from name_by_email so an order with "" never matches a customer by "both having blank emails"; that customer can still be matched through name_by_total.
  • Different decimal spellings of the same total: "3.5", "3.50", and Fraction("2") * Fraction("1.75") all reduce to Fraction(7, 2) and hash identically.
  • Ties on expected total or shared email: store_smaller_name keeps the lexicographically smallest customerName regardless of row order in customers (note that ASCII uppercase sorts before lowercase, so "Tariq" < "nadia").
  • Customer whose product is absent from products: Cannot be indexed in name_by_total, but still matches orders that carry their email.
  • Present email with no matching customer: Returns None from name_by_email and is omitted — it does not fall back to name_by_total, because Rule 2 applies only when the order email is missing.
  • Empty orders list: Returns {} cleanly.

Common mistakes

  • Comparing totals as float: 3 * 0.1 == 0.3 evaluates to False in IEEE 754 floating-point math, causing valid orders to go unmatched. Use Fraction or decimal.Decimal.
  • Comparing totals as formatted strings: "2" * "1.75" formatted naively gives "3.5", which misses an order total written "3.50".
  • Checking if order_email is None: instead of checking both None and "": An empty string "" is non-None, so forgetting order_email == "" sends blank-email orders to name_by_email instead of name_by_total.
  • Falling back to name_by_total when an email lookup fails: A present email is authoritative even if the order's dollar total happens to match another customer's expected bill.
  • Breaking ties by first-seen or last-seen row order: Overwriting unconditionally (lookup[key] = name) happens to pass Example 2 because "Nadia" appears after "Tariq", but fails whenever the alphabetically smallest name appears earlier in customers.

Follow-up questions

  • How would the data structures change if we needed to return every matching candidate name in sorted order instead of picking a single winner? Map each email and each expected Fraction total to a set of customer names (Dict[Any, Set[str]]), then return sorted(candidates) for each userId. Indexing stays O(P + C), while sorting and outputting candidate lists takes O(O * K log K) where K is the number of tied candidates for an order.
  • How should you preprocess email addresses if real-world logs contain mixed uppercase/lowercase letters or leading and trailing spaces? Normalize every email in one shared helper — clean = email.strip().lower() — before indexing customers and before looking up orders, and treat clean == "" as missing. Calling the exact same normalization function in both places guarantees consistent keys and ensures whitespace-only strings (" ") cleanly trigger the total-matching rule.
  • How would you write an equivalent relational database query in SQL without losing decimal precision? First compute each customer's expected total in a Common Table Expression (CTE — a named temporary result set defined with WITH) using a LEFT JOIN to products so customers without a product price can still match by email; then join orders using an OR condition gated on whether orders.email is empty, and group by user_id taking MIN(customer_name) for the tie-breaker (storing prices and totals as exact DECIMAL, never FLOAT):
WITH customer_expected AS (
    SELECT
        c.customer_name,
        c.email,
        c.quantity * p.unit_price AS expected_total
    FROM customers AS c
    LEFT JOIN products AS p
        ON p.product_name = c.product_name
)
SELECT
    o.user_id,
    MIN(ce.customer_name) AS customer_name
FROM orders AS o
JOIN customer_expected AS ce
    ON (COALESCE(o.email, '') <> '' AND ce.email = o.email)
    OR (COALESCE(o.email, '') = ''  AND ce.expected_total = o.order_total)
GROUP BY o.user_id;

Follow-up questions

Similar questions

More Karat interview questions

All 2 Karat questions →