Baseball Game - Problem

You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.

You are given a list of strings operations, where operations[i] is the i-th operation you must apply to the record and is one of the following:

  • An integer x - Record a new score of x
  • '+' - Record a new score that is the sum of the previous two scores
  • 'D' - Record a new score that is the double of the previous score
  • 'C' - Invalidate the previous score, removing it from the record

Return the sum of all the scores on the record after applying all the operations.

The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.

Input & Output

Example 1 — Mixed Operations
$ Input: operations = ["5","2","C","D","+"]
Output: 30
💡 Note: "5" → [5], "2" → [5,2], "C" → [5], "D" → [5,10], "+" → [5,10,15]. Sum = 5+10+15 = 30
Example 2 — Simple Numbers
$ Input: operations = ["5","-2","4","C","D","9","+","+"]
Output: 27
💡 Note: "5" → [5], "-2" → [5,-2], "4" → [5,-2,4], "C" → [5,-2], "D" → [5,-2,-4], "9" → [5,-2,-4,9], "+" → [5,-2,-4,9,5], "+" → [5,-2,-4,9,5,14]. Sum = 27
Example 3 — Only Numbers
$ Input: operations = ["1"]
Output: 1
💡 Note: Single operation adds 1 to record. Sum = 1

Constraints

  • 1 ≤ operations.length ≤ 1000
  • operations[i] is "C", "D", "+", or a string representing an integer in range [-3 × 104, 3 × 104]
  • For operation "+", there will always be at least two previous scores on the record
  • For operations "C" and "D", there will always be at least one previous score on the record

Visualization

Tap to expand
Baseball Game - Stack Solution INPUT operations array: "5" "2" "C" "D" "+" 0 1 2 3 4 Operations: x: Push score x +: Sum of last two D: Double last score C: Remove last score Use Stack for scores stack = [] ALGORITHM STEPS 1 "5" - Push 5 stack: [5] 2 "2" - Push 2 stack: [5, 2] 3 "C" - Remove last stack: [5] 4 "D" - Double 5 stack: [5, 10] 5 "+" - Sum 5+10 stack: [5, 10, 15] Final Stack State: 5 10 15 Sum: 5 + 10 + 15 = 30 bottom ----------> top FINAL RESULT All operations processed Score Record: 5 10 15 Calculation: sum(stack) = 5 + 10 + 15 = 30 Output: 30 OK - Answer Verified Key Insight: Use a stack to maintain the score record. Each operation either pushes a new score, modifies based on previous scores, or removes the last score. Stack enables O(1) access to recent scores needed for +, D, and C operations. Time: O(n), Space: O(n) TutorialsPoint - Baseball Game | Optimal Stack Solution
Asked in
Amazon 15 Google 8 Facebook 5
285.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen