Gem Card Purchases with Color Discounts
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Model the checkout mechanics of a tabletop strategy game played with five token colors: BLUE, WHITE, GREEN, RED, and YELLOW.
Every card in the catalog cards is represented as a dictionary with two keys:
- "color": one of the five token colors indicating the permanent +1 color bonus granted once the card is acquired.
- "cost": a dictionary mapping token colors to non-negative integer amounts (any color omitted from "cost" requires 0 tokens).
A player begins with initial_gems (a dictionary of starting token counts; any omitted color starts at 0), an empty collection of acquired cards, and a 0 bonus on every color.
Process a sequence of actions given by operations and arguments, where arguments[i] is [idx] referring to cards[idx] (an index may be referenced repeatedly across turns):
- Discount calculation: For each color
c, reduce the card's printed cost in colorcby the number of previously acquired cards whose"color"isc. Floor each color's effective cost at0(max(0, cost[c] - bonus[c])) so excess bonuses never create negative prices or grant extra tokens. "canPurchase": ReturnTrueif the player currently possesses at least the effective token cost across all five colors, orFalseotherwise. Do not modify player state."purchase":- If the player cannot cover every color's effective cost, return
Falsewithout modifying token counts, owned cards, or color bonuses. - Otherwise, subtract the effective cost from the player's tokens, record the card in the player's hand, increase the bonus for
cards[idx]["color"]by1(applicable to subsequent operations, never reducing the card's own price), and returnTrue.
- If the player cannot cover every color's effective cost, return
Implement:
def simulate_purchases(
initial_gems: Dict[str, int],
cards: List[Dict[str, object]],
operations: List[str],
arguments: List[List[int]],
) -> List[bool]:
returning one boolean per operation without mutating caller inputs.
Examples
Example 1
Input:
initial_gems = {"BLUE": 4, "GREEN": 2}
cards = [
{"color": "BLUE", "cost": {"BLUE": 3}},
{"color": "YELLOW", "cost": {"BLUE": 2, "GREEN": 2}}
]
operations = ["purchase", "canPurchase", "purchase", "canPurchase"]
arguments = [[0], [1], [1], [1]]
Output:
[True, True, True, False]
purchasecard0: costs3 BLUE; player spends3 BLUE(leavingBLUE: 1, GREEN: 2) and gains+1 BLUEbonus (True).canPurchasecard1: the+1 BLUEbonus lowers its price from{BLUE: 2, GREEN: 2}to{BLUE: 1, GREEN: 2}, which matches the player's remaining tokens (True, read-only).purchasecard1: spends1 BLUEand2 GREEN(leaving0tokens) and gains+1 YELLOWbonus (True).canPurchasecard1: effective price is still{BLUE: 1, GREEN: 2}, so with0tokens left it returnsFalse.
Example 2
Input:
initial_gems = {"RED": 2, "YELLOW": 1}
cards = [
{"color": "GREEN", "cost": {"RED": 2, "YELLOW": 3}},
{"color": "RED", "cost": {"RED": 2}}
]
operations = ["canPurchase", "purchase", "purchase", "canPurchase"]
arguments = [[0], [0], [1], [1]]
Output:
[False, False, True, False]
Card 0 needs 3 YELLOW while the player holds only 1, so both canPurchase and purchase return False without touching the player's 2 RED tokens. Buying card 1 then succeeds using those intact 2 RED tokens (True), and checking card 1 afterward needs max(0, 2 - 1) = 1 RED when 0 RED remain (False).
Example 3
Input:
initial_gems = {}
cards = [
{"color": "WHITE", "cost": {}},
{"color": "GREEN", "cost": {"WHITE": 1}}
]
operations = ["purchase", "purchase", "purchase", "canPurchase"]
arguments = [[0], [0], [1], [1]]
Output:
[True, True, True, True]
Card 0 has an empty cost {} and can be bought twice with zero tokens, raising the WHITE bonus to 2. Card 1's cost {WHITE: 1} minus a 2 WHITE bonus clamps at 0 (no tokens spent or refunded), so buying and re-checking card 1 both return True.
Constraints
- Valid token colors are
"BLUE","WHITE","GREEN","RED", and"YELLOW". 1 <= len(cards) <= 10^40 <= len(operations) == len(arguments) <= 10^4- Every
operations[i]is either"canPurchase"or"purchase", and0 <= arguments[i][0] < len(cards). - Token counts in
initial_gemsand"cost"are non-negative integers.
Step-by-step walkthrough
Understand the checkout rules and judge interface
In this token-based card game, a player buys cards using five colors (
BLUE,WHITE,GREEN,RED,YELLOW). Every purchased card grants a permanent+1discount of its"color"on all subsequent purchases:- Effective cost per color:
max(0, raw_cost[c] - discount_map[c]). Discounts can lower a color's price down to0, never below0. canPurchase: Read-only check returningTrueif the player currently holds enough tokens for every color in the discounted cost, orFalseotherwise.purchase: If affordable, deducts the discounted cost, appends the card tohand, incrementsdiscount_map[card["color"]]by1, and returnsTrue. If not affordable, returnsFalseand changes nothing.
The judge passes
initial_gems, a list ofcards, a list ofoperations("canPurchase"or"purchase"), andarguments([[card_index], ...]), expecting one boolean per operation. Two details from the examples are worth noting up front:- Missing colors mean
0: Example 1 passes{"BLUE": 4, "GREEN": 2}, omitting the other three colors, and Example 3 passesinitial_gems = {}andcost: {}(a free card). - Cards can be queried or bought repeatedly by index: Example 3 buys card
0twice in a row and then checks and buys card1.
- Effective cost per color:
Key invariants: clamp at zero and check before mutating
Counting
player.handfrom scratch on every operation would takeO(hand size)per check. Maintainingdiscount_mapincrementally makes every lookupO(1), so each operation inspects at most 5 colors.Two subtle bugs catch candidates off guard if they rush the arithmetic or state updates:
Trap 1 — Unclamped negative cost (forgot max(0, ...)): Owned WHITE cards = 2, card raw cost = {"WHITE": 1}, player WHITE gems = 0 Wrong: 1 - 2 = -1 -> gems["WHITE"] -= (-1) -> gems["WHITE"] becomes 1 (free gem!) Correct: max(0, 1 - 2) = 0 -> gems["WHITE"] stays 0 Trap 2 — Mutating while checking (partial deduction on failure): Player gems = {"RED": 2, "YELLOW": 1}, card cost = {"RED": 2, "YELLOW": 3} Wrong: check RED (ok) -> deduct RED to 0 -> check YELLOW (short!) -> return False (Player lost 2 RED gems on a failed purchase!) Correct: Phase 1 checks ALL colors first; Phase 2 deducts ONLY after all checks pass.Separating
discounted_cost,can_purchase(check), andpurchase(check, then commit) enforces both invariants cleanly.Model the Player state and discounted cost
Player.__init__initializes all five colors to0in a brand-newself.gemsdictionary before copyinginitial_gemsover, so missing colors default to0and the caller's dictionary is never mutated.discounted_costcomputesmax(0, required_gems - owned_discount)for every color listed on the card.GEM_COLORS = ["BLUE", "WHITE", "GREEN", "RED", "YELLOW"] class Player: def __init__(self, initial_gems: Dict[str, int]): # self.gems: owned gem counts per color, e.g. {"BLUE": 4, "GREEN": 2, "WHITE": 0, ...}. # Copy into a fresh dict initialized to 0 so missing colors default to 0 and caller input stays untouched. self.gems: Dict[str, int] = {} for color in GEM_COLORS: self.gems[color] = 0 for color, count in initial_gems.items(): self.gems[color] = count # self.hand: list of purchased card dicts in purchase order. self.hand: List[Dict[str, object]] = [] # self.discount_map: permanent per-color discount equal to owned cards of each color, e.g. {"BLUE": 1, ...}. self.discount_map: Dict[str, int] = {} for color in GEM_COLORS: self.discount_map[color] = 0 def discounted_cost(self, card: Dict[str, object]) -> Dict[str, int]: """Compute the effective gem cost of a card after clamping each color's discount at 0.""" effective_cost: Dict[str, int] = {} raw_cost = card["cost"] for color, required_gems in raw_cost.items(): owned_discount = self.discount_map.get(color, 0) # Clamp with max(0, ...) so a large discount never produces a negative cost (gem refund). effective_cost[color] = max(0, required_gems - owned_discount) return effective_costImplement `can_purchase` and all-or-nothing `purchase`
can_purchasechecks whetherself.gems.get(color, 0) >= needed_gemsfor every color indiscounted_cost(card)without modifying anything.purchasecallsself.can_purchase(card)first as its gatekeeper. Only when every color is covered does it deducteffective_cost, append the card toself.hand, and finally incrementself.discount_map[card_color]. Incrementingdiscount_maplast ensures a card's own color never discounts its own purchase price.def can_purchase(self, card: Dict[str, object]) -> bool: """Return True if the player owns enough gems for every color in the discounted cost.""" effective_cost = self.discounted_cost(card) for color, needed_gems in effective_cost.items(): if self.gems.get(color, 0) < needed_gems: return False return True def purchase(self, card: Dict[str, object]) -> bool: """Buy the card all-or-nothing: deduct gems, add to hand, and raise that card color's discount.""" # Phase 1 (check): verify every color is affordable before mutating any player state. if not self.can_purchase(card): return False # Phase 2 (commit): deduct effective cost, append card to hand, then increment discount_map. # Updating discount_map AFTER computing effective_cost ensures a card never discounts itself. effective_cost = self.discounted_cost(card) for color, needed_gems in effective_cost.items(): self.gems[color] = self.gems.get(color, 0) - needed_gems self.hand.append(card) card_color = card["color"] self.discount_map[card_color] = self.discount_map.get(card_color, 0) + 1 return TrueWire up the operation driver
simulate_purchasesinstantiates aPlayer, steps through(operation, args)in lockstep, looks upcards[args[0]], and collects each boolean return value.def simulate_purchases(initial_gems: Dict[str, int], cards: List[Dict[str, object]], operations: List[str], arguments: List[List[int]]) -> List[bool]: player = Player(initial_gems) results: List[bool] = [] # Execute each operation against the card at index arguments[i][0] and record its boolean outcome. for operation, args in zip(operations, arguments): card = cards[args[0]] if operation == "canPurchase": results.append(player.can_purchase(card)) elif operation == "purchase": results.append(player.purchase(card)) else: raise ValueError(f"Unknown operation: {operation}") return resultsTrace Example 1 step by step
Initial state: gems = {BLUE: 4, GREEN: 2} (others 0), discount_map = all 0 card 0: color=BLUE, cost={BLUE: 3} card 1: color=YELLOW, cost={BLUE: 2, GREEN: 2} 1. purchase(card 0): effective_cost = {BLUE: max(0, 3 - 0)} = {BLUE: 3} affordable? BLUE 4 >= 3 -> True! commit -> gems = {BLUE: 1, GREEN: 2}, discount_map = {BLUE: 1} 2. canPurchase(card 1): effective_cost = {BLUE: max(0, 2 - 1), GREEN: max(0, 2 - 0)} = {BLUE: 1, GREEN: 2} affordable? BLUE 1 >= 1 and GREEN 2 >= 2 -> True! (read-only, state unchanged) 3. purchase(card 1): effective_cost = {BLUE: 1, GREEN: 2} -> affordable -> True! commit -> gems = {BLUE: 0, GREEN: 0}, discount_map = {BLUE: 1, YELLOW: 1} 4. canPurchase(card 1): effective_cost = {BLUE: max(0, 2 - 1), GREEN: max(0, 2 - 0)} = {BLUE: 1, GREEN: 2} affordable? YELLOW discount does not reduce BLUE or GREEN; player has 0 -> False! Returned results: [True, True, True, False]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple GEM_COLORS = ["BLUE", "WHITE", "GREEN", "RED", "YELLOW"] class Player: def __init__(self, initial_gems: Dict[str, int]): # self.gems: owned gem counts per color, e.g. {"BLUE": 4, "GREEN": 2, "WHITE": 0, ...}. # Copy into a fresh dict initialized to 0 so missing colors default to 0 and caller input stays untouched. self.gems: Dict[str, int] = {} for color in GEM_COLORS: self.gems[color] = 0 for color, count in initial_gems.items(): self.gems[color] = count # self.hand: list of purchased card dicts in purchase order. self.hand: List[Dict[str, object]] = [] # self.discount_map: permanent per-color discount equal to owned cards of each color, e.g. {"BLUE": 1, ...}. self.discount_map: Dict[str, int] = {} for color in GEM_COLORS: self.discount_map[color] = 0 def discounted_cost(self, card: Dict[str, object]) -> Dict[str, int]: """Compute the effective gem cost of a card after clamping each color's discount at 0.""" effective_cost: Dict[str, int] = {} raw_cost = card["cost"] for color, required_gems in raw_cost.items(): owned_discount = self.discount_map.get(color, 0) # Clamp with max(0, ...) so a large discount never produces a negative cost (gem refund). effective_cost[color] = max(0, required_gems - owned_discount) return effective_cost def can_purchase(self, card: Dict[str, object]) -> bool: """Return True if the player owns enough gems for every color in the discounted cost.""" effective_cost = self.discounted_cost(card) for color, needed_gems in effective_cost.items(): if self.gems.get(color, 0) < needed_gems: return False return True def purchase(self, card: Dict[str, object]) -> bool: """Buy the card all-or-nothing: deduct gems, add to hand, and raise that card color's discount.""" # Phase 1 (check): verify every color is affordable before mutating any player state. if not self.can_purchase(card): return False # Phase 2 (commit): deduct effective cost, append card to hand, then increment discount_map. # Updating discount_map AFTER computing effective_cost ensures a card never discounts itself. effective_cost = self.discounted_cost(card) for color, needed_gems in effective_cost.items(): self.gems[color] = self.gems.get(color, 0) - needed_gems self.hand.append(card) card_color = card["color"] self.discount_map[card_color] = self.discount_map.get(card_color, 0) + 1 return True def simulate_purchases(initial_gems: Dict[str, int], cards: List[Dict[str, object]], operations: List[str], arguments: List[List[int]]) -> List[bool]: player = Player(initial_gems) results: List[bool] = [] # Execute each operation against the card at index arguments[i][0] and record its boolean outcome. for operation, args in zip(operations, arguments): card = cards[args[0]] if operation == "canPurchase": results.append(player.can_purchase(card)) elif operation == "purchase": results.append(player.purchase(card)) else: raise ValueError(f"Unknown operation: {operation}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of buying cards at a hobby shop where every card you purchase acts as a permanent reusable coupon of its color for all future cards (just like in the board game Splendor). Two common-sense checkout rules govern every turn: first, clamping (bounding a number so it cannot cross a limit) keeps every color's discounted price at 0 or above so coupons never make the shop hand you extra tokens; second, purchase is atomic (an all-or-nothing update where either the entire checkout completes or nothing changes at all).
Two naive implementations break quickly. First, recounting the player's entire hand on every operation wastes O(hand size) time per check instead of O(1) lookups in a hash map (discount_map, a key-value dictionary tracking owned cards per color). Second, subtracting gems color by color inside the same loop that checks affordability corrupts state whenever an early color succeeds (RED deducted) and a later color fails (YELLOW short), leaving the player poorer after a rejected purchase.
By isolating discounted_cost, checking all colors in can_purchase first, and mutating state in purchase only after can_purchase returns True, every operation stays fast and bug-free. Walk through Example 1 starting with BLUE: 4, GREEN: 2 and zero discounts:
purchasecard0(BLUE, costsBLUE: 3): effective cost is3blue;4 >= 3, soBLUEdrops to1anddiscount_map["BLUE"]becomes1(True).canPurchasecard1(YELLOW, costsBLUE: 2, GREEN: 2): the1blue discount lowers cost toBLUE: 1, GREEN: 2; player ownsBLUE: 1, GREEN: 2, returningTruewithout spending anything.purchasecard1: spendsBLUE: 1, GREEN: 2(leaving0of both) and raisesdiscount_map["YELLOW"]to1(True).canPurchasecard1again: effective cost is stillBLUE: 1, GREEN: 2(owningYELLOWonly discountsYELLOW), and with0tokens left it returnsFalse.
Complexity
Let q be the number of operations, c be the number of gem colors (c <= 5), and h be the number of successful purchases (h <= q).
- Time:
O(q * c), which simplifies toO(q)sincec <= 5is a small constant. EachcanPurchaseorpurchaseloops over at most5color entries incard["cost"]and performsO(1)dictionary lookups and updates. - Space:
O(c + h)(O(1)for the 5-colorgemsanddiscount_mapdictionaries, plusO(h)references stored inplayer.handandO(q)booleans in the output list).
Edge cases
- Zero-cost / empty-cost card (
cost: {}): Always affordable even wheninitial_gemsis{}across every color (Example 3). - Discount larger than printed cost: Owning
2white cards when buying a1-white card clampsmax(0, 1 - 2)to0, never-1(so tokens are never refunded). - Exact gem balance: Having
gems[color] == needed_gemssucceeds and leaves0tokens of that color. - Missing color keys in
initial_gems: Colors omitted frominitial_gemsdefault to0rather than raisingKeyError. - Self-discount prevention: Buying a
WHITEcard that costs1white token requires1white token ifdiscount_map["WHITE"] == 0; its own+1white discount takes effect only after purchase. - Failed multi-color purchase: In Example 2, having enough
RED(2) while lackingYELLOW(1 < 3) leavesgems,hand, anddiscount_mapcompletely unchanged so a subsequentREDpurchase still succeeds. - Caller immutability & empty operation list:
initial_gemsis copied so caller data is untouched, andoperations = []returns[].
Common mistakes
- Omitting
max(0, ...)when applying discounts: Turnsrequired - discountnegative when discounts exceed cost, causingself.gems[color] -= needed_gemsto add gems to the player's balance. - Deducting gems while checking affordability: Partially charges earlier colors in
card["cost"]before discovering a later color is unaffordable. - Incrementing
discount_mapbefore computingeffective_cost: Lets a card discount its own purchase price by1. - Direct indexing
self.gems[color]without.get(color, 0)or zero-initialization: Crashes withKeyErrorwheninitial_gemsomits colors with zero balance. - Mutating
initial_gemsin place: Assigningself.gems = initial_gemsmodifies the caller's dictionary during simulation.
Follow-up questions
- How would you support gold wildcard tokens that can stand in for one missing gem of any color? First compute
effective_cost[c] = max(0, cost[c] - discount_map[c])for each color, then compute each color's deficitshortfall[c] = max(0, effective_cost[c] - gems[c]). The card is affordable if and only ifsum(shortfall.values()) <= gold_wildcards. Duringpurchase, spend regular colored gems first (min(gems[c], effective_cost[c])per color) and deductsum(shortfall.values())fromgold_wildcards, preserving wildcards whenever specific gems are available because wildcards remain flexible for future turns. - How do you prevent race conditions and negative gem balances if two purchase requests for the same player arrive concurrently? Without synchronization, two threads can both run
can_purchasesimultaneously, observeBLUE: 3, and both subtract3, driving the balance to-3(a classic check-then-act race condition). In a single-process server, guardpurchasewith a per-player mutex lock; in a database-backed service, execute the read and deduction inside a serializable database transaction (a grouped unit of SQL work executed atomically in isolation) or issue a single conditionalUPDATE player_gems SET blue = blue - 3 ... WHERE player_id = ? AND blue >= 3and verify that1row was modified. - How would you design an undo_last_purchase() operation so gem balances and color discounts roll back accurately? Push a receipt
(card, paid_gems_dict)onto a history stack at the end of every successfulpurchase, wherepaid_gems_dictrecords the exacteffective_costactually deducted at that moment. Onundo_last_purchase(), pop the latest receipt, addpaid_gems_dictback intoself.gems, popself.hand, and decrementself.discount_map[card["color"]]by1. Storingpaid_gems_dictdirectly avoids miscalculating refunds when discounts had been clamped at0or altered by the purchased card's own color.
Follow-up questions
- How would you support gold wildcard tokens that can stand in for one missing gem of any color?
- How do you prevent race conditions and negative gem balances if two purchase requests for the same player arrive concurrently?
- How would you design an undo_last_purchase() operation so gem balances and color discounts roll back accurately?
Similar questions
- Diagnose and Fix Expense Module Defects
- Software Engineering Behavioral Scenarios
- Multi-Select Swatch Picker and Comparison Table in React
- Peer-to-Peer Wallet and Auditable Payments Service
- Full-Stack Account Ledger with AI-Assisted Workflow
- Peer-to-Peer Wallet Transfer Architecture
More Brex interview questions
- Software Engineering Behavioral Scenarios Medium
- Peer-to-Peer Wallet and Auditable Payments Service Medium
- Diagnose and Fix Expense Module Defects Medium Pro
- Peer-to-Peer Wallet Transfer Architecture Medium Pro
- Gem-Token Card Purchasing with Color Bonuses and Thread Safety Medium Pro
- Full-Stack Account Ledger with AI-Assisted Workflow Medium Pro
- Multi-Select Swatch Picker and Comparison Table in React Medium Pro
- Card Spend to Loyalty Points Ledger Service Hard Pro