LeetCode's "Design Excel Sum Formula" problem asks you to build a small spreadsheet engine: cells that can hold an integer or a formula like =B2+C1+D1:E3, where a formula can reference single cells or rectangular ranges. The cleanest accepted solution uses a 2D array of maps — each cell stores its value, and each formula cell stores a counter of the cells it depends on — so set recomputes only what changed and sum resolves references on the fly. Below is a step-by-step guide to designing, coding, and passing that solution on LeetCode.
What You'll Need
- A LeetCode account and the problem page open (search for "Design Excel Sum Formula" in the problem list).
- A working knowledge of one supported language — Python, Java, C++, or JavaScript all work fine here.
- Comfort with hash maps (dictionaries) and basic string parsing.
- About 30–60 minutes if it is your first attempt; the problem is rated Hard, mostly because of reference parsing and update propagation.
Step-by-Step
- Read the required interface. The class has three operations: initialize with height and width,
set(row, column, val)to write a raw number into a cell, andsum(row, column, numbers)to assign a formula (a list of strings like"A1"or"B2:C4") and return the cell's resulting value. There is also a getter that returns a cell's current value. - Choose your data model. Use a 2D grid of cells. Each cell should hold either a plain integer or a formula represented as a dictionary mapping
reference -> count, for example{"A1": 1, "B2:C4": 1}. The count matters because the same reference can appear more than once in one formula. - Normalize coordinates. Rows are 1-based integers; columns are letters (A = 1, B = 2, and so on). Write two helpers: one to convert a column letter or letters to a number, and one to parse a single token like
"AB12"into (row, col). Parsing multi-letter columns is a classic off-by-one trap, so test it withZ(26) andAA(27). - Parse references in sum. For each string in
numbers, check whether it contains a colon. If not, it is a single cell; if it does, split it into two corners and record the range string as-is in the formula's dictionary. You do not need to expand ranges into individual cells — keep the range string and resolve it when computing. - Compute a formula's value lazily. Write a function that, given a formula dictionary, loops over its references: a single cell contributes its stored value; a range contributes the sum of all cells inside its rectangle. Multiply each contribution by its count in the dictionary.
- Implement set. Replace the cell's content with the plain integer. Because other formula cells recompute lazily, no dependency graph or cascading update is needed — formulas simply read the new value next time they are evaluated.
- Implement sum. Store the parsed formula dictionary in the target cell, compute its value with your lazy evaluator, and return that value.
- Keep cached values only if you want speed. A fully lazy version recomputes on every getter call, which is fast enough for LeetCode's constraints. If you prefer, cache the computed value and invalidate nothing — just recompute on read — which keeps the code simple and bug-free.
- Test locally first. Try the sample scenario: set A1 = 1, set B2 = 2, then sum C1 over [A1, A1:B2]. The result must be 6 (A1 counted twice plus B2). Also test a formula referencing another formula cell, and overwriting a formula cell with
set. - Submit and iterate. Run the code against LeetCode's test cases. If a wrong-answer verdict appears, print your parsed references and per-term contributions for the failing case to find the mismatch.
Common Mistakes
- Treating column letters as single characters. Forgetting multi-letter columns (AA, AB) breaks parsing on larger grids.
- Assuming formulas are symmetric. Ranges are given as top-left:bottom-right in the tests, but swapping corners in your code without care can produce empty sums — decide explicitly whether to normalize corner order.
- Dropping duplicate references. Storing references as a set instead of a counted map loses duplicates like [A1, A1] and gives wrong totals.
- Breaking chained formulas. Overwriting a cell with
setmust not corrupt formulas that reference it; lazy evaluation avoids this, but eager caching without invalidation does not. - Off-by-one indexing. Mixing 0-based arrays with 1-based problem coordinates is the most common source of wrong answers here.
Tips
- Keep ranges unexpanded. Storing "B2:C4" as one key is simpler and smaller than listing nine cells, and it naturally handles the duplicate-count requirement.
- Separate parsing from evaluation into small helper functions; it makes the code readable and easier to debug.
- In Python, a plain
dictpluscollections.defaultdict(int)covers the counting logic in a couple of lines. - Remember the follow-up idea: for huge sheets you would want a real dependency graph with topological recalculation, but LeetCode's constraints do not require it.
Troubleshooting
- Wrong answer on ranges: log each term's value during evaluation and compare against a manual calculation of the failing test.
- Index out of range errors: check your coordinate conversion for both single cells and range corners; verify row and column are not swapped when indexing the grid.
- Formulas not updating after set: you are caching values without recomputing. Either recompute on every read or remove the cache.
- Time limit exceeded: you are probably expanding large ranges into individual cell entries. Keep ranges intact and sum them in a loop at evaluation time.
- Still stuck: read the official problem discussion tab's top-rated solutions for your language after attempting it yourself — comparing your parsing logic against an accepted one usually reveals the bug quickly.
Frequently Asked Questions
Is this problem really about Excel?
No. It is a simplified spreadsheet simulation. Real Excel features like functions, text, and auto-recalculation order are not required — only integer cells and sum formulas with cell and range references.
Do I need a dependency graph?
No. Because formulas can be evaluated lazily on read, storing formula dictionaries and recomputing values on demand is accepted. A dependency graph is a valid optimization but adds complexity you do not need here.
Can a formula reference another formula cell?
Yes. When your evaluator reads a referenced cell, if that cell holds a formula, evaluate it recursively. With lazy evaluation this works automatically.
What is the time complexity of the lazy approach?
Each getter or sum call costs the total number of cells covered by that formula's references, and set is O(1). That is comfortably within the problem's constraints.
Which language is easiest for this problem?
Python is a popular pick because dictionaries and string split make the formula-map logic very short, but any LeetCode-supported language works equally well.
What is the key takeaway for interviews?
Choosing the right data model: a counted reference map per formula cell plus lazy evaluation removes the hardest part of the problem (update propagation) entirely.