Implement a Stack Using a Resizable Array
Implement stackOpsArray
Implement a LIFO stackLIFOLast In, First Out — the most recently pushed element is always the first one popped. backed by a plain array, supporting
push(v), pop(), top(), isEmpty(), and size(). To make this testable with a single function call, this version takes a fixed sequence of operations (each with an argument, ignored when the operation doesn't need one) and replays them in order, returning the result of every pop, top, isEmpty, and size call as an array (push has no return value in a real stack API).
An array-backed stack is simple: push and pop both touch only the last occupied slot. The interesting part is what happens when the array runs out of room. Growing it by a fixed amount (say, one slot) every time keeps the logic simple but means nearly every push pays for a full copy of everything already stored — O(n²) total work across n pushes. Doubling the capacity instead trades a little extra unused memory for a dramatic speedup: resizes become exponentially rarer, so the total copying work across n pushes drops to O(n), making every push O(1) on average — this "spread the occasional expensive operation across many cheap ones" trick is called amortized analysisAmortized AnalysisMeasures the average cost per operation across a whole sequence, rather than the worst case for any single operation. A resize is expensive, but doubling makes resizes rare enough that their cost, spread across all the cheap pushes in between, averages out to O(1) per push..
Example 1:
Input: ops = ["push","push","push","pop","pop","top"], args = [5,10,15,0,0,0]
Output: [15,10,5]
Example 2:
Input: ops = ["isEmpty","push","isEmpty","pop","isEmpty"], args = [0,7,0,0,0]
Output: [1,0,7,1]
Example 3:
Input: ops = ["push","push","size","pop","size"], args = [1,2,0,0,0]
Output: [2,2,1]
+ 6 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of operations ≤ 12 - ●
Each operation is one of push, pop, top, isEmpty, or size - ●
0 ≤ pushed value ≤ 1000 - ●
pop and top return -1 when the stack is empty - ●
This version replays a fixed sequence of operations and reports the result of every pop, top, isEmpty, and size call, in order (push has no return value)
ops =
["push", "push", "push", "pop", "pop", "top"]
args =
[5, 10, 15, 0, 0, 0]