◀ THE GRIND — STACK

Baseball Game

The drill: Replay a baseball scoring log where a plain number adds a new score, "+" sums the previous two, "D" doubles the last one, and "C" erases the most recent entry — total whatever remains once the log ends.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A log of baseball scoring operations arrives as a list of string tokens. A token holding a plain number records a new score on the board; the other three tokens react to what's already there.

A '+' token sums the two most recently recorded scores and records that sum as a new entry. A 'D' token doubles the single most recent score and records the result. A 'C' token undoes the most recent recording entirely, removing it from the board.

Once every token has been processed, the drill totals whatever scores remain on the board and hands back that sum. The log always contains enough prior scores for every '+', 'D', or 'C' it uses.

EX 01
operations = ["5", "2", "C", "D", "+"]
30
CANCEL THEN DOUBLE THEN SUM
EX 02
operations = ["10", "-5", "+", "C", "D"]
-5
NEGATIVE COMPLETES A SUM
EX 03
operations = ["1"]
1
MINIMUM SIZE, NO OPERATORS
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Each entry in the log either adds a new score or reaches back into scores already on the board — the structure you pick needs to remember recent history, not just a running total.

HINT 2 THE STRUCTURE

A stack is exactly “recent history”: push new scores, and for “+” or “D” peek at the top one or two entries; “C” just pops.

HINT 3 ONE STEP FROM THE ANSWER

Walk the operations once, pushing parsed integers and using peek/pop for “+”, “D”, and “C”, then sum whatever is left on the stack at the end.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE SCOREBOARD STACKPATTERN · EXPLICIT STACKoperations = ["5", "2", "C", "D", "+"]
5
2
C
D
+
SCORE STACK
— empty —
STEP 1

Replay the log left to right; the stack always holds the board's current scores.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/baseball-game.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def calPoints(self, operations: List[str]) -> int:
        stack = []
        for op in operations:
            if op == "C":
                stack.pop()
            elif op == "D":
                stack.append(2 * stack[-1])
            elif op == "+":
                stack.append(stack[-1] + stack[-2])
            else:
                stack.append(int(op))
        return sum(stack)
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED