Baseball Game (LeetCode 682): Solution and Explanation
You are given a list of operations for a score sheet that starts empty. A number records a new score, "+" records the sum of the last two scores, "D" records double the last score, and "C" erases the last score. Return the sum of the scores left at the end.
Intuition
Look at what each operation touches. A number adds a new score at the end. "+" reads the last two scores, "D" reads the last one, and "C" removes the last one. Nothing ever reaches deeper than the two most recent scores that are still valid.
That pattern, where you only add to the end, read the end and remove from the end, is the definition of a stack. The important case is "C": once a score is erased, the score below it becomes the last one again, so a later "+" or "D" must use it. A stack handles that for free because popping exposes the previous item.
Once every operation has been applied, the stack holds exactly the valid scores, and the answer is their sum.
Approach: Stack simulation
- Create an empty list
recordto act as the stack. - For each operation: if it is
"+", pushrecord[-1] + record[-2]; if it is"D", push2 * record[-1]; if it is"C", pop the top. - Otherwise the operation is an integer, so parse it and push it.
- Return the sum of everything left in
record.
Step-by-step example
operations = ["5","2","C","D","+"]
- "5" is a number, so push 5. The stack is [5].
- "2" is a number, so push 2. The stack is [5, 2].
- "C" erases the top score 2. The stack is [5] and 5 is the top again.
- "D" doubles the top: 2 × 5 = 10. The stack is [5, 10].
- "+" adds the top two: 5 + 10 = 15. The stack is [5, 10, 15].
- The sum of the stack is 5 + 10 + 15 = 30, which is the answer.
Code: Python, Java, C++
1class Solution:
2 def calPoints(self, operations: List[str]) -> int:
3 record = []
4 for op in operations:
5 if op == "+":
6 record.append(record[-1] + record[-2])
7 elif op == "D":
8 record.append(2 * record[-1])
9 elif op == "C":
10 record.pop()
11 else:
12 record.append(int(op))
13 return sum(record)1class Solution {
2 public int calPoints(String[] operations) {
3 List<Integer> record = new ArrayList<>();
4 for (String op : operations) {
5 int n = record.size();
6 if (op.equals("+")) {
7 record.add(record.get(n - 1) + record.get(n - 2));
8 } else if (op.equals("D")) {
9 record.add(2 * record.get(n - 1));
10 } else if (op.equals("C")) {
11 record.remove(n - 1);
12 } else {
13 record.add(Integer.parseInt(op));
14 }
15 }
16 int total = 0;
17 for (int x : record) total += x;
18 return total;
19 }
20}1class Solution {
2public:
3 int calPoints(vector<string>& operations) {
4 vector<int> record;
5 for (const string& op : operations) {
6 int n = record.size();
7 if (op == "+") {
8 record.push_back(record[n - 1] + record[n - 2]);
9 } else if (op == "D") {
10 record.push_back(2 * record[n - 1]);
11 } else if (op == "C") {
12 record.pop_back();
13 } else {
14 record.push_back(stoi(op));
15 }
16 }
17 int total = 0;
18 for (int x : record) total += x;
19 return total;
20 }
21};Time and space complexity
O(n)
Each operation does a constant amount of work on the top of the stack, and the final sum visits each remaining score once.
O(n)
In the worst case every operation pushes a score, so the stack can hold n values.
Other approaches
Stack with a running total (time O(n), space O(n))
Keep a running sum alongside the stack: add every pushed value and subtract every popped value. The answer is ready the moment the loop ends, with no final pass. The asymptotic cost is the same.
Array with a size pointer (time O(n), space O(n))
Preallocate an array of length n and keep an index to the top. Pushing writes at the index and increments it, while "C" just decrements it. This avoids dynamic resizing and is handy in languages without a convenient list type.
Common mistakes
- Popping the two scores for
"+"instead of only reading them. Both earlier scores stay on the sheet; only the new sum is added. - Checking whether a string is an integer with a digit test that misses negative numbers like
"-2". Test for the three symbols first and treat everything else as a number. - Keeping only a running total without the stack. After
"C"you need to know which value to subtract and what the new last score is, which a single number cannot tell you. - Comparing strings with
==in Java. Useequals, or the symbol checks never match.
Frequently asked questions
Why is a stack the right structure for Baseball Game?
Every operation reads, adds or removes only the newest scores. A stack gives constant-time access to its top, and popping a score automatically exposes the one before it, which is what "C" needs.
Can the answer be negative?
Yes. Scores can be negative integers, and "D" or "+" on negative scores produce more negative values, so the final sum can be below zero.
What happens if every score is erased?
The stack is empty at the end, and the sum of an empty record is 0. For example, ["1","C"] returns 0.
What is the time complexity of Baseball Game?
O(n) time and O(n) space, where n is the number of operations. Each operation is constant work on the top of the stack.