Baseball Game

Easy

Topics
StackSimulation

You are given operations as a space-separated string s. Each token is an integer (record it), "+" (sum of last two), "D" (double last), or "C" (invalidate last). Return the total sum of the record.

Example 1

52CD+
Each chip is one entry on the record, applied in order. A number is scored as itself; C cancels the previous score, D scores double it, and + scores the sum of the two before it — so every operation reaches backwards into what is still on the record, and a cancelled score is gone for good. The answer is the total that survives, 30.
Chips are the operations in order.
Input:  s = "5 2 C D +"
Output: 30

Example 2

5-24CD9++
Input:  s = "5 -2 4 C D 9 + +"
Output: 27

Constraints

  • 1 <= number of operations <= 1000
  • Operations are valid when applied.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Four token types, three of which refer backwards: C cancels the previous score, D doubles it, + adds the last two. Everything touches the most recent entries, which is exactly a stack.

Once you see that, the whole problem is reading the tokens and keeping the running list of valid scores. The answer is the sum of whatever survives.

Worth noting what the stack buys over a plain running total: C needs to undo, and a single accumulator cannot undo without remembering what to subtract. Keeping the individual scores makes cancellation a pop.

Approach

  1. For each token: C pops; D pushes twice the top; + pushes the sum of the top two; a number pushes itself.
  2. Return the sum of the stack.

Dry Run

"5 2 C D +"

5   push 5            [5]
2   push 2            [5,2]
C   pop               [5]
D   push 2*5 = 10     [5,10]
+   push 5+10 = 15    [5,10,15]

sum = 30

Complexity

  • Time — O(n): one pass, constant work per token, plus a final sum.
  • Space — O(n): the stack, which in the worst case holds every token's score. A running total would be O(1) but cannot support C.

Common Pitfalls

  • Parsing negative numbers as operators. "-2" is a score, not a minus sign; test the token against the three operator strings and treat anything else as an integer.
  • Reading + as "add the top to itself". It is the sum of the last two distinct entries, and both remain on the stack.
  • Popping two values for +. Both operands stay; only the new total is pushed.
  • Using D to double the running total rather than the last score.
  • Guarding against empty-stack operations. The constraints promise the operations are valid when applied, so no guard is needed — but say that rather than silently assuming it.

Full Solution — all languages

class Solution:
    def calPoints(self, s):
        stack = []
        for tok in s.split():
            if tok == "C":
                stack.pop()
            elif tok == "D":
                stack.append(2 * stack[-1])
            elif tok == "+":
                stack.append(stack[-1] + stack[-2])
            else:
                stack.append(int(tok))
        return sum(stack)
SensAI
Beta
Tap the mic to stop voice mode