Baseball Game — LeetCode 682 Python Solution

EasyStackArraySimulation
Problem
#682
Pattern
Stack
Reading time
3 min

The 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.

Example

Input
ops = ["5","2","C","D","+"]
Output
30
Explanation
"5" - Add 5 to the record, record is now [5].

Python solution

Python
class Solution:
    def calPoints(self, operations: List[str]) -> int:
        stk = []
        for op in operations:
            if op == "+":
                stk.append(stk[-1] + stk[-2])
            elif op == "D":
                stk.append(stk[-1] << 1)
            elif op == "C":
                stk.pop()
            else:
                stk.append(int(op))
        return sum(stk)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 682. Baseball Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 682. Baseball Game?
LeetCode 682. Baseball Game is rated Easy on LeetCode.
What is the time complexity of LeetCode 682. Baseball Game?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 682. Baseball Game?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 682. Baseball Game cover?
LeetCode 682. Baseball Game is tagged Stack, Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview