Replay a Score Log With Undo and Combine Commands

Implement replayScoreLog

Given a list of string commands ops, replay them in order to build a log of scores and return the sum of every score remaining in the log once all commands have run. Each command is either a signed integer (record that score), "+" (record the sum of the two most recent scores), "X2" (record double the most recent score), or "UNDO" (erase the most recently recorded score). Every command here only ever touches the most recent end of the log — new scores go on top, and undo removes from the top — which is exactly what a stackStackA LIFO (Last In, First Out) structure — the natural fit whenever an operation only ever needs to read or remove the most recently added item. is built for. The only question is how to track the running total efficiently: re-deriving it from the whole log after every command works, but wastes effort re-reading scores that didn't change; updating it by exactly the one value that was just added or removed keeps every command O(1).

Example 1:

Input: ops = ["4","3","UNDO","X2","+"]

Output: 24

Example 2:

Input: ops = ["10","X2","+"]

Output: 60

Example 3:

Input: ops = ["-2","-3","+"]

Output: -10

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ ops.length ≤ 12
  • Each entry in ops is a signed integer string, or one of the commands "+", "X2", "UNDO"
  • "+" is only ever given when at least 2 prior scores exist in the log; "X2" and "UNDO" only when at least 1 does
  • -100 ≤ any integer score or computed value ≤ 200

ops =

["4", "3", "UNDO", "X2", "+"]