Baseball Game - Problem

You're the scorekeeper for a baseball game with unusual scoring rules! ๐ŸฅŽ

Starting with an empty record, you'll process a list of operations where each operation can be:

  • Integer x: Record a new score of x
  • '+': Record a new score equal to the sum of the previous two scores
  • 'D': Record a new score that is double the previous score
  • 'C': Cancel the previous score (remove it from the record)

Goal: Return the sum of all scores remaining in the record after applying all operations.

Example: Given operations ["5", "2", "C", "D", "+"]
โ€ข Start: []
โ€ข "5": [5]
โ€ข "2": [5, 2]
โ€ข "C": [5] (cancel 2)
โ€ข "D": [5, 10] (double 5)
โ€ข "+": [5, 10, 15] (5+10)
โ€ข Sum: 30

Input & Output

example_1.py โ€” Standard Operations
$ Input: ["5", "2", "C", "D", "+"]
โ€บ Output: 30
๐Ÿ’ก Note: Start with []. Add 5: [5]. Add 2: [5,2]. Cancel: [5]. Double: [5,10]. Sum last two: [5,10,15]. Total: 5+10+15=30
example_2.py โ€” Multiple Operations
$ Input: ["5", "-2", "4", "C", "D", "9", "+", "+"]
โ€บ Output: 27
๐Ÿ’ก Note: [5] โ†’ [5,-2] โ†’ [5,-2,4] โ†’ [5,-2] โ†’ [5,-2,-4] โ†’ [5,-2,-4,9] โ†’ [5,-2,-4,9,5] โ†’ [5,-2,-4,9,5,14]. Sum: 27
example_3.py โ€” Single Score
$ Input: ["1"]
โ€บ Output: 1
๐Ÿ’ก Note: Only one score recorded. The sum is simply 1.

Visualization

Tap to expand
๐ŸฅŽ Baseball Game Stack VisualizationOperations: ["5", "2", "C", "D", "+"]Score Stack5Push 552Push 252CCancel52DDouble510+Sum51015Final ResultSum = 5 + 10 + 15= 30
Understanding the Visualization
1
Initialize Empty Stack
Start with an empty stack to hold score cards
2
Process Each Operation
For numbers: add new card. For 'C': remove top card. For 'D': peek at top, add doubled card. For '+': peek at top two, add sum card
3
Calculate Final Sum
Add up all remaining score cards in the stack
Key Takeaway
๐ŸŽฏ Key Insight: Stack operations perfectly match this problem's requirements - we only need to access the most recent scores, making it a natural fit for LIFO (Last In, First Out) operations.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through operations array, each operation takes O(1) time

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Stack stores at most n scores in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค operations.length โ‰ค 1000
  • -3 ร— 104 โ‰ค x โ‰ค 3 ร— 104 for integer operations
  • All operations are guaranteed to be valid
  • At most 1000 calls to each operation type
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 15
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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