Implement Spreadsheet Cells with Dependencies
RampSoftware Engineer · Technical ScreenLast updated
This problem tests graph theory fundamentals, specifically cycle detection and topological sorting in the context of a dependency-driven computation engine.
Problem Statement
Implement a basic Spreadsheet system that supports setting cell values and defining dependencies. A cell can either contain a raw numeric value or a formula. A formula is defined as a simple addition operation between two other cells (e.g., "A1 + B2").
When the value of a cell changes, all cells that depend on it must be re-evaluated. If a circular dependency is introduced (e.g., A depends on B, and B depends on A), the system should detect it and raise an error.
Requirements
Implement the Spreadsheet class with the following methods:
set_value(cell: str, value: float): Sets a cell to a static number.set_formula(cell: str, formula: str): Sets a cell to a formula (e.g., "A1 + B2").get_value(cell: str) -> float: Returns the current computed value of the cell. If it has a formula, it computes it based on the current values of its dependencies.
Constraints
- Cell names follow the format
[Letter][Number](e.g., "A1", "B2"). - Formulas only support the format
"[Cell1] + [Cell2]". - The spreadsheet should handle transitive dependencies (e.g., C depends on B, B depends on A).
Examples
s = Spreadsheet()
s.set_value("A1", 10.0)
s.set_value("B1", 20.0)
s.set_formula("C1", "A1 + B1")
# s.get_value("C1") returns 30.0
s.set_value("A1", 5.0)
# s.get_value("C1") returns 25.0
Edge Cases
- Circular references:
set_formula("A1", "B1 + C1")followed byset_formula("B1", "A1 + D1")should raise an error. - Updating a dependency should propagate changes through multiple layers of formulas.
Hints
Hint 1
Represent the dependencies as a directed graph where an edge exists from a cell to the cells that depend on it.
Hint 2
Use a depth-first search (DFS) to detect cycles before finalizing a new formula assignment.
Hint 3
Decide whether to use a 'pull' approach (recalculate on demand) or a 'push' approach (eagerly update downstream cells).
Follow-up questions
- How would you optimize `get_value` if there are millions of cells, most of which are rarely updated?
- How would you extend this to support more operators like subtraction or multiplication?
- What changes are needed if a cell could depend on a range of cells (e.g., 'SUM(A1:A10)')?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.