Java Collections
Stack
Complete lesson for Stack using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Stack
Section: Java Collections. LIFO stacks: java.util.Stack vs ArrayDeque, and classic stack interview problems.
LIFO
- A stack is Last-In, First-Out:
pushadds to the top,popremoves the top,peek/topreads without removing. java.util.StackextendsVector— synchronized, old, and an awkwardList. New code should useDeque(ArrayDeque).- The
Dequestack API:push/pop/peek(oraddFirst/removeFirst/peekFirst).
import java.util.ArrayDeque;
import java.util.Deque;
public class StackBasics {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek()); // 3
System.out.println(stack.pop()); // 3
System.out.println(stack); // [2, 1] (ArrayDeque toString is not a promise)
}
} Stack vs Deque vs Vector
| Type | Thread-safe? | Nulls? | Use as stack? |
|---|---|---|---|
java.util.Stack | Yes (Vector) | Yes | Legacy only |
ArrayDeque | No | No null | Preferred |
LinkedList | No | Yes | Works; slower |
Vector | Yes | Yes | Not a stack API |
When interviews want a stack
- Matching brackets, undo, DFS, next-greater-element, evaluating postfix, call-stack simulation.
- If they say “use Stack”,
Dequeis the modern answer — mention why.st = new ArrayDeque<>();
Advanced — Stack
Complexity and pitfalls
ArrayDequepush/pop are amortized O(1). It grows like an array (circular buffer).Stack.empty()vsisEmpty()—DequeusesisEmpty().Stack.searchis 1-based from the top — rarely useful.pop/removeFirston emptyArrayDequethrowsNoSuchElementException.pollFirstreturnsnull— that is whynullelements are banned.- Do not use
Stack.get(i)just becauseStackis aList. That is not stack thinking.
Tricky Interview Points
Q1) Why is java.util.Stack discouraged?
Answer It extends Vector (synchronized, leftover List methods). The Deque interface plus ArrayDeque is the documented replacement.
Q2) push / pop / peek complexity on ArrayDeque?
Answer Amortized O(1) at the ends.
Q3) Can ArrayDeque store null?
Answer No. poll returns null to mean empty, so null elements are forbidden.
Q4) Stack vs Queue?
Answer Stack is LIFO. Queue is FIFO (offer at tail, poll at head). Deque can do both.
Q5) How do you implement two stacks in one array?
Answer Grow from both ends toward the middle — a classic extra question. In Java interviews, prefer Deque unless they ask you to implement from scratch.
Q6) Is Stack synchronized?
Answer java.util.Stack is. ArrayDeque is not. Synchronization of Stack is rarely the reason you wanted a stack.
Simple Programs
Balanced parentheses
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
public class Balanced {
static boolean balanced(String s) {
Map<Character, Character> closeToOpen = Map.of(')', '(', ']', '[', '}', '{');
Deque<Character> st = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (closeToOpen.containsValue(c)) {
st.push(c);
} else if (closeToOpen.containsKey(c)) {
if (st.isEmpty() || st.pop() != closeToOpen.get(c)) return false;
}
}
return st.isEmpty();
}
public static void main(String[] args) {
System.out.println(balanced("{[()]}"));
System.out.println(balanced("{[(])}"));
}
} Problem Solving Tricks
- Type the variable as
Dequeso you do not reach forVectormethods. - For min-stack / next-greater, store pairs or a second stack.
- DFS on a graph: explicit
ArrayDequebeats deep recursion on large graphs in Java. peekdoes not remove — off-by-one bugs often callpoptoo early.
Practice Programs List
- Evaluate a postfix expression (
2 3 + 4 *). - Next greater element to the right for an
int[]. - Rewrite balanced parentheses using
java.util.Stackand thenArrayDeque— same tests. - Simulate browser back-button with two stacks (back / forward).
- Implement a stack with
getMin()in O(1) using an auxiliary stack.