KatInterview

In-Memory Spreadsheet with Formula Evaluation and Cycle Detection

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designgraphdependency-trackingcycle-detection

Last updated

Build a spreadsheet system that stores values, evaluates formulas referencing other cells, and prevents circular dependencies through pre-write validation.

Design and implement an in-memory spreadsheet system. Each cell is identified by a coordinate string combining column letters and row numbers (for example, A1, B2, or Z99).

Your implementation must handle three types of operations through a single function that processes batches of commands:

Operation Types:

  1. set - Assigns a value or formula to a cell

    • Arguments: [cell_name, content]
    • Returns 1 if successful, 0 if the operation was rejected
  2. get - Retrieves the computed value of a cell

    • Arguments: [cell_name]
    • Returns the integer value of the cell

Value Format:

  • Plain integer: A string representing a number like "42" or "100"
  • Formula: A string beginning with = followed by an expression that adds cell references and integer constants using the + operator
    • Example: "=A1+B2+5" means add the value in A1, the value in B2, and the constant 5
    • Formulas may reference cells that haven't been assigned yet

Behavior Requirements:

  • Cells that have never been assigned default to 0
  • When evaluating a formula, use the current values of all referenced cells
  • Formulas may reference other cells containing formulas, creating dependency chains
  • Cycle Prevention: If assigning a value to a cell would create a circular dependency (where a cell depends on itself either directly or through intermediate cells), reject the entire operation and leave the spreadsheet completely unchanged
    • Return 0 for rejected set operations
    • Return 1 for successful set operations

Constraints:

  • Cell names match the pattern: one or more uppercase letters followed by a positive integer (row numbers start at 1)
  • Formula expressions contain only cell references, integer constants, and the + operator
  • All operations are processed sequentially in the order given
  • 1 ≤ number of operations ≤ 1000
  • 0 ≤ integer values ≤ 10^6

Examples

Example 1

Input: process_spreadsheet_commands(['set', 'set', 'get', 'set', 'get', 'set', 'get'], [['A1', '5'], ['B1', '=A1+3'], ['B1'], ['A1', '10'], ['B1'], ['C1', '=B1+A1+2'], ['C1']])

Output: [1, 1, 8, 1, 13, 1, 25]

Hints

Hint 1

Track which cells each formula depends on so you can detect cycles before committing a write

Hint 2

When checking for cycles, traverse the dependency graph starting from the cells that would depend on the cell being written

Hint 3

Store both the raw input (the string) and the parsed representation to avoid re-parsing on every read