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 color c by the number of previously acquired cards whose "color" is c. Floor each color's effective cost at 0 (max(0, cost[c] - bonus[c])) so excess bonuses never create negative prices or grant extra tokens.
  • "canPurchase": Return True if the player currently possesses at least the effective token cost across all five colors, or False otherwise. Do not modify player state.
  • "purchase":
    • If the player cannot cover every color's effective cost, return False without 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"] by 1 (applicable to subsequent operations, never reducing the card's own price), and return True.

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]
  1. purchase card 0: costs 3 BLUE; player spends 3 BLUE (leaving BLUE: 1, GREEN: 2) and gains +1 BLUE bonus (True).
  2. canPurchase card 1: the +1 BLUE bonus lowers its price from {BLUE: 2, GREEN: 2} to {BLUE: 1, GREEN: 2}, which matches the player's remaining tokens (True, read-only).
  3. purchase card 1: spends 1 BLUE and 2 GREEN (leaving 0 tokens) and gains +1 YELLOW bonus (True).
  4. canPurchase card 1: effective price is still {BLUE: 1, GREEN: 2}, so with 0 tokens left it returns False.

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^4
  • 0 <= len(operations) == len(arguments) <= 10^4
  • Every operations[i] is either "canPurchase" or "purchase", and 0 <= arguments[i][0] < len(cards).
  • Token counts in initial_gems and "cost" are non-negative integers.

Step-by-step walkthrough

  1. 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 +1 discount 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 to 0, never below 0.
    • canPurchase: Read-only check returning True if the player currently holds enough tokens for every color in the discounted cost, or False otherwise.
    • purchase: If affordable, deducts the discounted cost, appends the card to hand, increments discount_map[card["color"]] by 1, and returns True. If not affordable, returns False and changes nothing.

    The judge passes initial_gems, a list of cards, a list of operations ("canPurchase" or "purchase"), and arguments ([[card_index], ...]), expecting one boolean per operation. Two details from the examples are worth noting up front:

    1. Missing colors mean 0: Example 1 passes {"BLUE": 4, "GREEN": 2}, omitting the other three colors, and Example 3 passes initial_gems = {} and cost: {} (a free card).
    2. Cards can be queried or bought repeatedly by index: Example 3 buys card 0 twice in a row and then checks and buys card 1.
  2. Key invariants: clamp at zero and check before mutating

    Counting player.hand from scratch on every operation would take O(hand size) per check. Maintaining discount_map incrementally makes every lookup O(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), and purchase (check, then commit) enforces both invariants cleanly.

  3. Model the Player state and discounted cost

    Player.__init__ initializes all five colors to 0 in a brand-new self.gems dictionary before copying initial_gems over, so missing colors default to 0 and the caller's dictionary is never mutated. discounted_cost computes max(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_cost
    
  4. Implement `can_purchase` and all-or-nothing `purchase`

    can_purchase checks whether self.gems.get(color, 0) >= needed_gems for every color in discounted_cost(card) without modifying anything.

    purchase calls self.can_purchase(card) first as its gatekeeper. Only when every color is covered does it deduct effective_cost, append the card to self.hand, and finally increment self.discount_map[card_color]. Incrementing discount_map last 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 True
    
  5. Wire up the operation driver

    simulate_purchases instantiates a Player, steps through (operation, args) in lockstep, looks up cards[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 results
    
  6. Trace 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]
    
  7. 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:

  • purchase card 0 (BLUE, costs BLUE: 3): effective cost is 3 blue; 4 >= 3, so BLUE drops to 1 and discount_map["BLUE"] becomes 1 (True).
  • canPurchase card 1 (YELLOW, costs BLUE: 2, GREEN: 2): the 1 blue discount lowers cost to BLUE: 1, GREEN: 2; player owns BLUE: 1, GREEN: 2, returning True without spending anything.
  • purchase card 1: spends BLUE: 1, GREEN: 2 (leaving 0 of both) and raises discount_map["YELLOW"] to 1 (True).
  • canPurchase card 1 again: effective cost is still BLUE: 1, GREEN: 2 (owning YELLOW only discounts YELLOW), and with 0 tokens left it returns False.

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 to O(q) since c <= 5 is a small constant. Each canPurchase or purchase loops over at most 5 color entries in card["cost"] and performs O(1) dictionary lookups and updates.
  • Space: O(c + h) (O(1) for the 5-color gems and discount_map dictionaries, plus O(h) references stored in player.hand and O(q) booleans in the output list).

Edge cases

  • Zero-cost / empty-cost card (cost: {}): Always affordable even when initial_gems is {} across every color (Example 3).
  • Discount larger than printed cost: Owning 2 white cards when buying a 1-white card clamps max(0, 1 - 2) to 0, never -1 (so tokens are never refunded).
  • Exact gem balance: Having gems[color] == needed_gems succeeds and leaves 0 tokens of that color.
  • Missing color keys in initial_gems: Colors omitted from initial_gems default to 0 rather than raising KeyError.
  • Self-discount prevention: Buying a WHITE card that costs 1 white token requires 1 white token if discount_map["WHITE"] == 0; its own +1 white discount takes effect only after purchase.
  • Failed multi-color purchase: In Example 2, having enough RED (2) while lacking YELLOW (1 < 3) leaves gems, hand, and discount_map completely unchanged so a subsequent RED purchase still succeeds.
  • Caller immutability & empty operation list: initial_gems is copied so caller data is untouched, and operations = [] returns [].

Common mistakes

  • Omitting max(0, ...) when applying discounts: Turns required - discount negative when discounts exceed cost, causing self.gems[color] -= needed_gems to 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_map before computing effective_cost: Lets a card discount its own purchase price by 1.
  • Direct indexing self.gems[color] without .get(color, 0) or zero-initialization: Crashes with KeyError when initial_gems omits colors with zero balance.
  • Mutating initial_gems in place: Assigning self.gems = initial_gems modifies 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 deficit shortfall[c] = max(0, effective_cost[c] - gems[c]). The card is affordable if and only if sum(shortfall.values()) <= gold_wildcards. During purchase, spend regular colored gems first (min(gems[c], effective_cost[c]) per color) and deduct sum(shortfall.values()) from gold_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_purchase simultaneously, observe BLUE: 3, and both subtract 3, driving the balance to -3 (a classic check-then-act race condition). In a single-process server, guard purchase with 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 conditional UPDATE player_gems SET blue = blue - 3 ... WHERE player_id = ? AND blue >= 3 and verify that 1 row 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 successful purchase, where paid_gems_dict records the exact effective_cost actually deducted at that moment. On undo_last_purchase(), pop the latest receipt, add paid_gems_dict back into self.gems, pop self.hand, and decrement self.discount_map[card["color"]] by 1. Storing paid_gems_dict directly avoids miscalculating refunds when discounts had been clamped at 0 or altered by the purchased card's own color.

Follow-up questions

Similar questions

More Brex interview questions

All 9 Brex questions →