Code Logo

Baseball Score Tracker

Published at23 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
["1", "C"]
Output
0
Explanation

Add 1 then remove it. Empty record, total 0.

Example 2
Input
["5", "-2", "4", "C", "D", "9", "+", "+"]
Output
27
Explanation

Example with negative and multiple operations.

Example 3
Input
["5", "2", "C", "D", "+"]
Output
30
Explanation

5, 2, C removes 2, D doubles 5, + sums 5+10=15. Total 5+10+15=30.

Algorithm Flow

Recommendation Algorithm Flow for Baseball Score Tracker
Recommendation Algorithm Flow for Baseball Score Tracker

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.

function solution(ops) {
  var stack = []
  for (var i = 0; i < ops.length; i++) {
    var op = ops[i]
    if (op === 'C') stack.pop()
    else if (op === 'D') stack.push(stack[stack.length - 1] * 2)
    else if (op === '+') stack.push(stack[stack.length - 1] + stack[stack.length - 2])
    else stack.push(Number(op))
  }
  var sum = 0
  for (var i = 0; i < stack.length; i++) sum += stack[i]
  return sum
}

Time complexity is O(n). Space complexity is O(n) for the stack.

Best Answers

java
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;
    }
}