Problem Description
Design a simple spreadsheet with 26 fixed columns (labeled A to Z) and a specified number of rows, where each cell holds an integer between 0 and 10^5. Implement a class that supports setting a cell’s value, resetting a cell to 0, and evaluating formulas of the form "=X+Y" (where X and Y can be either integers or cell references). If a cell is never explicitly set, its value is considered 0.
Key Insights
- Use a 2D array (or equivalent) to represent the spreadsheet.
- Convert column letters (A-Z) to an index (0-25) and adjust row numbers from 1-indexed to 0-indexed.
- Parse the formula by removing the "=" and splitting based on "+".
- Differentiate between numeric constants and cell references using character checks.
- Direct access operations (set, reset, and get) can be done in constant time.
Space and Time Complexity
Time Complexity:
- setCell and resetCell operations: O(1)
- getValue operation: O(1) (given fixed-format formulas and constant-time parsing) Space Complexity:
- O(rows * 26) for storing the spreadsheet cells
Solution
We use a 2D array (or equivalent) to store cell values. Each cell is accessed by converting its cell reference (like "A1") into 0-indexed row and column indices. The getValue method parses the formula by stripping the leading "=" and splitting by "+". For each operand, we check if it starts with a digit (and treat it as an integer) or a letter (and look up the corresponding cell value). This straightforward approach ensures O(1) operations for each method call.