Skip to main content

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.

L1

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: push adds to the top, pop removes the top, peek/top reads without removing.
  • java.util.Stack extends Vector — synchronized, old, and an awkward List. New code should use Deque (ArrayDeque).
  • The Deque stack API: push / pop / peek (or addFirst / 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

TypeThread-safe?Nulls?Use as stack?
java.util.StackYes (Vector)YesLegacy only
ArrayDequeNoNo nullPreferred
LinkedListNoYesWorks; slower
VectorYesYesNot 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”, Deque st = new ArrayDeque<>(); is the modern answer — mention why.
L2

Advanced — Stack

Complexity and pitfalls

  • ArrayDeque push/pop are amortized O(1). It grows like an array (circular buffer).
  • Stack.empty() vs isEmpty() — Deque uses isEmpty(). Stack.search is 1-based from the top — rarely useful.
  • pop/removeFirst on empty ArrayDeque throws NoSuchElementException. pollFirst returns null — that is why null elements are banned.
  • Do not use Stack.get(i) just because Stack is a List. That is not stack thinking.
L3

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.

L4

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("{[(])}"));
    }
}
L5

Problem Solving Tricks

  • Type the variable as Deque so you do not reach for Vector methods.
  • For min-stack / next-greater, store pairs or a second stack.
  • DFS on a graph: explicit ArrayDeque beats deep recursion on large graphs in Java.
  • peek does not remove — off-by-one bugs often call pop too early.
L6

Practice Programs List

  1. Evaluate a postfix expression (2 3 + 4 *).
  2. Next greater element to the right for an int[].
  3. Rewrite balanced parentheses using java.util.Stack and then ArrayDeque — same tests.
  4. Simulate browser back-button with two stacks (back / forward).
  5. Implement a stack with getMin() in O(1) using an auxiliary stack.