Introduction
LeetCode 682 Baseball Game is one of the cleanest and most beginner-friendly stack simulation problems on LeetCode. It does not require any fancy algorithm or deep insight — it purely tests whether you can carefully read the rules and simulate them faithfully using the right data structure.
But do not let "Easy" fool you. This problem is a great place to practice thinking about which data structure fits best and why. We will solve it three different ways — Stack, ArrayList, and Deque — so you can see the tradeoffs and pick the one that makes most sense to you.
You can find the problem here — LeetCode 682 Baseball Game.
What Is the Problem Really Asking?
You are keeping score for a baseball game with four special rules. You process a list of operations one by one and maintain a record of scores. At the end, return the total sum of all scores in the record.
The four operations are:
A number (like "5" or "-2") — just add that number as a new score to the record.
"C" — the last score was invalid, remove it from the record.
"D" — add a new score that is double the most recent score.
"+" — add a new score that is the sum of the two most recent scores.
That is it. Four rules, simulate them in order, sum up what is left.
Real Life Analogy — A Scoreboard With Corrections
Imagine a scoreboard operator at a sports event. They write scores on a whiteboard as the game progresses:
- A player scores 5 points → write 5
- Another player scores 2 → write 2
- Referee says last score was invalid → erase the last number (C)
- Special bonus rule kicks in → double the last valid score (D)
- Two scores combine → add the last two scores as one entry (+)
At the end, add up everything on the whiteboard. The stack is your whiteboard — you write on top and erase from the top.
Why Stack Is the Natural Fit
All four operations only ever look at or modify the most recently added scores. C removes the last one. D doubles the last one. + uses the last two. This "most recent first" access pattern is the definition of LIFO — Last In First Out — which is exactly what a Stack provides.
Any time a problem says "the previous score" or "the last two scores," your brain should immediately think Stack.
Approach 1: Stack (Your Solution) ✅
The Idea
Use a Stack of integers. For each operation:
- Number → parse and push
- C → pop the top
- D → peek the top, push doubled value
- + → pop top two, push both back, push their sum
One small improvement over your original solution — using op.equals("C") instead of op.charAt(0) == 'C'. This is cleaner and handles edge cases better since negative numbers like "-2" also start with - not a digit, so charAt(0) comparisons can get tricky. Using equals is always safer for string operations.
Why the + Operation Needs Pop-Push-Pop
The trickiest part is the + operation. You need the two most recent scores. Stack only lets you see the top. So you pop the first, then the second, compute the sum, then push both back before pushing the sum. This restores the record correctly — the previous two scores stay, and the new sum score is added on top.
Detailed Dry Run — ops = ["5","2","C","D","+"]
Let us trace every step carefully:
"5" → number, parse and push Stack: [5]
"2" → number, parse and push Stack: [5, 2]
"C" → remove last score, pop Stack: [5]
"D" → double last score, peek=5, push 10 Stack: [5, 10]
"+" → sum of last two:
- pop prev1 = 10
- pop prev2 = 5
- sum = 15
- push prev2=5, push prev1=10, push sum=15 Stack:
[5, 10, 15]
Sum all: 5 + 10 + 15 = 30 ✅
Detailed Dry Run — ops = ["5","-2","4","C","D","9","+","+"]
"5" → push 5. Stack: [5]
"-2" → push -2. Stack: [5, -2]
"4" → push 4. Stack: [5, -2, 4]
"C" → pop 4. Stack: [5, -2]
"D" → peek=-2, push -4. Stack: [5, -2, -4]
"9" → push 9. Stack: [5, -2, -4, 9]
"+" → prev1=9, prev2=-4, sum=5. Push -4, 9, 5. Stack: [5, -2, -4, 9, 5]
"+" → prev1=5, prev2=9, sum=14. Push 9, 5, 14. Stack: [5, -2, -4, 9, 5, 14]
Sum: 5 + (-2) + (-4) + 9 + 5 + 14 = 27 ✅
Approach 2: ArrayList (Most Readable)
The Idea
ArrayList gives you index-based access which makes the + operation much cleaner — no need to pop and push back. Just access the last two elements directly using size()-1 and size()-2.
See how the + operation becomes a single line with ArrayList? record.get(n-1) + record.get(n-2) directly accesses the last two elements without any pop-push gymnastics.
Dry Run — ops = ["5","2","C","D","+"]
- "5" → add 5. List:
[5] - "2" → add 2. List:
[5, 2] - "C" → remove last. List:
[5] - "D" → 5×2=10, add 10. List:
[5, 10] - "+" → get(0)+get(1) = 5+10=15, add 15. List:
[5, 10, 15]
Sum: 30 ✅
Time Complexity: O(n) — single pass through operations Space Complexity: O(n) — ArrayList stores at most n scores
The one tradeoff — remove(n-1) on an ArrayList is O(1) for the last element (no shifting needed). And get() is O(1). So this is fully O(n) overall and arguably the cleanest solution to read and understand.
Approach 3: Deque (ArrayDeque — Fastest in Java)
The Idea
ArrayDeque is faster than Stack in Java because Stack is synchronized (thread-safe overhead) and ArrayDeque is not. For single-threaded LeetCode problems, ArrayDeque is always the better choice over Stack.
The logic is identical to the Stack approach. The only difference is the method names — offerLast instead of push, pollLast instead of pop, peekLast instead of peek.
Time Complexity: O(n) Space Complexity: O(n)
For iterating a Deque to sum, you can use a for-each loop directly — no need to pop everything out like with Stack.
Approach Comparison
| Approach | Time | Space | Best For |
| Stack | O(n) | O(n) | Classic interview answer, clear LIFO intent |
| ArrayList | O(n) | O(n) | Cleanest code, easiest to read |
| ArrayDeque | O(n) | O(n) | Best performance, preferred in production |
All three approaches have identical time and space complexity. The difference is purely in code style and readability. In an interview, any of these is perfectly acceptable. Mention that ArrayDeque is preferred over Stack in Java for performance if you want to impress.
Why op.equals() Is Better Than op.charAt(0)
Your original solution uses operations[i].charAt(0) == 'C' to check operations. This works but has a subtle risk — the + character check with charAt(0) is fine, but imagine if a future test had a number starting with C or D (it will not in this problem but defensive coding is a good habit). More importantly, "-2".charAt(0) is '-' which is fine, but using equals is semantically clearer — you are comparing the whole string, not just the first character. This shows cleaner coding habits in interviews.
Edge Cases to Know
Negative numbers like "-2" Integer.parseInt("-2") handles negatives perfectly. The D operation on -2 gives -4. The + operation works correctly with negatives too. No special handling needed.
"C" after a "+" that added a score The problem guarantees C always has at least one score to remove. So after + adds a score, a C removes just that one new score — the previous two scores that + used remain intact. This is correct behavior and our solution handles it automatically.
All scores removed If all operations are numbers followed by C operations removing every score, the stack ends up empty and the sum is 0. Our while loop handles this correctly — it simply never executes and returns 0.
Only one operation A single number like ["5"] → push 5, sum is 5. Works fine.
Common Mistakes to Avoid
In the + operation, forgetting to push both numbers back When you pop prev1 and prev2 to compute the sum, you must push them back onto the stack before pushing the sum. If you only push the sum without restoring prev1 and prev2, those scores disappear from the record permanently — which is wrong. The + operation only adds a new score, it does not remove the previous ones.
Using charAt(0) comparison for detecting numbers Negative numbers start with -, not a digit. If you check charAt(0) >= '0' && charAt(0) <= '9' to detect numbers, you will miss negatives. The safest approach is to check for C, D, and + explicitly using equals, and fall through to the else for everything else (which covers both positive and negative numbers).
Calling st.peek() or st.pop() without checking empty The problem guarantees valid operations — C always has something to remove, + always has two previous scores, D always has one. But in real code and defensive interview solutions, adding empty checks shows good habits even when the constraints guarantee safety.
FAQs — People Also Ask
Q1. Why is Stack a good choice for LeetCode 682 Baseball Game? Because all four operations only access the most recently added scores — the last score for C and D, the last two for +. This "most recent first" access pattern is exactly what LIFO (Last In First Out) provides. Stack's push, pop, and peek all run in O(1) making it perfectly efficient.
Q2. What is the time complexity of LeetCode 682? O(n) time where n is the number of operations. Each operation performs a constant number of stack operations (at most 3 pushes/pops for the + case). Space complexity is O(n) for storing scores.
Q3. Why does the + operation need to pop and push back in the Stack approach? Stack only gives direct access to the top element. To get the second most recent score, you must pop the first one, peek/pop the second, then push the first one back. The ArrayList approach avoids this by using index-based access directly.
Q4. What is the difference between Stack and ArrayDeque in Java for this problem? Both work correctly. ArrayDeque is faster because Stack is a legacy class that extends Vector and is synchronized (thread-safe), adding unnecessary overhead for single-threaded use. ArrayDeque has no synchronization overhead. For LeetCode and interviews, either is acceptable but ArrayDeque is technically better.
Q5. Is LeetCode 682 asked in coding interviews? It appears occasionally as a warmup or screening problem. Its main value is testing whether you can carefully simulate rules without making logical errors — a skill that matters in systems programming, game development, and any domain with complex state management.
Similar LeetCode Problems to Practice Next
- 71. Simplify Path — Medium — stack simulation with path operations
- 1047. Remove All Adjacent Duplicates In String — Easy — stack simulation
- 735. Asteroid Collision — Medium — stack simulation with conditions
- 150. Evaluate Reverse Polish Notation — Medium — stack with arithmetic operations, very similar pattern
- 227. Basic Calculator II — Medium — stack with operator precedence
Conclusion
LeetCode 682 Baseball Game is a perfect problem to build confidence with stack simulation. The four operations are clearly defined, the rules are unambiguous, and the stack maps naturally to every operation. Once you understand why pop-push-back is needed for + in the stack approach and how ArrayList simplifies that with index access, you have genuinely understood the tradeoffs between these data structures.
If you are newer to stacks, start with the ArrayList solution for clarity. Once that clicks, rewrite it with Stack to understand the LIFO mechanics. Then try ArrayDeque to understand why it is preferred in modern Java code.




