Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Design Spreadsheet

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3484" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 specified cell. 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", where X and Y are 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 columns spreadsheet.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 <= 103 0 <= value <= 105 The formula is always in the format "=X+Y", where X and Y are either valid cell references or non-negative integers with values less than or equal to 105. Each cell reference consists of a capital letter from 'A' to 'Z' followed by a row number between 1 and rows. At most 104 calls will be made in total to setCell, resetCell, and getValue.

Explanation

  • Data Structure: Use a 2D array (list of lists in Python) to represent the spreadsheet. This allows for direct access to cell values using row and column indices.
    • Cell Conversion: Create helper functions to convert between cell references (e.g., "A1") and row/column indices. This improves code readability and maintainability.
    • Formula Evaluation: Parse the formula string, identify operands (either cell references or integers), and calculate the sum. Handle the case where a referenced cell is not explicitly set by treating it as 0.
  • Runtime Complexity: O(1) for setCell, resetCell, and getValue.
  • Storage Complexity: O(rows) since we create a 2D array of size rows * 26.

Code

    class Spreadsheet:

    def __init__(self, rows: int):
        self.rows = rows
        self.grid = [[0] * 26 for _ in range(rows)]

    def _cell_to_indices(self, cell: str) -> tuple[int, int]:
        """Converts a cell reference (e.g., "A1") to row and column indices."""
        col = ord(cell[0]) - ord('A')
        row = int(cell[1:]) - 1
        return row, col

    def _get_cell_value(self, row: int, col: int) -> int:
        """Gets the value of a cell at the given row and column."""
        return self.grid[row][col]

    def setCell(self, cell: str, value: int) -> None:
        """Sets the value of the specified cell."""
        row, col = self._cell_to_indices(cell)
        self.grid[row][col] = value

    def resetCell(self, cell: str) -> None:
        """Resets the specified cell to 0."""
        row, col = self._cell_to_indices(cell)
        self.grid[row][col] = 0

    def getValue(self, formula: str) -> int:
        """Evaluates a formula of the form "=X+Y" and returns the result."""
        formula = formula[1:]  # Remove the "=" sign
        parts = formula.split('+')
        operand1 = parts[0].strip()
        operand2 = parts[1].strip()

        def get_value(operand: str) -> int:
            if 'A' <= operand[0] <= 'Z':
                row, col = self._cell_to_indices(operand)
                return self._get_cell_value(row, col)
            else:
                return int(operand)

        value1 = get_value(operand1)
        value2 = get_value(operand2)
        return value1 + value2

More from this blog

C

Chatmagic blog

2894 posts