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], wherequantityis an integer encoded as a string,emailmay be blank (""orNone), and each customer orders only oneproductName.orders:[userId, email, orderTotal], whereemailmay be missing (Noneor"") andorderTotalis an integer or decimal amount encoded as a string.products:[productName, unitPrice], whereunitPriceis an integer or decimal price encoded as a string.
Resolve each row [userId, email, orderTotal] in orders using two mutually exclusive rules:
- Present email (
emailis neitherNonenor""): Match strictly to customers whoseemailequalsorders.email. Never fall back to bill-amount matching if the provided email is unknown. - Missing email (
emailisNoneor""): Match to customers whose expected billquantity * unitPrice(computed with exact decimal arithmetic after joiningcustomers.productNametoproducts.productName) equalsorderTotal.
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)
emailfields inorders(andcustomers) may beNoneor""; 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
customerNameunder<, and omit anyuserIdwith no matching customer
Step-by-step walkthrough
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
userIdto thecustomerNamewho 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
emailis 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] = customerNameBefore writing code, let's settle four important edge behaviors from the rules and examples:
- Missing emails: Both
Noneand""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. - Tie-breaker: Multiple customers can produce the same expected total (
3 * 8 == 24and2 * 12 == 24in Example 2) or share an email. Whenever two candidates tie, we keep the lexicographically smallest name ("Nadia" < "Tariq"in alphabetical / character-code order). - No fallback when email is present: Rule 2 applies only when
orders.emailis missing. If an order provides an unknown email, we do not fall back to matching its total. - Unmatched orders: If an order matches no customer, we leave its
userIdout of the output dictionary.
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
productsto look upunitPrice.If there are
Oorders,Ccustomers, andPproducts, nested loops takeO(O * C * P)time. Even if we putproductsin a dictionary first, scanning allCcustomers for every order still takesO(O * C)time.Notice that every order asks one of two fixed questions: - "Which customer owns this
email?" - "Which customer'squantity * unitPriceequals thisorderTotal?"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.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.Fractionsolves both problems cleanly.Fraction("6.75")andFraction("3") * Fraction("2.25")both simplify to the exact rational number27/4. EqualFractionvalues compare equal (==) and produce the exact same dictionary hash, makingFractionideal as a dictionary key.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_namePrecompute the email and expected-total lookup tables
Now we build the two customer indexes in two linear passes:
- Product price lookup (
unit_price_by_product): Map eachproductNametoFraction(unitPrice). - Customer lookups (
name_by_emailandname_by_total): For each customer:- If their email is non-empty, record
customer_email -> customer_nameviastore_smaller_name. (Skipping empty emails ensures an empty string never entersname_by_email.) - If their
productNamehas a known price, computeFraction(quantity_str) * unit_price_by_product[product_name]and recordexpected_total -> customer_nameviastore_smaller_name.
- If their email is non-empty, record
Here is how those tables look for Example 2 (
Tariqbuys3Posterat8;Nadiabuys2Frameat12):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- Product price lookup (
Match every order and trace Example 3
With both lookup dictionaries ready, we loop through
ordersonce. Each order checks its ownorder_email: - Missing (Noneor"") -> look upFraction(order_total_str)inname_by_total. - Present -> look uporder_emailinname_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"}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:
name_by_email: maps each customer's email address to their name.name_by_total: performs a relational join (combining rows from two tables that share a matching column, hereproductName) betweencustomersandproductsto compute each customer's expected billquantity * 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 scanproductsonce inO(P)to populateunit_price_by_product, scancustomersonce inO(C)doing at most twoO(1)average dictionary updates per customer, and scanordersonce inO(O)doing a singleO(1)average dictionary lookup per order. - Space:
O(P + C + O).unit_price_by_productstores up toPentries,name_by_emailandname_by_totaleach store at mostCentries, and the output dictionaryuser_to_namestores at mostOentries.
Edge cases
- Both
Noneand""onorders.email: Both represent a missing email and route the order toname_by_total. - Empty
emailon a customer row: Excluded fromname_by_emailso an order with""never matches a customer by "both having blank emails"; that customer can still be matched throughname_by_total. - Different decimal spellings of the same total:
"3.5","3.50", andFraction("2") * Fraction("1.75")all reduce toFraction(7, 2)and hash identically. - Ties on expected total or shared email:
store_smaller_namekeeps the lexicographically smallestcustomerNameregardless of row order incustomers(note that ASCII uppercase sorts before lowercase, so"Tariq" < "nadia"). - Customer whose product is absent from
products: Cannot be indexed inname_by_total, but still matches orders that carry their email. - Present email with no matching customer: Returns
Nonefromname_by_emailand is omitted — it does not fall back toname_by_total, because Rule 2 applies only when the order email is missing. - Empty
orderslist: Returns{}cleanly.
Common mistakes
- Comparing totals as
float:3 * 0.1 == 0.3evaluates toFalsein IEEE 754 floating-point math, causing valid orders to go unmatched. UseFractionordecimal.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 bothNoneand"": An empty string""is non-None, so forgettingorder_email == ""sends blank-email orders toname_by_emailinstead ofname_by_total. - Falling back to
name_by_totalwhen 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 incustomers.
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
Fractiontotal to asetof customer names (Dict[Any, Set[str]]), then returnsorted(candidates)for eachuserId. Indexing staysO(P + C), while sorting and outputting candidate lists takesO(O * K log K)whereKis 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 treatclean == ""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 aLEFT JOINtoproductsso customers without a product price can still match by email; then joinordersusing anORcondition gated on whetherorders.emailis empty, and group byuser_idtakingMIN(customer_name)for the tie-breaker (storing prices and totals as exactDECIMAL, neverFLOAT):
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
- How would the data structures change if we needed to return every matching candidate name in sorted order instead of picking a single winner?
- How should you preprocess email addresses if real-world logs contain mixed uppercase/lowercase letters or leading and trailing spaces?
- How would you write an equivalent relational database query in SQL without losing decimal precision?
Similar questions
- Check Password Policy Violations
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One