Skip to content
Problem 682 · LeetCode 682(opens in a new tab)

Baseball Game

EasyArrays

You are scoring a game with unusual rules. A record of scores starts empty, and you apply a list of operations to it in order. Each operation is one of four kinds.

A number means a new score of that value. "+" means a new score equal to the sum of the last two scores. "D" means a new score equal to twice the last score. "C" cancels the last score, which removes it from the record as if it never happened.

Return the sum of the scores left on the record once every operation has been applied.

Example 1

Input:  operations = ["4","7","D","C","+","-3"]
Output: 19
Why:    the record ends as 4, 7, 11, -3; the 14 from "D" was cancelled
2 more examples and the constraints

Example 2

Input:  operations = ["2","C","6"]
Output: 6
Why:    2 is cancelled, so only 6 is left

Example 3

Input:  operations = ["-5","D","+","C","C"]
Output: -5
Why:    -10 and -15 are added, then both cancelled

Constraints

  • 1 ≤ length of operations ≤ 1,000
  • Each operation is "+", "D", "C", or a number from −30,000 to 30,000
  • "+" always has two scores to read; "D" and "C" always have at least one
  • Every score and the final sum fit in a 32-bit signed integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Stack, then sumO(n)
  2. Stack with a running totalO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 operationsVerdict
Stack, then sumO(n)
Passes; one extra pass
Stack with a running totalO(n)
Best; single pass

n = number of operations.

Edge cases to test

  • Everything cancelled. ["1","C"] leaves an empty record, so the answer is 0.
  • Negative scores. "-3" is a number, not an operator; parse it as −3.
  • "+" after a cancel. It adds the two scores that are on the record now, not the ones that were cancelled.
  • Chained doubles. ["5","D","D"] gives 5, 10, 20 for a sum of 35.

Common mistakes

  • Letting "+" or "D" read a score that "C" already cancelled.
  • Telling numbers from operators by the first character, which breaks on "-3".
  • Popping the top two for "+" and forgetting to push them back.

How to talk through it

  1. 1Clarify. Are the operations always valid? Can scores be negative? Does the sum fit in an int?
  2. 2Pick the structure. Every rule reads or removes the latest scores, so a stack fits.
  3. 3Walk the four cases. Number: push. "+": push top two summed. "D": push double the top. "C": pop.
  4. 4Add the running total. Add on push and subtract on pop, so no final pass is needed.
  5. 5Test out loud. Run a list that cancels everything and one with a negative number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?