Baseball Game

Keep a score record that operations add to, double, combine and cancel, then add up what is left.

A game is scored with a few unusual rules. The record of scores starts empty, and each string in the array operations changes it in one of four ways:

Return the sum of all scores on the record after the last operation. Every operation is valid, so "+" always has two scores to add, and "D" and "C" always have one to work on.

Example 1
Input: operations = ["5", "2", "C", "D", "+"]
Output: 30
Explanation: the record ends as [5, 10, 15].
Example 2
Input: operations = ["5", "-2", "4", "C", "D", "9", "+", "+"]
Output: 27
Explanation: the record ends as [5, -2, -4, 9, 5, 14].
Solution

The Idea

Think of a scorekeeper with a notepad. Each new score goes on a new line at the bottom of the list. When a score is cancelled, the scorekeeper crosses out the last line. When a rule needs "the previous score", the scorekeeper looks at the last line that is not crossed out.

Follow Example 1 on that notepad. "5" and "2" write 5 and then 2. "C" crosses out the 2. Now "D" asks for double the previous score. Which score is that? Not the 2, which is gone, but the 5 written before it, so "D" writes 10. Then "+" adds the last two scores, 10 and 5, and writes 15. The record is 5, 10, 15, and the answer is 30.

Notice where all the work happens. Every rule writes at the end of the list, crosses out at the end, or reads one or two scores from the end. Nothing ever touches the middle. And when the last score is crossed out, the one before it becomes "the previous score" again.

A pile of plates works the same way: you put a plate on top and take a plate from the top. In programming such a pile is called a stack. Putting a value on top is a push, taking the top value off is a pop, and reading the top value without taking it off is a peek. Look at the picture below.

The record after each operation of Example 1, newest score on top. "5" pushes 5, "2" pushes 2, "C" pops the 2, "D" pushes 2 × 5 = 10, and "+" pushes 10 + 5 = 15, so the record ends as 5, 10, 15.

Each column shows the record as a stack after one operation of Example 1, with the newest score on top. Under "C", the crossed-out 2 has been popped, and 5 is on top again. That is why the next column, "D", says "push 2 × 5". In the last column, "+" adds the top two scores, 10 and 5, and pushes 15.

So the record is a stack of scores. Each operation is one or two stack moves, and the answer is the sum of whatever is left on the stack at the end.

Solution Approach

Turning that idea into code means settling three things: which Java class holds the record, how "+" reaches the score below the top, and how to add up the record at the end.

The class that holds the record

Which Java class gives us a stack? ArrayDeque, from java.util, stores its values in an array that grows as needed. Through the Deque interface it has push, pop and peek, and each one takes a fixed number of steps however long the record is. Java also has an older Stack class, but its documentation recommends Deque instead.

With that, three of the operations are one move each. A number is pushed. "D" peeks at the top and pushes twice its value. "C" pops the top.

Reaching the score below the top

What about "+"? It needs the top two scores, but peek only shows the top one. So pop the top score and keep it in a variable. The score that was below it is now on top, and a peek reads it. Then push the popped score back, so the record is as it was, and push the sum on top of it.

Adding up the record

When does the total get computed? Only at the end. A running total would have to be corrected on every "C", by subtracting the score being removed. Adding up what is left after the last operation is simpler, and the order of the scores does not matter for a sum.

Java Solution

The method calPoints works in these steps:

  1. First, create the record as an empty stack, Deque<Integer> record = new ArrayDeque<>().
  2. Loop over operations, one string op at a time, and pick the case for it with a switch. The switch uses the arrow form, case "+" ->, from Java 14, so each case runs only its own code and needs no break.
  3. For "+", pop the top score into last, add the score now on top into sum, then push last back and push sum.
  4. For "D", push twice the top score. For "C", pop the top score. Any other string is a number: the default case turns it into an int with Integer.parseInt, which also reads a minus sign such as the one in "-2", and pushes it.
  5. After the loop, a second loop adds every score left in record into total, and the method returns total.

The main method runs both examples, a "C" that cancels a "+" score, a negative score that is doubled and added, and a record that ends empty.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class BaseballGame {

    public static int calPoints(String[] operations) {
        Deque<Integer> record = new ArrayDeque<>();
        for (String op : operations) {
            switch (op) {
                case "+" -> {
                    int last = record.pop();          // take the newest score off
                    int sum = last + record.peek();   // add the one now on top
                    record.push(last);                // put the newest score back
                    record.push(sum);
                }
                case "D" -> record.push(2 * record.peek());
                case "C" -> record.pop();
                default -> record.push(Integer.parseInt(op));
            }
        }
        int total = 0;
        for (int score : record) {
            total += score;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(calPoints(new String[] {"5", "2", "C", "D", "+"}));
        System.out.println(calPoints(new String[] {"5", "-2", "4", "C", "D", "9", "+", "+"}));
        System.out.println(calPoints(new String[] {"3", "4", "+", "C", "+"}));
        System.out.println(calPoints(new String[] {"-3", "D", "+"}));
        System.out.println(calPoints(new String[] {"1", "C"}));
    }
}

Running it prints:

Output
30
27
14
-18
0

The 30 and 27 at the top match the two examples. The 14 comes from ["3", "4", "+", "C", "+"]. The first "+" pushes 7 and "C" pops it, so the second "+" sees 4 and 3 on top again and pushes another 7: 3 + 4 + 7 = 14.

The -18 shows that negative scores need nothing special: -3 is doubled to -6, then "+" pushes -6 + -3 = -9, and -3 - 6 - 9 = -18. The last line, 0, is the record that "C" emptied: the second loop has no scores to add, so total stays 0.

The line record.push(last) in the "+" case is easy to leave out, because the popped score feels used up. Without it, Example 1 returns 20 instead of 30: the 10 disappears, and the record ends as just 5 and 15.

The original implementation, BaseballGame.java, is on GitHub.

Complexity

The work is one pass over the operations, then one pass over the scores left on the record.

  • Time: O(n) for n operations. Each operation does at most one pop, one peek and two pushes, each a fixed number of steps on an ArrayDeque, and the final loop visits at most n scores.
  • Space: O(n) for the record. Every number, "D" and "+" adds one score, so with no "C" at all the record holds n scores.

A stack that holds values for operators to combine is also how Evaluate Reverse Polish Notation works.