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
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
โ Linear Growth
Space Complexity
O(n)
Stack stores at most n scores in worst case
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code