↓Skip to main content
  1. LeetCode/

LeetCode 682: Baseball Game

·1 min· ·
LeetCode Easy Array Stack Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-30

  • Submissions: Accepted (first try)

Approach
#

Each operation involves only the latest scores (Stack Template 2): push numbers; C pops; D pushes 2 * st[-1]; + pushes st[-1] + st[-2]. Sum the stack at the end.

My Solution
#

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

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Scores can be negative; convert with int(op) rather than testing isdigit.

Interview Explanation
#

Each operation touches only recent scores, so a stack of valid scores handles C by popping, D by pushing a double and + by pushing the sum of the last two; the answer is the stack’s sum. Time O(n).

Related

LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)
LeetCode 495: Teemo Attacking
·2 mins
LeetCode Easy Array Simulation
LeetCode 495 note: each attack contributes min(gap to the next attack, duration), and the last one contributes the full duration
LeetCode 657: Robot Return to Origin
·1 min
LeetCode Easy String Simulation
LeetCode 657 note: returning to the origin means as many U as D and as many L as R
LeetCode 594: Longest Harmonious Subsequence
·1 min
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 note: subsequences need not be contiguous, so just count; for each x add the counts of x and x + 1
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 506: Relative Ranks
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 note: sort indices by score descending, give medals to the top three and rank strings to the rest, writing back into the original positions