KatInterview

Thread-Safe Inventory Management

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designdesign-dsarraysconcurrency

Last updated

Simulate concurrent inventory purchases and sales ensuring atomic state updates, preventing negative inventory, and handling invalid operations cleanly.

You are tasked with building a thread-safe inventory tracker for a online store trading digital goods. The system tracks the available unit balance of a single item and supports two core actions:

  1. buy(quantity): Replenishes the stock by adding quantity units to the available balance. A purchase operation always succeeds. It returns the total updated stock count immediately following the replenishment.
  2. sell(quantity): Attempts to deduct quantity units from the stock.
    • If the available stock is greater than or equal to quantity, the sale succeeds: deduct quantity units from stock and return True.
    • If the stock is insufficient, the sale fails: leave the stock completely unchanged (no partial deductions) and return False.

Requirements

To operate correctly under multi-threaded execution:

  • No overselling: The current available stock must never drop below $0$.
  • No lost updates: Concurrent modifications must be properly synchronized so that every addition and every successful deduction is accurately reflected in the final count.
  • Atomic check-and-modify: Checking stock availability and performing the deduction within a sale must occur as a single atomic operation without interleaving from other calls.

Write a function stock_inventory that processes a list of operations sequentially. Given an initial stock count and parallel sequences of operation names and integer arguments, execute each command and collect the returned results.

If an unsupported operation name (anything other than "buy" or "sell") is encountered, raise a ValueError.

Constraints

  • 0 <= initial <= 10^9
  • 1 <= quantity <= 10^9 for every action argument
  • 1 <= operations.length <= 10^5
  • arguments.length == operations.length, where each element is a single-element list [quantity]

Examples

Example 1

Input: stock_inventory(100, ['sell', 'sell', 'buy', 'sell', 'sell'], [[30], [80], [50], [120], [1]])

Output: [True, False, 120, True, False]

Example 2

Input: stock_inventory(0, ['buy', 'sell', 'sell'], [[1], [1], [1]])

Output: [1, True, False]

Hints

Hint 1

Consider what happens if two threads try to execute a sale simultaneously when stock is only sufficient for one. A simple condition check followed by subtraction is vulnerable to race conditions.

Hint 2

Even `buy` operations modify shared state (`shares += quantity` is a read-modify-write process), so additions must also be protected under the same locking mechanism.

Hint 3

To satisfy atomicity in Python, guard the state checks and modifications inside a synchronized critical section using a standard lock.