Stack + running total

Close a Nested Ledger

01. The question

An account has an opening balance and a grouped adjustment note. Evaluate its whole-number additions, subtractions, and parentheses, then return the closing balance. No multiplication or division.

Before revealing the idea, predict the result and describe what information you would need to track.

02. Worked example

Inputopening = 40, note = "(18 - (6 + 2)) - 5"

Output45

  1. Start with an opening balance of 40, but evaluate the adjustment separately.
  2. The inner group 6 + 2 is 8. The outer group becomes 18 - 8 = 10.
  3. Subtract the final 5: the adjustment is +5.
  4. Add that adjustment to the opening balance: 40 + 5 = 45.

Try your code

Define solve(data, parameter="") and return your result. Your code runs locally, not on a server.

Edit your test cases

Use 1-10 objects with data and an optional string parameter. Expected outputs are computed from the lesson. An optional expected field must be correct.

Input contract & reference code

Example data: "(18 - (6 + 2)) - 5". Parameter: "40". Numeric parameters arrive as strings; convert them with int(parameter) when needed.

The example and generated cases use the question’s exact variant. This checks behavior on a small test batch—not performance on every possible input.

Python runtime notices

Python downloads only when you run code, using compressed runtime assets. Code is not saved or uploaded. Enable JavaScript to run it.

Five-second execution limit per batch. Standard-library Python only; additional packages and network access are unavailable. Stop ends execution without blocking the lesson.

03. The idea

Try sketching your own approach first. What would you track, and why would it work?

Reveal the idea
  1. Collect digits into number using number * 10 + digit.
  2. At + or -, commit the previous number, then set the sign for the next one.
  3. At (, push the outside result and sign. At ), finish inside and combine with the saved frame.

04. Watch it happen

Use Step to move slowly, or Play to follow the whole trace. Change a preset or load your own input.

Input & settings

Use integers, +, -, parentheses and spaces (max 100 characters). Opening balance: -1,000,000 to 1,000,000.

Red = current item / blue = active window or cells / green = completed work. A value docks at its actual destination; the original input stays unchanged. Positions start at 0.

Working state / what changes

Ready to begin

Enable JavaScript to step through the animation. The worked example and solution below remain readable without it.

Python / why it changes

The line behind the step

def close_ledger(note: str, opening: int) -> int:
    result, number, sign = 0, 0, 1
    stack = []
    for ch in note:
        if '0' <= ch <= '9':
            number = number * 10 + int(ch)
        elif ch in '+-':
            result += sign * number
            number = 0
            sign = 1 if ch == '+' else -1
        elif ch == '(':
            stack.append((result, sign))
            result, number, sign = 0, 0, 1
        elif ch == ')':
            result += sign * number
            number = 0
            outside_result, outside_sign = stack.pop()
            result = outside_result + outside_sign * result
    return opening + result + sign * number
How to use this walkthrough

Hover or focus a control for its label. Play forms the input and follows values into the working state. Step shows one change; Back and the slider restore exact snapshots. Reduced motion uses instant updates. Saved snapshots and sorted heap displays are teaching overhead, not algorithm complexity.

05. Python solution

def close_ledger(note: str, opening: int) -> int:
    result, number, sign = 0, 0, 1
    stack = []
    for ch in note:
        if '0' <= ch <= '9':
            number = number * 10 + int(ch)
        elif ch in '+-':
            result += sign * number
            number = 0
            sign = 1 if ch == '+' else -1
        elif ch == '(':
            stack.append((result, sign))
            result, number, sign = 0, 0, 1
        elif ch == ')':
            result += sign * number
            number = 0
            outside_result, outside_sign = stack.pop()
            result = outside_result + outside_sign * result
    return opening + result + sign * number

06. Cost & edge cases

Time
O(n)
Space
O(n) in the worst case
  • Collect multi-digit amounts before committing them.
  • A leading minus is valid, including inside parentheses. The closing balance may be negative.
  • The Python function expects a valid note. The animation rejects malformed notes and integers that cannot be represented exactly.

Keep going