Design Spreadsheet solution and explanation
9 more videos on this problem
Design Spreadsheet | Simple Simulation | Leetcode 3484 | codestorywithMIKcodestorywithMIK · 16:22 · 5K views
Design Spreadsheet | Leetcode 3484Techdose · 14:56 · 1K views
3484. Design Spreadsheet | Leetcode Daily - PythonLeetcode Daily · 5:41 · 474 views
Design Spreadsheet | LeetCode 3484 | Real Life DB ProblemSanyam IIT Guwahati · 13:18 · 394 views
3484. Design Spreadsheet (Leetcode Medium)Programming Live with Larry · 6:12 · 314 views
Leetcode 3484 | Design Spreadsheet | Biweekly Contest 152Road To FAANG · 10:19 · 265 views
LeetCode 3484 🔥 Design Spreadsheet | Daily Challenge | Optimal Java Solution + Dry Run Study Placement · 13:49 · 222 views
Design Spreadsheet | LeetCode 3484 | Java Code | Developer CoderDeveloper Coder · 16:22 · 165 views
3484. Design Spreadsheet | Brute Force to Optimized | HashMap | Leetcode Daily ChallengeEye on AI and DSA · 21:35 · 164 views
Design Spreadsheet | Detailed Thought Process | Leetcode 3484 |Simple ExplanationCodeWith_Kedar · 11:27 · 143 views
The problem
A spreadsheet is a grid with 26 columns (labeled from 'A' to 'Z') and a given number of rows. Each cell in the spreadsheet can hold an integer value between 0 and 105.
Implement the Spreadsheet class:
Spreadsheet(int rows)Initializes a spreadsheet with 26 columns (labeled'A'to'Z') and the specified number of rows. All cells are initially set to 0.void setCell(String cell, int value)Sets the value of the specifiedcell. The cell reference is provided in the format"AX"(e.g.,"A1","B10"), where the letter represents the column (from'A'to'Z') and the number represents a 1-indexed row.void resetCell(String cell)Resets the specified cell to 0.int getValue(String formula)Evaluates a formula of the form"=X+Y", whereXandYare either cell references or non-negative integers, and returns the computed sum.
Note: If getValue references a cell that has not been explicitly set using setCell, its value is considered 0.
Example 1:
Input:
["Spreadsheet", "getValue", "setCell", "getValue", "setCell", "getValue", "resetCell", "getValue"]
[[3], ["=5+7"], ["A1", 10], ["=A1+6"], ["B2", 15], ["=A1+B2"], ["A1"], ["=A1+B2"]]
Output:
[null, 12, null, 16, null, 25, null, 15]
Explanation
Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columnsspreadsheet.getValue("=5+7"); // returns 12 (5+7)
spreadsheet.setCell("A1", 10); // sets A1 to 10
spreadsheet.getValue("=A1+6"); // returns 16 (10+6)
spreadsheet.setCell("B2", 15); // sets B2 to 15
spreadsheet.getValue("=A1+B2"); // returns 25 (10+15)
spreadsheet.resetCell("A1"); // resets A1 to 0
spreadsheet.getValue("=A1+B2"); // returns 15 (0+15)
Constraints:
1 <= rows <= 1030 <= value <= 105- The formula is always in the format
"=X+Y", whereXandYare either valid cell references or non-negative integers with values less than or equal to105. - Each cell reference consists of a capital letter from
'A'to'Z'followed by a row number between1androws. - At most
104calls will be made in total tosetCell,resetCell, andgetValue.
Approach overview
Problem Overview: Design a spreadsheet system that stores values in cells and evaluates simple expressions referencing other cells. Each cell can hold a number or participate in a formula such as =A1+B2. The system must support updating cells, resetting them, and computing the result of expressions using current values.
Approach 1: 2D Matrix Simulation (O(1) access, O(L) evaluation)
The most direct implementation uses a fixed matrix to represent the spreadsheet grid. Each cell stores its numeric value, and operations like set or reset simply update the matrix position derived from the cell label (for example converting A1 into row/column indices). When evaluating an expression, parse the string and fetch values from the matrix for each referenced cell. Access to any cell is O(1), while evaluating a formula takes O(L) time where L is the expression length. Space complexity is O(R × C) for the grid. This approach works well when the spreadsheet size is fixed and relatively small.
Approach 2: Hash Table Cell Storage (O(1) average operations)
A more flexible design stores only active cells in a hash table mapping the cell label (like "A1") to its value. Updates and resets become simple hash operations. When computing an expression, parse the string, extract referenced cells, and perform hash lookups for their values. Missing cells default to zero. Hash lookups run in O(1) average time, and expression parsing costs O(L). Space complexity becomes O(K), where K is the number of cells that have been written. This avoids allocating a full grid and is typically the preferred design for interview settings.
Expression parsing is straightforward: iterate through the string, split operands around the '+' operator, and check whether each token is a number or a cell reference. Cell references require converting column letters and row digits before performing the lookup. String processing dominates runtime, which is why the complexity is proportional to the expression length.
Recommended for interviews: The hash table approach is usually expected. It demonstrates good use of hash tables for constant‑time lookups and clean handling of sparse spreadsheets. A matrix simulation shows basic understanding of arrays and matrix indexing, but the hash table design scales better and keeps memory usage proportional to the number of populated cells.
Solution
We use a hash table d to record the values of all cells, where the key is the cell reference and the value is the cell's value.
When calling the setCell method, we store the cell reference and value in the hash table.
When calling the resetCell method, we remove the cell reference from the hash table.
When calling the getValue method, we split the formula into two cell references, calculate their values, and then return their sum.
The time complexity is O(L), and the space complexity is O(L). Where L is the length of the formula.
class Spreadsheet:
def __init__(self, rows: int):
self.d = {}
def setCell(self, cell: str, value: int) -> None:
self.d[cell] = value
def resetCell(self, cell: str) -> None:
self.d.pop(cell, None)
def getValue(self, formula: str) -> int:
ans = 0
for cell in formula[1:].split("+"):
ans += int(cell) if cell[0].isdigit() else self.d.get(cell, 0)
return ans
# Your Spreadsheet object will be instantiated and called as such:
# obj = Spreadsheet(rows)
# obj.setCell(cell,value)
# obj.resetCell(cell)
# param_3 = obj.getValue(formula)class Spreadsheet {
private Map<String, Integer> d = new HashMap<>();
public Spreadsheet(int rows) {
}
public void setCell(String cell, int value) {
d.put(cell, value);
}
public void resetCell(String cell) {
d.remove(cell);
}
public int getValue(String formula) {
int ans = 0;
for (String cell : formula.substring(1).split("\\+")) {
ans += Character.isDigit(cell.charAt(0)) ? Integer.parseInt(cell)
: d.getOrDefault(cell, 0);
}
return ans;
}
}
/**
* Your Spreadsheet object will be instantiated and called as such:
* Spreadsheet obj = new Spreadsheet(rows);
* obj.setCell(cell,value);
* obj.resetCell(cell);
* int param_3 = obj.getValue(formula);
*/class Spreadsheet {
private:
unordered_map<string, int> d;
public:
Spreadsheet(int rows) {}
void setCell(string cell, int value) {
d[cell] = value;
}
void resetCell(string cell) {
d.erase(cell);
}
int getValue(string formula) {
int ans = 0;
stringstream ss(formula.substr(1));
string cell;
while (getline(ss, cell, '+')) {
if (isdigit(cell[0])) {
ans += stoi(cell);
} else {
ans += d.count(cell) ? d[cell] : 0;
}
}
return ans;
}
};
/**
* Your Spreadsheet object will be instantiated and called as such:
* Spreadsheet* obj = new Spreadsheet(rows);
* obj->setCell(cell,value);
* obj->resetCell(cell);
* int param_3 = obj->getValue(formula);
*/class Spreadsheet {
private d: Map<string, number>;
constructor(rows: number) {
this.d = new Map<string, number>();
}
setCell(cell: string, value: number): void {
this.d.set(cell, value);
}
resetCell(cell: string): void {
this.d.delete(cell);
}
getValue(formula: string): number {
let ans = 0;
const cells = formula.slice(1).split('+');
for (const cell of cells) {
ans += isNaN(Number(cell)) ? this.d.get(cell) || 0 : Number(cell);
}
return ans;
}
}
/**
* Your Spreadsheet object will be instantiated and called as such:
* var obj = new Spreadsheet(rows)
* obj.setCell(cell,value)
* obj.resetCell(cell)
* var param_3 = obj.getValue(formula)
*/public class Spreadsheet {
private Dictionary<string, int> d = new Dictionary<string, int>();
public Spreadsheet(int rows) {
}
public void SetCell(string cell, int value) {
d[cell] = value;
}
public void ResetCell(string cell) {
d.Remove(cell);
}
public int GetValue(string formula) {
int ans = 0;
foreach (string cell in formula.Substring(1).Split('+')) {
ans += char.IsDigit(cell[0]) ? int.Parse(cell)
: (d.ContainsKey(cell) ? d[cell] : 0);
}
return ans;
}
}
/**
* Your Spreadsheet object will be instantiated and called as such:
* Spreadsheet obj = new Spreadsheet(rows);
* obj.SetCell(cell,value);
* obj.ResetCell(cell);
* int param_3 = obj.GetValue(formula);
*/type Spreadsheet struct {
d map[string]int
}
func Constructor(rows int) Spreadsheet {
return Spreadsheet{d: make(map[string]int)}
}
func (this *Spreadsheet) SetCell(cell string, value int) {
this.d[cell] = value
}
func (this *Spreadsheet) ResetCell(cell string) {
delete(this.d, cell)
}
func (this *Spreadsheet) GetValue(formula string) int {
ans := 0
cells := strings.Split(formula[1:], "+")
for _, cell := range cells {
if val, err := strconv.Atoi(cell); err == nil {
ans += val
} else {
ans += this.d[cell]
}
}
return ans
}
/**
* Your Spreadsheet object will be instantiated and called as such:
* obj := Constructor(rows);
* obj.SetCell(cell,value);
* obj.ResetCell(cell);
* param_3 := obj.GetValue(formula);
*/use std::collections::HashMap;
struct Spreadsheet {
d: HashMap<String, i32>,
}
impl Spreadsheet {
fn new(_rows: i32) -> Self {
Spreadsheet {
d: HashMap::new(),
}
}
fn set_cell(&mut self, cell: String, value: i32) {
self.d.insert(cell, value);
}
fn reset_cell(&mut self, cell: String) {
self.d.remove(&cell);
}
fn get_value(&self, formula: String) -> i32 {
let mut ans = 0;
for cell in formula[1..].split('+') {
if cell.chars().next().unwrap().is_ascii_digit() {
ans += cell.parse::<i32>().unwrap();
} else {
ans += *self.d.get(cell).unwrap_or(&0);
}
}
ans
}
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| 2D Matrix Simulation | O(1) cell access, O(L) formula evaluation | O(R × C) | When spreadsheet size is fixed and small |
| Hash Table Cell Storage | O(1) average updates/lookups, O(L) evaluation | O(K) | General case with sparse cells and dynamic updates |
Frequently asked questions
Is Design Spreadsheet easy or hard?
Design Spreadsheet is typically classified as a medium difficulty problem. The main challenge is building a clean design that parses expressions correctly while maintaining O(1) average-time cell access using a hash table.
Design Spreadsheet Python/Java solution
Implement a class that stores cell values in a dictionary or HashMap. Methods update the map for set and reset operations. Formula evaluation parses the string, identifies cell references, and retrieves values using constant‑time lookups.
How to solve Design Spreadsheet in O(1)?
Store cell values in a hash map keyed by cell identifiers. Setting or resetting a cell becomes a direct hash update, which is O(1) on average. When evaluating a formula like =A1+B2, parse the string and fetch values for each referenced cell using constant‑time hash lookups.
What is the best approach for Design Spreadsheet?
The hash table approach is the most practical solution. Store cell values in a map keyed by the cell label (such as "A1"). Updates and lookups run in O(1) average time, and formulas are evaluated by parsing the expression and performing constant‑time hash lookups for each referenced cell.
Is Design Spreadsheet asked at Google/Amazon/Meta?
Design-style data structure problems like Design Spreadsheet commonly appear in interviews at large tech companies. They test system modeling, hash table usage, and clean API design rather than heavy algorithmic complexity.
What data structure is used in Design Spreadsheet?
The core data structure is a hash table mapping cell identifiers to values. Some implementations also simulate the spreadsheet using a 2D array or matrix, but the hash table approach is more memory efficient when many cells are empty.
What is the time complexity of Design Spreadsheet?
Basic spreadsheet operations such as setting, resetting, and retrieving a cell run in O(1) average time using a hash table. Evaluating a formula takes O(L), where L is the length of the expression string, because the algorithm must parse tokens and resolve referenced cells.
