KatInterview

631. Design Excel Sum Formula

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to implement a simplified version of an Excel spreadsheet. The core functionalities are initializing a sheet, setting a cell's value to an integer, getting a cell's value, and defining a cell's value as a sum of other cells or ranges. The most challenging aspect is handling the sum formulas. When a cell's value is defined by a formula, it depends on other cells. If any of these dependency cells change their value, the formula cell must reflect this change. This dynamic relationship necessitates a system for tracking and re-evaluating formulas upon request.

Solution

Design Excel Sum Formula in Python

class Excel:

    def __init__(self, height: int, width: str):
        # Internally use 0-indexed rows and columns
        self.H = height
        self.W = ord(width) - ord('A') + 1
        # Each cell is a dictionary storing its value and formula
        self.sheet = [[{'val': 0, 'formula': None} for _ in range(self.W)] for _ in range(self.H)]

    def set(self, row: int, column: str, val: int) -> None:
        r, c = row - 1, ord(column) - ord('A')
        # Set value and clear any existing formula
        self.sheet[r][c] = {'val': val, 'formula': None}

    def get(self, row: int, column: str) -> int:
        r, c = row - 1, ord(column) - ord('A')
        # Create a memoization dictionary for this specific get call
        return self._calculate(r, c, {})

    def _calculate(self, r: int, c: int, memo: dict) -> int:
        # Use tuple (r, c) as key for memoization
        if (r, c) in memo:
            return memo[(r, c)]

        cell = self.sheet[r][c]
        if cell['formula'] is None:
            memo[(r, c)] = cell['val']
            return cell['val']
        
        total_sum = 0
        for s in cell['formula']:
            if ':' in s:
                # It's a range, e.g., "A1:B2"
                p1_str, p2_str = s.split(':')
                c1, r1 = ord(p1_str[0]) - ord('A'), int(p1_str[1:]) - 1
                c2, r2 = ord(p2_str[0]) - ord('A'), int(p2_str[1:]) - 1
                
                for ri in range(r1, r2 + 1):
                    for ci in range(c1, c2 + 1):
                        total_sum += self._calculate(ri, ci, memo)
            else:
                # It's a single cell, e.g., "A1"
                c1, r1 = ord(s[0]) - ord('A'), int(s[1:]) - 1
                total_sum += self._calculate(r1, c1, memo)
        
        memo[(r, c)] = total_sum
        return total_sum

    def sum(self, row: int, column: str, numbers: list[str]) -> int:
        r, c = row - 1, ord(column) - ord('A')
        # Set the formula. The old value is now irrelevant.
        self.sheet[r][c]['formula'] = numbers
        # The sum function must return the calculated value.
        return self.get(row, column)


# Your Excel object will be instantiated and called as such:
# obj = Excel(height, width)
# obj.set(row,column,val)
# param_2 = obj.get(row,column)
# param_3 = obj.sum(row,column,numbers)

Design Excel Sum Formula in Java

class Excel {
    private Cell[][] sheet;

    // Inner class to represent a cell, holding either a value or a formula.
    private class Cell {
        int val = 0;
        String[] formula = null;
    }

    public Excel(int height, char width) {
        // Internally, use 0-indexed rows and columns.
        // sheet is height x (width-'A'+1)
        sheet = new Cell[height][width - 'A' + 1];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j <= width - 'A'; j++) {
                sheet[i][j] = new Cell();
            }
        }
    }
    
    public void set(int row, char column, int val) {
        int r = row - 1;
        int c = column - 'A';
        // A new cell object cleanly overwrites any previous state (value or formula).
        sheet[r][c] = new Cell();
        sheet[r][c].val = val;
    }
    
    public int get(int row, char column) {
        int r = row - 1;
        int c = column - 'A';
        // Create a memoization map for this specific get call.
        return calculate(r, c, new HashMap<>());
    }
    
    // Recursive helper to calculate cell value with memoization.
    private int calculate(int r, int c, Map<Integer, Integer> memo) {
        int key = r * 26 + c; // Unique key for the cell (r,c)
        if (memo.containsKey(key)) {
            return memo.get(key);
        }

        Cell cell = sheet[r][c];
        if (cell.formula == null) {
            memo.put(key, cell.val);
            return cell.val;
        }

        int totalSum = 0;
        for (String s : cell.formula) {
            if (s.contains(":")) {
                // It's a range, e.g., "A1:B2"
                String[] parts = s.split(":");
                int c1 = parts[0].charAt(0) - 'A';
                int r1 = Integer.parseInt(parts[0].substring(1)) - 1;
                int c2 = parts[1].charAt(0) - 'A';
                int r2 = Integer.parseInt(parts[1].substring(1)) - 1;
                
                for (int i = r1; i <= r2; i++) {
                    for (int j = c1; j <= c2; j++) {
                        totalSum += calculate(i, j, memo);
                    }
                }
            } else {
                // It's a single cell, e.g., "A1"
                int c1 = s.charAt(0) - 'A';
                int r1 = Integer.parseInt(s.substring(1)) - 1;
                totalSum += calculate(r1, c1, memo);
            }
        }
        
        memo.put(key, totalSum);
        return totalSum;
    }

    public int sum(int row, char column, String[] numbers) {
        int r = row - 1;
        int c = column - 'A';
        // Set the formula for the cell. The old value is now irrelevant.
        sheet[r][c].formula = numbers;
        // The sum function must return the calculated value.
        return get(row, column);
    }
}

Design Excel Sum Formula in C++

class Excel {
private:
    // Using a pair to store cell data: {value, formula}
    // An empty vector for the formula indicates a raw value cell.
    vector<vector<pair<int, vector<string>>>> sheet;
    int H, W;

    // Recursive helper to calculate cell value with memoization
    int calculate(int r, int c, unordered_map<int, int>& memo) {
        int key = r * 26 + c; // Unique key for the cell (r, c)
        if (memo.count(key)) {
            return memo[key];
        }

        // If the formula list is empty, it's a raw value cell
        if (sheet[r][c].second.empty()) {
            return memo[key] = sheet[r][c].first;
        }
        
        int totalSum = 0;
        for (const string& s : sheet[r][c].second) {
            size_t colon_pos = s.find(':');
            if (colon_pos != string::npos) {
                // It's a range, e.g., "A1:B2"
                string s1 = s.substr(0, colon_pos);
                string s2 = s.substr(colon_pos + 1);
                
                int c1 = s1[0] - 'A';
                int r1 = stoi(s1.substr(1)) - 1;
                int c2 = s2[0] - 'A';
                int r2 = stoi(s2.substr(1)) - 1;

                for (int i = r1; i <= r2; ++i) {
                    for (int j = c1; j <= c2; ++j) {
                        totalSum += calculate(i, j, memo);
                    }
                }
            } else {
                // It's a single cell, e.g., "A1"
                int c1 = s[0] - 'A';
                int r1 = stoi(s.substr(1)) - 1;
                totalSum += calculate(r1, c1, memo);
            }
        }
        
        return memo[key] = totalSum;
    }

public:
    Excel(int height, char width) {
        H = height;
        W = width - 'A' + 1;
        // Internally, use 0-indexed rows and columns.
        // sheet is H x W.
        sheet.resize(H, vector<pair<int, vector<string>>>(W, {0, {}}));
    }
    
    void set(int row, char column, int val) {
        int r = row - 1;
        int c = column - 'A';
        // Set the value and clear any existing formula.
        sheet[r][c] = {val, {}};
    }
    
    int get(int row, char column) {
        int r = row - 1;
        int c = column - 'A';
        // Create a memoization map for this specific get call.
        unordered_map<int, int> memo;
        return calculate(r, c, memo);
    }
    
    int sum(int row, char column, vector<string> numbers) {
        int r = row - 1;
        int c = column - 'A';
        // Set the formula for the cell. The old value is now irrelevant.
        sheet[r][c] = {0, numbers};
        // The sum function must return the calculated value.
        return get(row, column);
    }
};

Design Excel Sum Formula in TypeScript

class Excel {
    private sheet: { val: number; formula: string[] | null }[][];

    constructor(height: number, width: string) {
        const H = height;
        const W = width.charCodeAt(0) - 'A'.charCodeAt(0) + 1;
        // Correctly initialize a 2D array of unique objects
        this.sheet = Array.from({ length: H }, () => 
            Array.from({ length: W }, () => ({ val: 0, formula: null }))
        );
    }

    set(row: number, column: string, val: number): void {
        const r = row - 1;
        const c = column.charCodeAt(0) - 'A'.charCodeAt(0);
        // A new object cleanly overwrites any previous state (value or formula).
        this.sheet[r][c] = { val, formula: null };
    }

    get(row: number, column: string): number {
        const r = row - 1;
        const c = column.charCodeAt(0) - 'A'.charCodeAt(0);
        // Create a memoization map for this specific get call.
        const memo = new Map<number, number>();
        return this.calculate(r, c, memo);
    }

    private calculate(r: number, c: number, memo: Map<number, number>): number {
        const key = r * 26 + c; // Unique key for cell (r, c)
        if (memo.has(key)) {
            return memo.get(key)!;
        }

        const cell = this.sheet[r][c];
        if (cell.formula === null) {
            memo.set(key, cell.val);
            return cell.val;
        }

        let totalSum = 0;
        for (const s of cell.formula) {
            const colonIndex = s.indexOf(':');
            if (colonIndex !== -1) {
                // It's a range, e.g., "A1:B2"
                const s1 = s.substring(0, colonIndex);
                const s2 = s.substring(colonIndex + 1);

                const c1 = s1.charCodeAt(0) - 'A'.charCodeAt(0);
                const r1 = parseInt(s1.substring(1)) - 1;
                const c2 = s2.charCodeAt(0) - 'A'.charCodeAt(0);
                const r2 = parseInt(s2.substring(1)) - 1;

                for (let i = r1; i <= r2; i++) {
                    for (let j = c1; j <= c2; j++) {
                        totalSum += this.calculate(i, j, memo);
                    }
                }
            } else {
                // It's a single cell, e.g., "A1"
                const c1 = s.charCodeAt(0) - 'A'.charCodeAt(0);
                const r1 = parseInt(s.substring(1)) - 1;
                totalSum += this.calculate(r1, c1, memo);
            }
        }
        
        memo.set(key, totalSum);
        return totalSum;
    }

    sum(row: number, column: string, numbers: string[]): number {
        const r = row - 1;
        const c = column.charCodeAt(0) - 'A'.charCodeAt(0);
        // Set the formula. The old value is now irrelevant.
        this.sheet[r][c].formula = numbers;
        // The sum function must return the calculated value.
        return this.get(row, column);
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.