Fundamentals · Easy · Free
Implement stack push/pop using an array. What is overflow?
FresherFundamentalsData Structures & Algorithms
Stack with array
LIFO structure—push increments top, pop decrements. Fixed array risks overflow when top == capacity-1.
java
class ArrayStack {
int[] a; int top = -1;
void push(int x) {
if (top + 1 == a.length) throw new IllegalStateException("overflow");
a[++top] = x;
}
int pop() { if (top < 0) throw new IllegalStateException("empty"); return a[top--]; }
}Use
ArrayDeque in Java interviews unless asked to implement.