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.
Every operation works on the most recent end of the record: "D" and "C" need the last score, and "+" needs the last two. This last-in, first-out access pattern is what a stack provides. Every operation either pushes a value onto the stack or pops one off.
1 <= operations.length <= 1000 → Small input, so performance is not a concern. A single pass over the operations runs in O(n).A stack matches each operation directly. A number is a push. "D" is a peek followed by a push of double that value. "+" is a look at the top two elements followed by a push of their sum. "C" is a pop. No operation ever reads or modifies the middle of the record, so push, pop, and peek (all O(1)) cover everything, and the stack contents at the end are the valid scores to sum.
Tracing ops = ["5", "-2", "4", "C", "D", "9", "+", "+"] (Example 2). The expected output is 27.
The stack can also be implemented as a fixed-size array of length n plus an index pointer, where incrementing the pointer is a push and decrementing it is a pop. The operations and complexity are identical, so that variant is an implementation detail rather than a different algorithm.