You are keeping score for a baseball game with an unusual set of operations. You start with an empty record, then process a list of operations one by one. Each operation is either an integer (add it to the record), "+" (sum of the last two scores), "D" (double the last score), or "C" (remove the last score). At the end, return the sum of all scores on the record.
A stack is perfect here because operations only affect the most recent scores. Pushing integers, peeking for "D", popping for "C", and peeking the top two for "+" are all natural stack operations. There is no need to track indices or manage the full list manually.
For example, given ["5", "2", "C", "D", "+"]: add 5, add 2, remove 2 (record is [5]), double 5 to 10 (record is [5,10]), sum last two 5+10=15 (record is [5,10,15]). Total is 30.
Example Input & Output
Add 1 then remove it. Empty record, total 0.
Example with negative and multiple operations.
5, 2, C removes 2, D doubles 5, + sums 5+10=15. Total 5+10+15=30.
Algorithm Flow

Solution Approach
Iterate through each operation. If it's an integer, parse it and push onto the stack. If it's "C", pop the top. If it's "D", peek the top, double it, and push. If it's "+", peek the top two, sum them, and push. At the end, sum all values on the stack.
Time complexity is O(n). Space complexity is O(n) for the stack.
Best Answers
import java.util.*;
class Solution {
public int solution(String[] ops) {
Stack<Integer> stack = new Stack<>();
for (String op : ops) {
if (op.equals("C")) stack.pop();
else if (op.equals("D")) stack.push(stack.peek() * 2);
else if (op.equals("+")) {
int top = stack.pop();
int sum = stack.peek() + top;
stack.push(top);
stack.push(sum);
} else stack.push(Integer.parseInt(op));
}
int sum = 0;
for (int v : stack) sum += v;
return sum;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
