Implement a stack (last-in, first-out) backed by an array, supporting two operations:
push(x) — add x to the top of the stack.pop() — remove and return the top element; if the stack is empty, return -1.You'll be given a sequence of operations; the first names the class (its constructor). Each pop reports its result; push and the constructor report nothing.
top index; push writes at top and increments, pop reads and decrements. You handle overflow yourself.Input: push(5), push(10), pop(), pop(), pop() Output: 10, 5, -1 Two pushes, then three pops return 10, 5, and -1 (empty).
Input: push(7), pop() Output: 7 Push 7, then pop returns 7.
- 1 <= number of operations <= 100 - 1 <= x <= 10^5 - pop() returns -1 if the stack is empty.
A stack is the simplest container with a discipline: last in, first out. Backed by a dynamic array, both operations are trivially O(1) — push appends to the end (the "top"), and pop removes from the end.
“Which end is the top?”
The end of the array — appends and removals both happen there for O(1).
“What does pop return on an empty stack?”
-1, by this problem's convention, rather than erroring.
I'll keep a dynamic array and treat its last element as the top of the stack.
Push appends; pop removes and returns the last element.
If the array is empty, pop returns -1 instead of failing.
Worked example — operations push 5, push 10, pop, pop, pop
push 5 -> arr = [5] (null) push 10 -> arr = [5, 10] (null) pop -> arr = [5] returns 10 pop -> arr = [] returns 5 pop -> arr = [] empty returns -1
Appending and removing at the end of a dynamic array are both amortized O(1), which is exactly what a stack's push and pop need.
Popping an empty stack has no element to return, so this problem defines it to return -1 — check the size before removing.
Key takeaway
A stack is a dynamic array where you only ever touch the end: push appends, pop removes-and-returns the last element (or -1 when empty). Every operation is O(1).
push(x): arr.append(x) pop(): return -1 if arr is empty else arr.pop()