leetcode

Design Spreadsheet - Link

Question Description

Implement a simple spreadsheet where:

Methods:


Constraints


Approach

Use a HashMap to store cell values with cell references as keys.

Operations:

Formula parsing:

Why this approach works:

Alternative approaches considered:


Dry Run

Example Operations:

Spreadsheet obj = new Spreadsheet(3);
obj.setCell("A1", 5);
obj.setCell("B1", 10);
obj.getValue("=A1+B1+3"); // returns 18
obj.resetCell("A1");
obj.getValue("=A1+B1+3"); // returns 13

Step-by-step execution:


Solution

import java.util.*;

class Spreadsheet {

    private Map<String, Integer> cellMap = new HashMap<>();
    
    public Spreadsheet(int rows) {
        // rows parameter can be used for validation if needed
    }
    
    public void setCell(String cell, int value) {
        cellMap.put(cell, value);
    }
    
    public void resetCell(String cell) {
        cellMap.put(cell, 0);
    }
    
    public int getValue(String formula) {
        int sum = 0;
        // skip '=' at start
        for (String s : formula.substring(1).split("\\+")) {
            sum += mapToValue(s.trim());
        }
        return sum;
    }

    private int mapToValue(String s) {
        return Character.isLetter(s.charAt(0)) ? cellMap.getOrDefault(s, 0) : Integer.parseInt(s);
    }
}

Time and Space Complexity