Last Updated: March 29, 2026
We are simulating a scoring system where we process a sequence of operations one by one. Some operations add a numeric score, some compute a new score based on previous ones, and one operation removes the most recent score. At the end, we return the total of all remaining scores.
The key observation here is that we always need access to the most recent score (for "D" and "C") and the two most recent scores (for "+"). This "last in, first out" access pattern is a textbook fit for a stack. Every operation either pushes a value onto the stack or pops one off.
1 <= operations.length <= 1000 → With n up to 1000, even an O(n^2) approach would be fine. But this problem naturally solves in O(n) with a single pass.Every operation revolves around the most recent elements. A number gets added on top. "D" needs the most recent score. "+" needs the two most recent scores. "C" removes the most recent score. That is a stack. We push scores on, pop them off for "C", and peek at the top for "D" and "+". There is no need for random access into the middle of our record, so a stack is the perfect fit.
This is one of those problems where picking the right data structure makes everything fall into place. Once you see "most recent" and "remove most recent," the stack choice is almost automatic.
The stack perfectly mirrors the problem's scoring record. Every time we add a score, it goes on top. Every time we invalidate ("C"), we remove from the top. The "D" and "+" operations only ever look at the top one or two elements. The stack preserves the order of scores and gives us O(1) access to exactly the elements we need.
Since we are already at O(n) time and O(n) space, there is no asymptotic improvement possible. But we can implement the same logic using a plain array and a pointer instead of a stack class.
Since we know the maximum number of operations is 1000, we can simulate this using a plain array and an index pointer. Instead of push/pop, we just move an index forward or backward. This avoids any overhead from dynamic resizing or stack class methods.
The idea is identical to Approach 1. We are just using a fixed-size array and a top pointer instead of a stack object. Incrementing top is a push, decrementing it is a pop, and record[top] is a peek.
top starting at -1 (empty record).top by 1 (logically removes the last score).top, set arr[top] = 2 * arr[top - 1].top, set arr[top] = arr[top - 1] + arr[top - 2].top, set arr[top] = parsed number.top and return.