#682

Baseball Game

Easy
ArrayStackSimulationStackArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to efficiently manage the scores. This allows us to handle operations in constant time, making the entire process faster and more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty stack to store scores.
  2. 2Step 2: Iterate through each operation in the input list.
  3. 3Step 3: For each operation, update the stack based on the operation type (integer, '+', 'D', or 'C').
  4. 4Step 4: At the end, sum all the scores in the stack and return the total.
solution.py14 lines
1# Full working Python code
2
3def calPoints(ops):
4    stack = []
5    for op in ops:
6        if op == 'C':
7            stack.pop()
8        elif op == 'D':
9            stack.append(2 * stack[-1])
10        elif op == '+':
11            stack.append(stack[-1] + stack[-2])
12        else:
13            stack.append(int(op))
14    return sum(stack)

Complexity note: The time complexity is O(n) because we process each operation exactly once. The space complexity is O(n) due to the stack storing scores.

  • 1Using a stack allows efficient management of scores.
  • 2Operations can be handled in constant time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.