Baseball Game
Easy
Topics
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
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.Input: s = "5 2 C D +" Output: 30
Example 2
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
- For each token:
Cpops;Dpushes twice the top;+pushes the sum of the top two; a number pushes itself. - 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 = 30Complexity
- 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
Dto 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)import java.util.*;
class Solution {
public int calPoints(String s) {
Deque<Integer> stack = new ArrayDeque<>();
for (String tok : s.trim().split("\\s+")) {
if (tok.equals("C")) stack.pop();
else if (tok.equals("D")) stack.push(2 * stack.peek());
else if (tok.equals("+")) {
int a = stack.pop();
int b = a + stack.peek();
stack.push(a);
stack.push(b);
} else stack.push(Integer.parseInt(tok));
}
int sum = 0;
for (int x : stack) sum += x;
return sum;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int calPoints(string s) {
vector<int> stack;
stringstream ss(s);
string tok;
while (ss >> tok) {
if (tok == "C") stack.pop_back();
else if (tok == "D") stack.push_back(2 * stack.back());
else if (tok == "+") stack.push_back(stack[stack.size()-1] + stack[stack.size()-2]);
else stack.push_back(stoi(tok));
}
int sum = 0;
for (int x : stack) sum += x;
return sum;
}
};/**
* @param {string} s
* @return {number}
*/ var calPoints = function(s) {
const stack = [];
for (const tok of s.split(/\s+/).filter(x => x.length)) {
if (tok === 'C') stack.pop();
else if (tok === 'D') stack.push(2 * stack[stack.length - 1]);
else if (tok === '+') stack.push(stack[stack.length - 1] + stack[stack.length - 2]);
else stack.push(parseInt(tok, 10));
}
return stack.reduce((a, b) => a + b, 0);
};