Implement spreadsheet cells with formulas
Company: Fuse Energy
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Design an in-memory spreadsheet that supports these operations on cells such as `A1`, `B2`, and ranges such as `A1:B2`:
- `Set(cell, value)`: assign an integer literal to a cell.
- `Sum(dest, refs)`: assign `dest` to a formula equal to the sum of all referenced cells. Each item in `refs` is either a single cell like `"B2"` or a rectangular range like `"A1:B2"`.
- `Get(cell)`: return the current value of the cell.
- `Undo()`: revert the most recent successful write operation. Both `Set` and `Sum` count as write operations.
Rules:
1. Cells that have never been assigned should be treated as `0`.
2. Formula cells are reactive: if a referenced cell changes later, `Get` on the formula cell should reflect the new value.
3. Duplicate references count multiple times.
4. A `Sum` operation is invalid if it would introduce a cycle in the dependency graph. In that case, it should raise an error and leave the spreadsheet unchanged.
Example:
```text
Set("A1", 1)
Set("B2", 2)
Sum("D1", ["A1:B2", "B2"])
Get("D1") // 5, because A1 + A2 + B1 + B2 + B2 = 1 + 0 + 0 + 2 + 2
Set("A1", 2)
Get("D1") // 6
```
Cycle examples:
```text
Sum("A1", ["A1", "B1"]) // invalid: direct self-cycle
Sum("A1", ["B1"]) // valid
Sum("B1", ["A1"]) // invalid if A1 already depends on B1
Sum("B3", ["B3"]) // invalid
```
Implement the data structure and explain how you would track dependencies, detect cycles, and support `Undo()` efficiently.
Quick Answer: This question evaluates proficiency in data structures and algorithms for dependency management, reactive computation, cycle detection, and state versioning (undo), assessing the ability to reason about how cells, formulas, and ranges interact under updates.