TARGET DECK: Leetcode FILE TAGS: Easy


Intuition

  • The trick here is: There is no trick.
  • It simply is the act of using a stack to keep track of all the rounds.
  • I tried to use O(1) space by keeping track of the sum on each round rather than using scratch space via a stack, but that didn’t work since:
    • It would require keeping track of which position you inserted in, adding complexity.
    • But also, you need a sum of all scores, and so you need the previous score as well.

Complexity

Runtime

Space

Code

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

Notes

Cards

START Basic Front: Baseball Game Back: Use a stack to keep track of each score.

END


References