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. A stack is a Last-In, First-Out (LIFO) collection: the last item you put in is the first one you take out. Learn push, pop, peek, java.util.Stack vs ArrayDeque, the call stack, building your own stack, expression evaluation, monotonic stacks, and min stack — all with real-life examples.

What is a stack?

  • A stack is a linear collection where items are added and removed from only one end, called the top.
  • It follows LIFO — Last In, First Out. The item added last is the first one removed.
  • Three core operations: push (add on top), pop (remove from top), and peek (look at the top without removing).
  • In Java, use Deque<E> stack = new ArrayDeque<>(); for a stack. The older java.util.Stack class still works but is legacy.
  • Real life: a stack of plates in a wedding buffet. New plates go on top, and guests always take the top plate.
import java.util.ArrayDeque;
import java.util.Deque;

public class PlateStack {
    public static void main(String[] args) {
        Deque<String> plates = new ArrayDeque<>();
        plates.push("Plate 1");                              // bottom
        plates.push("Plate 2");
        plates.push("Plate 3");                              // top

        System.out.println("Top plate: " + plates.peek());   // Plate 3
        System.out.println("Taken: " + plates.pop());        // Plate 3
        System.out.println("Taken: " + plates.pop());        // Plate 2
        System.out.println("Plates left: " + plates.size()); // 1
        System.out.println("Empty? " + plates.isEmpty());    // false
    }
}

Stack operations

OperationWhat it doesArrayDeque methodStack methodOn an empty stack
pushAdds an item on toppush(e)push(e)Works normally
popRemoves and returns the top itempop()pop()NoSuchElementException / EmptyStackException
peekReturns the top item without removing itpeek()peek()Returns null / EmptyStackException
safe popRemoves the top, or returns null if emptypoll()Not availableReturns null
isEmptyTrue if there are no itemsisEmpty()empty() or isEmpty()Returns true
sizeNumber of itemssize()size()Returns 0
search1-based position from the topNot availablesearch(o)Returns -1
import java.util.ArrayDeque;
import java.util.Deque;

public class StackOperations {
    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();
        System.out.println("1. empty?   " + stack.isEmpty());                    // true
        stack.push(10);
        System.out.println("2. push 10: " + stack);                              // [10]
        stack.push(20);
        System.out.println("3. push 20: " + stack);                              // [20, 10]
        stack.push(30);
        System.out.println("4. push 30: " + stack);                              // [30, 20, 10]  (top first)
        System.out.println("5. peek:    " + stack.peek() + " -> " + stack);      // 30 -> [30, 20, 10]
        System.out.println("6. pop:     " + stack.pop() + " -> " + stack);       // 30 -> [20, 10]
    }
}

Java stack operations — push, peek, and pop step by step

A stack works only at its top. push drops an item on top, peek looks at the top item without touching it, and pop lifts the top item out. Like a stack of plates, the last plate placed is the first plate taken — LIFO: Last In, First Out.

Java stack operations in six steps using a glass jar: 1 empty stack; 2 push(10) puts 10 at the bottom; 3 push(20) puts 20 on top of 10; 4 push(30) puts 30 on top; 5 peek() highlights 30 and it stays in the stack; 6 pop() lifts 30 out of the jar, leaving 20 and 10. A side card compares push and pop to adding and taking plates from a stack, and a footer notes that push, pop, and peek all take O(1) time.
Java stack operations — follow the numbered cards from an empty stack through three pushes, a peek, and a pop
  • push(e): adds e on top — the stack grows by one.
  • peek(): returns the top item (30) and leaves the stack unchanged.
  • pop(): removes and returns the top item (30) — 20 becomes the new top.
  • isEmpty(): check it before pop or peek to avoid exceptions.

Real-life examples of stack

Real-life scenariopush meanspop means
Plates in a buffetWash and place a plate on topGuest takes the top plate
Browser back buttonOpen a new pageGo back to the previous page
Undo (Ctrl+Z) in an editorEvery change is savedUndo the latest change first
Bangles on a wristWear one more bangleRemove the last one worn
Pile of exam papersStudent submits a paper on topTeacher checks the top paper first
Car boot loadingLoad a bag inUnload the bag loaded last
Tiffin carrier boxesStack one more boxOpen the top box first
Train in a dead-end sidingCoach enters the sidingLast coach in leaves first
Method calls in a programA method is calledThe method returns
Chips in a tube canChips are packed inYou eat the top chip first

Ways to create a stack in Java

OptionCodeNotes
ArrayDeque (recommended)Deque<E> s = new ArrayDeque<>();Fast, resizable array, no nulls
ArrayDeque with capacitynew ArrayDeque<>(100)Starts with room for about 100 items
java.util.Stack (legacy)Stack<E> s = new Stack<>();Extends Vector, synchronized, slower
LinkedListDeque<E> s = new LinkedList<>();Works, allows null, more memory per item
Your own classArray or linked nodesCommon in interviews and data structure courses
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class CreateStacks {
    public static void main(String[] args) {
        Deque<String> a = new ArrayDeque<>();        // recommended
        Deque<String> b = new ArrayDeque<>(100);     // initial room for about 100 items
        Stack<String> c = new Stack<>();             // legacy, synchronized
        Deque<String> d = new LinkedList<>();        // works, allows null

        a.push("A");
        b.push("B");
        c.push("C");
        d.push("D");
        System.out.println(a.peek() + " " + b.peek() + " " + c.peek() + " " + d.peek());   // A B C D
    }
}

Using java.util.Stack (legacy class)

  • java.util.Stack has existed since Java 1.0. It extends Vector, so every method is synchronized and it also inherits list methods like get(i) and add(i, e).
  • Those inherited methods let you insert in the middle, which breaks the LIFO idea. Its iteration and toString go from bottom to top.
  • You will still see it in old code, textbooks, and interview questions, so know its methods.
  • Real life: a pile of textbooks on a study desk.
MethodReturnsExample result
push(e)The item pushedbooks.push("Maths") returns "Maths"
pop()Top item (removed)Throws EmptyStackException if empty
peek()Top item (not removed)Throws EmptyStackException if empty
empty()true if no itemsSame as isEmpty()
search(o)Position from the top (top = 1), or -1Rarely needed in real code
import java.util.Stack;

public class BookPile {
    public static void main(String[] args) {
        Stack<String> books = new Stack<>();
        books.push("Maths");
        books.push("Physics");
        books.push("Chemistry");                                      // top

        System.out.println(books);                                    // [Maths, Physics, Chemistry] (bottom to top)
        System.out.println("Top: " + books.peek());                   // Chemistry
        System.out.println("Physics at: " + books.search("Physics")); // 2 (counted from the top)
        System.out.println("Biology at: " + books.search("Biology")); // -1
        System.out.println("Took: " + books.pop());                   // Chemistry
        System.out.println("Empty? " + books.empty());                // false

        books.add(0, "Notes");                    // allowed (Vector method) but breaks LIFO thinking
        System.out.println(books);                // [Notes, Maths, Physics]
    }
}

Using ArrayDeque as a stack

  • ArrayDeque is the recommended stack in modern Java: it is faster than Stack, has no synchronization overhead, and offers only end operations.
  • Declare the variable as Deque<E>. Its push, pop, and peek all work on the front (head) of the deque, which acts as the top.
  • ArrayDeque does not allow null elements, because peek and poll return null to mean "empty".
  • Real life: the undo history of a text editor — every change is pushed, and Ctrl+Z pops the latest one.
Stack ideaDeque methodSame asIf empty
Push on toppush(e)addFirst(e)Works
Pop from toppop()removeFirst()Throws NoSuchElementException
Safe poppoll()pollFirst()Returns null
Look at toppeek()peekFirst()Returns null
Look at top (strict)element()getFirst()Throws NoSuchElementException
import java.util.ArrayDeque;
import java.util.Deque;

public class EditorUndo {
    public static void main(String[] args) {
        Deque<String> history = new ArrayDeque<>();
        String text = "";

        for (String typed : new String[] { "Hello", " World", "!" }) {
            history.push(text);                  // save the state before the change
            text = text + typed;
            System.out.println("Typed: " + text);
        }
        // Typed: Hello / Typed: Hello World / Typed: Hello World!

        text = history.pop();                    // Ctrl+Z
        System.out.println("Undo:  " + text);    // Hello World
        text = history.pop();                    // Ctrl+Z again
        System.out.println("Undo:  " + text);    // Hello
        System.out.println("Undo steps left: " + history.size());   // 1
    }
}

Handling an empty stack safely

  • Popping an empty stack is the most common stack bug. ArrayDeque.pop() throws NoSuchElementException; Stack.pop() and Stack.peek() throw EmptyStackException.
  • ArrayDeque.peek() and poll() return null instead of throwing — handy, but remember to check for null.
  • The safest habit: check isEmpty() before pop() or peek().
  • Real life: a cafeteria tray dispenser — before taking a tray, you glance to see if any are left.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
import java.util.Stack;

public class EmptyStackSafety {
    public static void main(String[] args) {
        Deque<String> trays = new ArrayDeque<>();
        System.out.println(trays.peek());            // null: no exception
        System.out.println(trays.poll());            // null: safe pop
        try {
            trays.pop();
        } catch (NoSuchElementException e) {
            System.out.println("ArrayDeque pop on empty: NoSuchElementException");
        }

        Stack<String> legacy = new Stack<>();
        try {
            legacy.peek();
        } catch (EmptyStackException e) {
            System.out.println("Stack peek on empty: EmptyStackException");
        }

        if (!trays.isEmpty()) {                      // best habit: check first
            trays.pop();
        }
        // trays.push(null);                         // NullPointerException: ArrayDeque bans null
    }
}

Iterating a stack

  • Interview trap: ArrayDeque and Stack print the same pushes in opposite orders.
  • Real life: a teacher collecting exam papers in a pile. Reading from the top gives the last submitted paper first.
Typefor-each / toString orderHow to go the other way
ArrayDeque used as a stackTop to bottomdescendingIterator() for bottom to top
java.util.StackBottom to top (Vector order)Loop indexes from size() - 1 down to 0
Any stackPop until emptyTop to bottom, but empties the stack
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.Stack;

public class IterateStacks {
    public static void main(String[] args) {
        Deque<String> deque = new ArrayDeque<>();
        Stack<String> stack = new Stack<>();
        for (String paper : new String[] { "Paper A", "Paper B", "Paper C" }) {
            deque.push(paper);
            stack.push(paper);
        }

        System.out.println("ArrayDeque: " + deque);    // [Paper C, Paper B, Paper A]  top first
        System.out.println("Stack:      " + stack);    // [Paper A, Paper B, Paper C]  bottom first

        System.out.print("Bottom to top: ");
        Iterator<String> it = deque.descendingIterator();
        while (it.hasNext()) System.out.print(it.next() + "  ");      // Paper A  Paper B  Paper C
        System.out.println();

        System.out.print("Checking order: ");
        while (!deque.isEmpty()) System.out.print(deque.pop() + "  ");  // Paper C  Paper B  Paper A
        System.out.println();
    }
}

Reversing with a stack

  • Push every item, then pop them all — they come out in reverse order. This is the simplest use of a stack.
  • The same idea checks palindromes: compare the original order with the popped (reversed) order.
  • Real life: train coaches entering a dead-end siding come out in reverse order — the guard van leaves first.
import java.util.ArrayDeque;
import java.util.Deque;

public class ReverseWithStack {
    static String reverse(String s) {
        Deque<Character> st = new ArrayDeque<>();
        for (char c : s.toCharArray()) st.push(c);
        StringBuilder sb = new StringBuilder();
        while (!st.isEmpty()) sb.append(st.pop());
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverse("JAVA"));                       // AVAJ

        String[] coaches = { "Engine", "S1", "S2", "S3", "Guard" };
        Deque<String> siding = new ArrayDeque<>();
        for (String c : coaches) siding.push(c);                   // coaches enter the siding
        StringBuilder out = new StringBuilder();
        while (!siding.isEmpty()) out.append(siding.pop()).append(" ");
        System.out.println("Leaving order: " + out.toString().trim());   // Guard S3 S2 S1 Engine
    }
}

Browser back and forward with two stacks

  • A browser keeps two stacks: a back stack and a forward stack.
  • Visiting a page pushes the current page onto back and clears forward. Back moves the current page to forward; forward moves it back again.
  • The same two-stack pattern powers undo and redo in editors, Photoshop, and Google Docs.
import java.util.ArrayDeque;
import java.util.Deque;

public class BrowserHistory {
    private final Deque<String> back = new ArrayDeque<>();
    private final Deque<String> forward = new ArrayDeque<>();
    private String current = "home";

    void visit(String page) {
        back.push(current);
        current = page;
        forward.clear();                         // a new visit wipes forward history
    }

    void goBack() {
        if (back.isEmpty()) return;
        forward.push(current);
        current = back.pop();
    }

    void goForward() {
        if (forward.isEmpty()) return;
        back.push(current);
        current = forward.pop();
    }

    public static void main(String[] args) {
        BrowserHistory b = new BrowserHistory();
        b.visit("google");
        b.visit("youtube");
        b.visit("learncodeguru");

        b.goBack();
        System.out.println(b.current);           // youtube
        b.goBack();
        System.out.println(b.current);           // google
        b.goForward();
        System.out.println(b.current);           // youtube
        b.visit("github");                       // forward history cleared
        b.goForward();
        System.out.println(b.current);           // github (nothing to go forward to)
    }
}

Differences between Stack and ArrayDeque

Featurejava.util.StackArrayDeque
IntroducedJava 1.0 (legacy)Java 6
ParentExtends VectorImplements Deque
Thread-safeYes (synchronized methods)No
SpeedSlower (locking on every call)Faster
null elementsAllowedNot allowed
Iteration orderBottom to topTop to bottom
Extra methodsget(i), add(i, e) — can break LIFOOnly end operations
Empty popEmptyStackExceptionNoSuchElementException (or poll() returns null)
search()YesNo
RecommendedNo (old code only)Yes

Differences between stack and queue

FeatureStackQueue
OrderLIFO — Last In, First OutFIFO — First In, First Out
Ends usedOne end (top)Two ends (rear to add, front to remove)
Addpushoffer / add
Removepoppoll / remove
Lookpeek (top)peek (front)
Java choiceArrayDeque as DequeArrayDeque or LinkedList as Queue
Real lifeStack of platesTicket counter line
Typical usesUndo, back button, recursion, bracketsPrinting jobs, BFS, task scheduling
L2

Advanced — Stack

How the call stack works

  • Every thread in the JVM has its own call stack. Each method call pushes a stack frame holding its parameters, local variables, and return address.
  • When a method returns, its frame is popped and control goes back to the caller — strict LIFO.
  • Recursion without a base case keeps pushing frames until the stack is full and the JVM throws StackOverflowError. The stack size can be changed with -Xss (for example -Xss2m).
  • Real life: office approvals. The clerk asks the manager, the manager asks the director. The director answers first, then the manager, then the clerk.
StepCall stack (top on the left)What happens
1mainProgram starts
2factorial(3), mainmain calls factorial(3)
3factorial(2), factorial(3), main3 waits for factorial(2)
4factorial(1), factorial(2), factorial(3), mainBase case reached
5factorial(2), factorial(3), mainfactorial(1) returns 1 and is popped
6factorial(3), mainfactorial(2) returns 2
7mainfactorial(3) returns 6
public class CallStackDemo {
    static int factorial(int n) {
        System.out.println("push frame: factorial(" + n + ")");
        int result = (n <= 1) ? 1 : n * factorial(n - 1);
        System.out.println("pop frame:  factorial(" + n + ") = " + result);
        return result;
    }

    static int noBaseCase(int n) {
        return noBaseCase(n + 1);                 // never stops
    }

    public static void main(String[] args) {
        factorial(3);
        // push frame: factorial(3)
        // push frame: factorial(2)
        // push frame: factorial(1)
        // pop frame:  factorial(1) = 1
        // pop frame:  factorial(2) = 2
        // pop frame:  factorial(3) = 6

        try {
            noBaseCase(1);
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError: too many frames");
        }
    }
}

Build your own stack with an array

  • Keep an array and a size counter. The top is at index size - 1.
  • push: store at data[size] and increase size; double the array when it is full (amortized O(1)).
  • pop: decrease size, read the item, and set the slot to null so the garbage collector can reclaim it.
  • Real life: a tiffin carrier — boxes are stacked one above another and you open the top one first.
import java.util.Arrays;
import java.util.NoSuchElementException;

public class ArrayStack<T> {
    private Object[] data = new Object[4];
    private int size = 0;

    public void push(T item) {
        if (size == data.length) data = Arrays.copyOf(data, size * 2);   // grow when full
        data[size++] = item;
    }

    @SuppressWarnings("unchecked")
    public T pop() {
        if (size == 0) throw new NoSuchElementException("stack is empty");
        T item = (T) data[--size];
        data[size] = null;                        // avoid holding a stale reference
        return item;
    }

    @SuppressWarnings("unchecked")
    public T peek() {
        if (size == 0) throw new NoSuchElementException("stack is empty");
        return (T) data[size - 1];
    }

    public boolean isEmpty() { return size == 0; }
    public int size() { return size; }

    public static void main(String[] args) {
        ArrayStack<String> tiffin = new ArrayStack<>();
        for (String box : new String[] { "Rice", "Dal", "Curry", "Curd", "Sweet" }) tiffin.push(box);
        System.out.println("Top box: " + tiffin.peek());      // Sweet (array grew from 4 to 8)
        System.out.println("Open: " + tiffin.pop());           // Sweet
        System.out.println("Open: " + tiffin.pop());           // Curd
        System.out.println("Boxes left: " + tiffin.size());    // 3
    }
}

Build your own stack with a linked list

  • Each node stores a value and a link to the node below it. top points to the newest node.
  • push creates a node pointing to the old top; pop moves top to the next node. Both are O(1) with no resizing.
  • Real life: bangles on a wrist — each new bangle sits above the previous one, and you remove the last one worn first.
FeatureArray stackLinked list stack
push / popO(1) amortizedO(1) always
ResizingNeeded when fullNever
Memory per itemLow (one slot)Higher (node object + link)
Cache friendlinessGood (contiguous)Poor (scattered nodes)
Used byArrayDequeLinkedList, ConcurrentLinkedDeque
import java.util.NoSuchElementException;

public class LinkedStack<T> {
    private static class Node<T> {
        final T value;
        final Node<T> next;
        Node(T value, Node<T> next) {
            this.value = value;
            this.next = next;
        }
    }

    private Node<T> top;
    private int size;

    public void push(T value) {
        top = new Node<>(value, top);             // new node points to the old top
        size++;
    }

    public T pop() {
        if (top == null) throw new NoSuchElementException("stack is empty");
        T value = top.value;
        top = top.next;
        size--;
        return value;
    }

    public T peek() {
        if (top == null) throw new NoSuchElementException("stack is empty");
        return top.value;
    }

    public boolean isEmpty() { return top == null; }

    public static void main(String[] args) {
        LinkedStack<String> bangles = new LinkedStack<>();
        bangles.push("Red");
        bangles.push("Green");
        bangles.push("Gold");
        System.out.println("Remove first: " + bangles.pop());   // Gold
        System.out.println("Next: " + bangles.peek());          // Green
        System.out.println("Count: " + bangles.size);           // 2
    }
}

Evaluating postfix expressions

  • In postfix (Reverse Polish) notation the operator comes after its operands: 5 3 + 2 * means (5 + 3) × 2. No brackets are needed.
  • Rule: push numbers; on an operator, pop two numbers (right operand first), apply the operator, and push the result. The final item is the answer.
  • Real life: scientific calculators and compilers convert what you type into postfix and evaluate it with a stack.
TokenActionStack (bottom → top)
5Push 55
3Push 35, 3
+Pop 3 and 5, push 5 + 38
2Push 28, 2
*Pop 2 and 8, push 8 × 216
EndPop the answer16
import java.util.ArrayDeque;
import java.util.Deque;

public class PostfixCalculator {
    static int evaluate(String expr) {
        Deque<Integer> st = new ArrayDeque<>();
        for (String token : expr.trim().split(" +")) {
            switch (token) {
                case "+", "-", "*", "/" -> {
                    int b = st.pop();                     // right operand comes off first
                    int a = st.pop();
                    st.push(switch (token) {
                        case "+" -> a + b;
                        case "-" -> a - b;
                        case "*" -> a * b;
                        default -> a / b;
                    });
                }
                default -> st.push(Integer.parseInt(token));
            }
        }
        return st.pop();
    }

    public static void main(String[] args) {
        System.out.println(evaluate("5 3 + 2 *"));          // 16   (5 + 3) x 2
        System.out.println(evaluate("10 2 8 * + 3 -"));     // 23   10 + 2 x 8 - 3
        System.out.println(evaluate("20 4 /"));             // 5
    }
}

Infix to postfix conversion

  • Humans write infix (A + B * C); machines prefer postfix (A B C * +). A stack of operators performs the conversion.
  • Operands go straight to the output. An operator first pops operators of higher or equal precedence, then is pushed. ( is pushed; ) pops until the matching (.
  • Real life: a billing calculator that must respect "multiply before add" when you type 100 + 5 * 18.
OperatorPrecedenceNote
* /2 (higher)Applied first
+ -1 (lower)Applied after * and /
(0 on the stackWaits until ) arrives
import java.util.ArrayDeque;
import java.util.Deque;

public class InfixToPostfix {
    static int precedence(char op) {
        if (op == '*' || op == '/') return 2;
        if (op == '+' || op == '-') return 1;
        return 0;
    }

    static String convert(String infix) {
        StringBuilder out = new StringBuilder();
        Deque<Character> ops = new ArrayDeque<>();
        for (char c : infix.replace(" ", "").toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                out.append(c).append(' ');
            } else if (c == '(') {
                ops.push(c);
            } else if (c == ')') {
                while (ops.peek() != '(') out.append(ops.pop()).append(' ');
                ops.pop();                                    // discard the (
            } else {
                while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) {
                    out.append(ops.pop()).append(' ');
                }
                ops.push(c);
            }
        }
        while (!ops.isEmpty()) out.append(ops.pop()).append(' ');
        return out.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(convert("A + B * C"));           // A B C * +
        System.out.println(convert("(A + B) * C"));         // A B + C *
        System.out.println(convert("A * (B + C) - D"));     // A B C + * D -
    }
}

Monotonic stack: next greater element

  • A monotonic stack keeps its items in increasing or decreasing order. When a new item breaks the order, the popped items have found their answer.
  • It solves "next greater element", "next warmer day", "stock span", and "largest rectangle" in O(n) instead of O(n²).
  • Real life: a weather app showing how many days you must wait for a warmer day.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class NextWarmerDay {
    static int[] daysToWait(int[] temps) {
        int[] answer = new int[temps.length];
        Deque<Integer> st = new ArrayDeque<>();            // indexes of days still waiting
        for (int i = 0; i < temps.length; i++) {
            while (!st.isEmpty() && temps[i] > temps[st.peek()]) {
                int day = st.pop();
                answer[day] = i - day;                     // found a warmer day
            }
            st.push(i);
        }
        return answer;                                     // 0 = no warmer day ahead
    }

    public static void main(String[] args) {
        int[] temps = { 31, 33, 32, 30, 34, 29, 35 };
        System.out.println(Arrays.toString(daysToWait(temps)));   // [1, 3, 2, 1, 2, 1, 0]
    }
}

Min stack in O(1)

  • A min stack returns the smallest item in O(1) at any time, even after pops.
  • Keep a second stack of minimums: on each push, push min(x, current min); on each pop, pop both stacks.
  • Real life: a stock trading app that always shows the lowest price of the session, even after cancelling recent trades.
import java.util.ArrayDeque;
import java.util.Deque;

public class MinStack {
    private final Deque<Integer> values = new ArrayDeque<>();
    private final Deque<Integer> mins = new ArrayDeque<>();     // mins.peek() = current minimum

    void push(int x) {
        values.push(x);
        mins.push(mins.isEmpty() ? x : Math.min(x, mins.peek()));
    }

    int pop() {
        mins.pop();
        return values.pop();
    }

    int min() {
        return mins.peek();
    }

    public static void main(String[] args) {
        MinStack prices = new MinStack();
        prices.push(520);
        prices.push(498);
        prices.push(530);
        prices.push(476);
        System.out.println("Lowest so far: " + prices.min());   // 476
        prices.pop();                                           // cancel the 476 trade
        System.out.println("Lowest now: " + prices.min());      // 498
    }
}

Time complexity of stack operations

OperationArrayDequeStackLinkedListOwn array stack
pushO(1) amortizedO(1) amortized + lockO(1)O(1) amortized
popO(1)O(1) + lockO(1)O(1)
peekO(1)O(1) + lockO(1)O(1)
isEmpty / sizeO(1)O(1)O(1)O(1)
search / containsO(n)O(n)O(n)O(n)
Memory per itemLowLowHigh (node)Low

Thread-safe stacks

  • ArrayDeque is not thread-safe. If several threads push and pop the same stack, use a concurrent deque.
  • Real life: several waiters putting clean plates on the same counter stack while others take them.
OptionHow it is safeUse when
java.util.StackEvery method synchronizedOld code only
ConcurrentLinkedDequeLock-free, non-blockingHigh-traffic shared stack
LinkedBlockingDequeLocks; can block when empty or fullProducer-consumer with waiting
Collections.synchronizedCollectionSingle lock wrapperRarely; prefer the options above
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SharedPlateStack {
    public static void main(String[] args) throws InterruptedException {
        Deque<Integer> plates = new ConcurrentLinkedDeque<>();
        ExecutorService waiters = Executors.newFixedThreadPool(4);

        for (int w = 0; w < 4; w++) {
            waiters.submit(() -> {
                for (int i = 0; i < 1000; i++) plates.push(i);    // each waiter adds 1000 plates
            });
        }
        waiters.shutdown();
        waiters.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Plates on counter: " + plates.size());   // always 4000
    }
}

Stack best practices

PracticeWhy
Use Deque<E> s = new ArrayDeque<>();Faster than Stack and has a clean stack API
Check isEmpty() before pop() and peek()Avoids NoSuchElementException and EmptyStackException
Use peek to look, pop to takeCalling pop too early is a common off-by-one bug
Do not store null in ArrayDequeIt throws NullPointerException
Avoid Stack.get(i) and add(i, e)They break LIFO thinking
Remember iteration order differsArrayDeque is top first, Stack is bottom first
Prefer an explicit stack over deep recursionAvoids StackOverflowError on large inputs
Use ConcurrentLinkedDeque for threadsArrayDeque is not thread-safe
L3

Tricky Interview Points

Q1) What is a stack?

Answer A linear data structure that follows LIFO: the last item pushed is the first one popped. Insertion and removal happen only at the top.

Q2) What are the basic stack operations and their complexity?

Answer push adds to the top, pop removes the top, peek reads the top, and isEmpty checks for no items. All are O(1).

Q3) What is the difference between pop and peek?

Answer pop removes and returns the top item. peek only returns it, leaving the stack unchanged.

Q4) Why is java.util.Stack not recommended?

Answer It extends Vector, so every method is synchronized (slow), and it inherits list methods like get and add(index) that break LIFO. The Java documentation recommends Deque with ArrayDeque instead.

Q5) How do you use ArrayDeque as a stack?

Answer Declare Deque<E> stack = new ArrayDeque<>(); then use push, pop, and peek. These work on the head of the deque, which acts as the top.

Q6) Why does ArrayDeque not allow null?

Answer Methods like peek and poll return null to signal an empty deque. Allowing null elements would make that ambiguous.

Q7) What exception is thrown when popping an empty stack?

Answer java.util.Stack throws EmptyStackException. ArrayDeque.pop throws NoSuchElementException. ArrayDeque.poll and peek return null instead.

Q8) What does Stack.search return?

Answer The 1-based position of the item counted from the top (top = 1), or -1 if the item is not present.

Q9) What is the difference between a stack and a queue?

Answer A stack is LIFO and works at one end. A queue is FIFO: items are added at the rear and removed from the front. A Deque can act as both.

Q10) What is the call stack?

Answer Each thread has a stack of frames. A method call pushes a frame with its parameters, locals, and return address; returning pops it. Recursion uses this call stack.

Q11) What causes StackOverflowError?

Answer Too many nested calls, usually recursion without a correct base case, fill the thread stack. Fix the base case, convert recursion to a loop with an explicit stack, or increase the stack size with -Xss.

Q12) Where are stacks used in real applications?

Answer Undo and redo, browser back and forward, bracket matching in editors and compilers, expression evaluation, method calls, depth-first search, and backtracking problems like maze solving.

Q13) How do you check balanced parentheses?

Answer Push every opening bracket. On a closing bracket, the stack must be non-empty and the popped bracket must match. At the end, the stack must be empty.

Q14) How do you implement a stack using an array?

Answer Keep an array and a size index. push stores at data[size++], pop returns data[--size] and clears the slot, and the array doubles when full, giving amortized O(1) push.

Q15) How do you implement a stack using a linked list?

Answer Keep a top node. push creates a new node whose next is the old top. pop returns top.value and moves top to top.next. Both are O(1).

Q16) How do you design a stack that returns the minimum in O(1)?

Answer Use a second stack of minimums. On push, push min(x, current min) onto it; on pop, pop both. The top of the min stack is always the current minimum.

Q17) How do you evaluate a postfix expression?

Answer Scan tokens left to right. Push numbers. On an operator, pop the right operand then the left, apply the operator, and push the result. The last remaining item is the answer.

Q18) What is a monotonic stack?

Answer A stack kept in increasing or decreasing order. It solves next greater element, stock span, and daily temperatures in O(n), because each index is pushed and popped at most once.

Q19) How do you implement a queue using two stacks?

Answer Push into an in-stack. To dequeue, if the out-stack is empty, pop everything from the in-stack into the out-stack, then pop from the out-stack. Each item moves at most twice, so operations are amortized O(1).

Q20) Do ArrayDeque and Stack iterate in the same order?

Answer No. ArrayDeque used as a stack iterates from top to bottom. java.util.Stack iterates from bottom to top because it follows Vector index order.

L4

Simple Programs

Bracket checker for a code editor

import java.util.ArrayDeque;
import java.util.Deque;

public class BracketChecker {
    static String check(String code) {
        Deque<Integer> st = new ArrayDeque<>();          // positions of open brackets
        String open = "([{";
        String close = ")]}";
        for (int i = 0; i < code.length(); i++) {
            char c = code.charAt(i);
            if (open.indexOf(c) >= 0) {
                st.push(i);
            } else if (close.indexOf(c) >= 0) {
                if (st.isEmpty()) return "Unexpected " + c + " at position " + i;
                char last = code.charAt(st.pop());
                if (open.indexOf(last) != close.indexOf(c)) {
                    return "Mismatch: " + last + " closed by " + c + " at position " + i;
                }
            }
        }
        return st.isEmpty() ? "Balanced" : "Unclosed " + code.charAt(st.peek()) + " at position " + st.peek();
    }

    public static void main(String[] args) {
        System.out.println(check("if (a[0] > 0) { print(a); }"));   // Balanced
        System.out.println(check("list.get(i];"));                  // Mismatch: ( closed by ] at position 10
        System.out.println(check("while (x) { y++;"));              // Unclosed { at position 10
        System.out.println(check("sum(a, b));"));                   // Unexpected ) at position 9
    }
}

Undo and redo in a text editor

import java.util.ArrayDeque;
import java.util.Deque;

public class UndoRedoEditor {
    private final StringBuilder text = new StringBuilder();
    private final Deque<String> undo = new ArrayDeque<>();
    private final Deque<String> redo = new ArrayDeque<>();

    void type(String s) {
        undo.push(text.toString());
        redo.clear();                            // new typing wipes redo history
        text.append(s);
    }

    void undo() {
        if (undo.isEmpty()) return;
        redo.push(text.toString());
        text.setLength(0);
        text.append(undo.pop());
    }

    void redo() {
        if (redo.isEmpty()) return;
        undo.push(text.toString());
        text.setLength(0);
        text.append(redo.pop());
    }

    public static void main(String[] args) {
        UndoRedoEditor ed = new UndoRedoEditor();
        ed.type("Dear Sir,");
        ed.type(" Please find");
        ed.type(" the report.");
        System.out.println(ed.text);     // Dear Sir, Please find the report.
        ed.undo();
        System.out.println(ed.text);     // Dear Sir, Please find
        ed.undo();
        System.out.println(ed.text);     // Dear Sir,
        ed.redo();
        System.out.println(ed.text);     // Dear Sir, Please find
        ed.type(" attached.");
        ed.redo();                       // nothing to redo: typing cleared it
        System.out.println(ed.text);     // Dear Sir, Please find attached.
    }
}

HTML tag nesting validator

import java.util.ArrayDeque;
import java.util.Deque;

public class HtmlTagChecker {
    static boolean valid(String[] tags) {
        Deque<String> open = new ArrayDeque<>();
        for (String tag : tags) {
            if (tag.startsWith("</")) {
                String name = tag.substring(2, tag.length() - 1);
                if (open.isEmpty() || !open.pop().equals(name)) return false;
            } else {
                open.push(tag.substring(1, tag.length() - 1));
            }
        }
        return open.isEmpty();
    }

    public static void main(String[] args) {
        String[] page1 = { "<html>", "<body>", "<p>", "<b>", "</b>", "</p>", "</body>", "</html>" };
        String[] page2 = { "<div>", "<p>", "</div>", "</p>" };
        String[] page3 = { "<ul>", "<li>", "</li>" };
        System.out.println(valid(page1));   // true
        System.out.println(valid(page2));   // false: p must close before div
        System.out.println(valid(page3));   // false: ul never closed
    }
}

Stock span for a trading app

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class StockSpan {
    // span = number of consecutive days up to today with price <= today
    static int[] span(int[] prices) {
        int[] result = new int[prices.length];
        Deque<Integer> st = new ArrayDeque<>();          // indexes of higher earlier prices
        for (int i = 0; i < prices.length; i++) {
            while (!st.isEmpty() && prices[st.peek()] <= prices[i]) st.pop();
            result[i] = st.isEmpty() ? i + 1 : i - st.peek();
            st.push(i);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] prices = { 100, 80, 60, 70, 60, 75, 85 };
        System.out.println(Arrays.toString(span(prices)));   // [1, 1, 1, 2, 1, 4, 6]
    }
}

Palindrome checker for names and number plates

import java.util.ArrayDeque;
import java.util.Deque;

public class PalindromeCheck {
    static boolean isPalindrome(String s) {
        String clean = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        Deque<Character> st = new ArrayDeque<>();
        for (char c : clean.toCharArray()) st.push(c);
        for (char c : clean.toCharArray()) {
            if (c != st.pop()) return false;        // popped order is the reverse
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Malayalam"));            // true
        System.out.println(isPalindrome("Never odd or even"));    // true
        System.out.println(isPalindrome("TS 09 90 ST"));          // true
        System.out.println(isPalindrome("Java"));                 // false
    }
}

Decimal to binary converter

import java.util.ArrayDeque;
import java.util.Deque;

public class DecimalToBinary {
    static String toBinary(int n) {
        if (n == 0) return "0";
        Deque<Integer> st = new ArrayDeque<>();
        while (n > 0) {
            st.push(n % 2);                          // remainders come out in reverse
            n /= 2;
        }
        StringBuilder sb = new StringBuilder();
        while (!st.isEmpty()) sb.append(st.pop());
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(toBinary(13));     // 1101
        System.out.println(toBinary(6));      // 110
        System.out.println(toBinary(255));    // 11111111
    }
}

Simplify a folder path like the cd command

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

public class SimplifyPath {
    static String simplify(String path) {
        Deque<String> st = new ArrayDeque<>();
        for (String part : path.split("/")) {
            if (part.isEmpty() || part.equals(".")) continue;     // stay in the same folder
            if (part.equals("..")) {
                if (!st.isEmpty()) st.pop();                      // go up one folder
            } else {
                st.push(part);                                    // go into a folder
            }
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = st.descendingIterator();            // bottom to top
        while (it.hasNext()) sb.append("/").append(it.next());
        return sb.length() == 0 ? "/" : sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(simplify("/home/ravi/../docs/./java/"));   // /home/docs/java
        System.out.println(simplify("/a/b/../../c"));                 // /c
        System.out.println(simplify("/../"));                         // /
    }
}
L5

Problem Solving Tricks

  • LIFO = Last In, First Out. Picture a stack of plates.
  • Modern Java stack: Deque<E> stack = new ArrayDeque<>(); — mention why Stack is legacy.
  • peek looks, pop takes. Do not call pop just to read the top.
  • Always check isEmpty() before pop or peek, or use poll and handle null.
  • Need to reverse something? Push everything, then pop everything.
  • Matching pairs (brackets, HTML tags) = push on open, pop and compare on close.
  • Undo/redo and back/forward = two stacks; any new action clears the second stack.
  • "Next greater", "stock span", "daily temperatures" = monotonic stack, O(n).
  • Deep recursion risk? Replace it with an explicit ArrayDeque loop.
  • ArrayDeque prints top first; java.util.Stack prints bottom first.
L6

Practice Programs List

  1. Simulate a stack of plates: push 5 plates, peek, pop 2, and print the size.
  2. Write the same program with java.util.Stack and with ArrayDeque, and compare the printed order.
  3. Reverse a string and a sentence word-by-word using a stack.
  4. Check whether brackets in a line of code are balanced, reporting the error position.
  5. Build browser back and forward with two stacks.
  6. Build undo and redo for a simple text editor.
  7. Evaluate a postfix expression such as 6 2 / 3 4 * +.
  8. Convert A * (B + C) / D to postfix using an operator stack.
  9. Find the next greater element for every item in an int[] using a monotonic stack.
  10. Implement a min stack that returns the minimum in O(1).
  11. Implement your own generic stack using an array that doubles when full.
  12. Implement a stack using a linked list of nodes.
  13. Implement a queue using two stacks.
  14. Trigger a StackOverflowError with recursion, then rewrite the method with an explicit stack.