Implement Stack using Arrays
EasyAn array plus a top index
Problem
Implement a stack (push, pop, top, isEmpty) using a fixed-size array and a top index.
A pile of plates: add and remove only from the top.
The idea
Keep an index pointing just past the last element: push writes there and increments, pop decrements and reads. Every operation touches one slot, so all of them are O(1).
The trick
- top == -1 (or 0, depending on convention) means empty — check before popping.
- A fixed array can overflow; doubling the capacity gives amortised O(1) growth.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
1
2
0
1
Step 1 of 2. Here's the example — push 1,2; pop Values: 1, 2.
1/2
Optimal
timeO(1)spaceO(n)
1top=-12push(x): arr[++top]=x3pop(): return arr[top--]4top(): return arr[top]Input
- array
- [1, 2]
Output
- answer
- —
Check yourself
2 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- push 1,2; pop
- Output:
- returns 2
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.