OpenAI questions

Spreadsheet with Formulas

OpenAIOnsiteMedium

Design a spreadsheet engine as a class Spreadsheet.

A cell name is a column letter A to Z followed by a row number 1 to 100, such as A1 or Z100. A cell that was never written holds 0.

The content written to a cell is either a number such as "5" or "-12", or a formula that starts with =. A formula is a list of terms joined by + and - with no spaces. Each term is a non-negative whole number or a cell name, and the first term has no sign, for example "=A1+B1-3".

Formulas are live: get_cell always reflects the current contents of the cells a formula refers to, including cells that have not been written yet.

Each test drives one Spreadsheet() instance through a sequence of calls and checks every return value.

Part 1: Values and formulas

Implement Spreadsheet with two methods.

set_cell(cell, content) stores content in cell, replacing whatever was there, and returns True.

get_cell(cell) returns the cell's current value as an integer. A cell holding a number returns that number. A cell holding a formula returns the sum of its terms, subtracting each term that follows a -. An unwritten cell returns 0.

  1. Example 1
    init
    []
    operations
    [["set_cell",["A1","5"]],["set_cell",["B1","10"]],["set_cell",["C1","=A1+B1"]],["get_cell",["C1"]],["set_cell",["A1","7"]],["get_cell",["C1"]],["get_cell",["Z9"]],["set_cell",["D1","=C1-A1-3"]],["get_cell",["D1"]]]
    Output
    [true,true,true,15,true,17,0,true,7]

    Why: C1 holds a formula, so it tracks A1: after A1 changes from 5 to 7 it reads 7 + 10 = 17. Z9 was never written and reads 0. D1 evaluates 17 - 7 - 3 = 7.

Constraints

  • 1 <= len(operations) <= 10^3
  • Cell names are a column 'A' to 'Z' followed by a row 1 to 100
  • Every stored or computed value has absolute value at most 10^12
  • A formula in content has at most 20 terms
  • Dependency chains reachable from any cell are at most 100 cells long
  • No formula refers to the cell that holds it, directly or through other cells
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Spreadsheet with Formulas: OpenAI interview question | LoopCoach