Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 16 / Stage 4

Data structures and algorithms in Java

Goal: Reason about time/space complexity before writing a line of code, then work through the data structures and algorithms that come up in nearly every interview and nearly every real system — hashing, two pointers, stacks/queues, recursion, sorting, binary search, linked lists, trees, heaps, graphs and dynamic programming — implementing each one by hand before reaching for the library version. Three small, real builds are woven in along the way: an undo button, a trending-posts feed, and a delivery route planner. Time: ~25–30 hours across this one large part, plus ongoing daily practice

What you will learn

  • Big-O: measuring how work grows with input size, not with a stopwatch
  • Hashing: turning an O(n²) brute-force scan into an O(n) one with HashMap/HashSet
  • Two pointers and sliding window: one pass instead of a nested loop
  • Deque as a stack (LIFO) and as a queue (FIFO) — the modern replacement for Stack and most Queue casts
  • Recursion (base case + recursive case) and backtracking (choose, explore, un-choose) with pruning
  • Sorting by hand (bubble, insertion, merge, quicksort) and what Arrays.sort/Collections.sort actually run
  • Binary search by hand, then Arrays.binarySearch/Collections.binarySearch — and the one precondition that breaks everything if you skip it
  • Building a singly linked list by hand: nodes, head/tail pointers, reversal, cycle detection
  • Building a binary search tree by hand: insert, search, the four traversal orders, why a skewed tree degrades to O(n)
  • PriorityQueue as a heap: min-heap, max-heap, bounded top-k
  • Representing a graph with an adjacency list, and BFS vs. DFS
  • Dynamic programming: memoization (top-down) and tabulation (bottom-up), and where it beats plain backtracking

About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in ../../TOOLING.md. None of this part's algorithms depend on JDK internals, so the logic is portable to any Java version — only exact nanosecond/millisecond timings are tagged (varies), because they depend on the machine running them, not on Java.

How this part is organised

One examples/ subfolder per topic, plus the three real-world builds living next to the topic they demonstrate:

part-16-dsa-in-java/
├── README.md
├── examples/
│   ├── big-o/BigODemo.java
│   ├── hashing/HashingDemo.java
│   ├── two-pointers/TwoPointersDemo.java
│   ├── stacks-queues/DequeDemo.java, UndoButtonDemo.java          (real-world build 1)
│   ├── recursion-backtracking/RecursionBacktrackingDemo.java
│   ├── sorting/SortingDemo.java
│   ├── binary-search/BinarySearchDemo.java
│   ├── linked-lists/LinkedListDemo.java
│   ├── trees/TreeDemo.java
│   ├── heaps/HeapDemo.java, TrendingPostsDemo.java                (real-world build 2)
│   ├── graphs/GraphDemo.java, DeliveryRouteDemo.java               (real-world build 3)
│   └── dynamic-programming/DynamicProgrammingDemo.java
├── exercises.md
└── solutions/

Every example is a single-file, no-package program — compile and run it exactly like Stage 1 did, from inside its own folder: javac SomeDemo.java && java SomeDemo.

Topics in this part

Practice

Each exercise is its own file with a main method, exactly like the examples. Where timing is involved, the exercise prints a comparison (true/false) instead of a raw millisecond number, so your output can match exactly.


Exercise 1: Counting operations (Big-O)

Scenario: Before fixing a slow IRCTC seat-search, you want to prove the shape of the current code, not guess at it. What to do:

  1. Write linearScanSteps(int[] seats, int target) that counts how many array accesses it takes to find target with a plain loop (return -1 steps if not found, but still count every access attempted).
  2. Write countAllPairsSteps(int n) that counts how many pair-comparisons a nested loop over n elements performs (same shape as BigODemo.countPairComparisons).
  3. In main, call countAllPairsSteps for n = 500, 1000, 2000 and print each count plus the ratio to the previous one, formatted to 1 decimal place.
  4. Print whether the ratio from 1000 to 2000 is between 3.9 and 4.1.

Sample output:

n=500  -> 124750 comparisons
n=1000 -> 499500 comparisons (4.0x)
n=2000 -> 1999000 comparisons (4.0x)
ratio confirms O(n^2): true

Exercise 2: Two-sum with hashing

Scenario: A Swiggy cart has item prices; find two items whose prices add up exactly to a coupon value, without comparing every pair. What to do: Write twoSum(int[] prices, int target) using one HashMap<Integer, Integer> pass (price → index), returning the pair of indices or null. Call it on {249, 99, 149, 399, 599} with target 498, and print the indices and the two prices they point to. Then call it with a target that has no valid pair and print "no pair found".

Sample output:

indices: [1, 3] (99 + 399)
no pair found

Exercise 3: Sliding window maximum average

Scenario: A fitness app wants the best 7-day rolling average of daily step counts. What to do: Write bestWindowAverage(int[] dailySteps, int windowSize) using the fixed-size sliding-window technique (running sum, add new/drop oldest), returning the highest average as a double rounded to 1 decimal place. Run it on a 10-day array of your choosing with windowSize = 7 and print the result alongside the brute-force answer (recompute every window's sum from scratch) to prove they match.

Sample output:

steps: [4200, 6100, 3900, 8800, 5200, 7000, 6600, 4100, 9300, 5500]
sliding window best 7-day average: 6642.9
brute force best 7-day average:    6642.9
match: true

Exercise 4: Balanced brackets with a Deque

Scenario: A config-file linter needs to catch unbalanced brackets before a deploy, including brackets mixed with other characters. What to do: Write isBalanced(String text) using an ArrayDeque<Character> as a stack, ignoring every character that isn't (, ), [, ], { or }. Test it on "{ \"routes\": [ (1,2), (3,4) ] }" (balanced) and "{ \"routes\": [ (1,2), (3,4) }" (one ] missing), printing both results.

Sample output:

{ "routes": [ (1,2), (3,4) ] } -> balanced: true
{ "routes": [ (1,2), (3,4) } -> balanced: false

Exercise 5: A fixed-capacity undo history

Scenario: A drawing app's undo button should only remember the last 20 strokes — older ones are simply forgotten, to keep memory bounded. What to do: Write a class BoundedUndo<T> backed by an ArrayDeque<T> with a fixed capacity. record(T action) pushes an action; if the deque would exceed capacity, remove the oldest one first (from the opposite end push uses). undo() pops and returns the most recent action, or null if empty. In main, record 25 numbered "stroke-N" actions into a BoundedUndo<String> of capacity 20, then undo 3 times and print what comes back, plus the deque's final size.

Sample output:

undo 1: stroke-25
undo 2: stroke-24
undo 3: stroke-23
remaining history size: 17

Exercise 6: Backtracking with pruning — exam seat groups

Scenario: An exam hall needs every way to split n students into groups of exactly 3, where no two students who share the same roll-number prefix (first letter) can be in the same group — a simplified seating-conflict rule. What to do: Write validGroupings(List<String> rollNumbers) that backtracks through all ways to partition the list into groups of 3 (assume the list length is divisible by 3), pruning any partial group the moment it would contain two roll numbers with the same first letter. Return the list of valid groupings (each grouping is a List<List<String>>). Run it on List.of("A101", "B204", "A305", "C110", "B220", "C330") and print the count of valid groupings and the first one found.

Sample output:

roll numbers: [A101, B204, A305, C110, B220, C330]
valid groupings found: 4
first grouping: [[A101, B204, C110], [A305, B220, C330]]

💡 Hint: this is the same "choose, explore, un-choose" shape as RecursionBacktrackingDemo's subset pruning — prune as soon as a partial group of size < 3 already has a repeated first letter, not only once a group of 3 is complete.


Exercise 7: Merge sort vs. Arrays.sort, proven equal

Scenario: Before trusting a hand-written merge sort in a billing report, prove it agrees with the JDK's own sort on several inputs, including edge cases. What to do: Write mergeSort(int[] values) (by hand, as in SortingDemo). In main, test it against Arrays.sort on: an empty array, a single-element array, an already-sorted array, a reverse-sorted array, and an array with duplicate values. Print each case's input, your result, and whether it matches a cloned-and-Arrays.sort-ed reference.

Sample output:

[] -> [] matches: true
[7] -> [7] matches: true
[1, 2, 3, 4] -> [1, 2, 3, 4] matches: true
[9, 7, 5, 3, 1] -> [1, 3, 5, 7, 9] matches: true
[4, 1, 4, 2, 1] -> [1, 1, 2, 4, 4] matches: true

Exercise 8: Binary search for the insertion point

Scenario: A leaderboard needs to insert a new score into a sorted array of scores, keeping it sorted, without a full re-sort. What to do: Write insertionIndex(int[] sortedScores, int newScore) using binary search (adapt BinarySearchDemo.binarySearch: when the loop ends without finding an exact match, low is the correct insertion index). Then write insertSorted(int[] sortedScores, int newScore) that builds a new, larger array with newScore placed at that index. Test on {10, 25, 40, 40, 70} inserting 35, and separately inserting 40 (a duplicate — insert it adjacent to the existing ones, either side is fine, but say which side your code picks).

Sample output:

scores: [10, 25, 40, 40, 70]
insert 35 -> index 2 -> [10, 25, 35, 40, 40, 70]
insert 40 -> index 2 -> [10, 25, 40, 40, 40, 70] (inserted before the existing 40s)

Exercise 9: A doubly linked list for an LRU-ish history

Scenario: A browser's "recently visited" list needs fast add-to-front AND fast remove-from-anywhere (revisiting a page should move it to the front, not duplicate it). What to do: Extend the singly linked list idea to a doubly linked list: each Node has both prev and next. Implement moveToFront(T value) (remove the node holding value from wherever it is — O(1) once found, since you have prev directly, no scanning for a "previous" pointer like the singly linked version needed — then re-insert it at the head) and toList() returning the current order head to tail. Visit "home", "search", "product-42", "cart", then revisit "search", and print the list after every step.

Sample output:

visit home:        [home]
visit search:       [search, home]
visit product-42:   [product-42, search, home]
visit cart:          [cart, product-42, search, home]
revisit search:      [search, cart, product-42, home]

Exercise 10: Binary search tree with delete

Scenario: TreeDemo's BST never removes a node. An employee-ID lookup tree needs delete, including the three real cases: a leaf, a node with one child, and a node with two children. What to do: Add delete(int value) to a BST like TreeDemo's. For a two-children case, replace the node's value with its in-order successor (the smallest value in its right subtree), then delete that successor node from the right subtree instead. Build a tree from {50, 30, 70, 20, 40, 60, 80}, print the in-order traversal, delete 30 (two children), print again, delete 80 (leaf), print again, delete 70 (one child after 80 is gone), print a final time.

Sample output:

initial in-order:        [20, 30, 40, 50, 60, 70, 80]
after delete(30):         [20, 40, 50, 60, 70, 80]
after delete(80):         [20, 40, 50, 60, 70]
after delete(70):         [20, 40, 50, 60]

Exercise 11: Top-k frequent words with a bounded heap

Scenario: A customer-support dashboard needs the 3 most frequent words across a batch of complaint tickets, without sorting the entire vocabulary. What to do: Write topKFrequent(List<String> words, int k) that counts frequencies with a HashMap (hashing part), then keeps the top k with a correctly-bounded PriorityQueue (say out loud which kind, min or max, the way section 10 recommends) instead of sorting every distinct word. Break ties by alphabetical order. Run it on a list where "refund" appears 5 times, "delay" 3 times, "damaged" 3 times, and 4 other words appear once each, with k = 3.

Sample output:

top 3: [refund(5), damaged(3), delay(3)]

Exercise 12: BFS vs. Dijkstra on the same graph

Scenario: Prove, on one concrete graph, that BFS's "shortest path" and Dijkstra's "cheapest path" can disagree once edges have weights — the exact trap DeliveryRouteDemo's README section warns about. What to do: Build one weighted graph (reuse or adapt GraphDemo's adjacency list plus edge weights, or DeliveryRouteDemo's RoadNetwork) with at least 5 nodes, where the fewest-hops path between two chosen nodes is NOT the cheapest-weight path. Run plain BFS to get the fewest-hops path and Dijkstra to get the cheapest-weight path between the same two nodes, print both paths with their hop count and total weight, and print whether the two paths differ.

Sample output:

BFS path (fewest hops):      [Warehouse, Aundh] (1 hop, 20 min)
Dijkstra path (cheapest):    [Warehouse, Baner, Aundh] (2 hops, 15 min)
paths differ: true

Exercise 13: Topological sort for a build pipeline

Scenario: A CI pipeline has build steps that depend on other steps finishing first; running them in the wrong order breaks the build. Figure out a valid run order, or detect that one is impossible. What to do: Write topologicalOrder(Map<String, List<String>> dependsOn) (each key depends on everything in its list) using DFS with a visiting/visited marker (the same three-state idea GraphDemo.hasCycle uses for undirected cycle detection, adapted to a directed graph: a node currently "on the DFS path" that gets visited again means a cycle, i.e. an impossible build). Return a valid order if one exists, or throw an IllegalStateException with a message naming the cycle if not. Test it on a valid pipeline of 5 steps, then on the same pipeline with one extra dependency added that creates a cycle, catching and printing the exception's message.

Sample output:

valid order: [compile, lint, test, package, deploy]
Cycle detected involving: compile

Exercise 14: Longest increasing subsequence, memoization vs. tabulation

Scenario: A stock-watch tool wants the longest run of days (not necessarily consecutive) where the price strictly increased, to show "best growth streak" on a chart. What to do: Write longestIncreasingSubsequenceMemo(int[] prices) (top-down: recursion with a cache, trying "start a new subsequence here" against every later, larger price) and longestIncreasingSubsequenceTabulation(int[] prices) (bottom-up: table[i] = the longest increasing subsequence ending exactly at index i, filled left to right). Run both on {200, 450, 130, 780, 320, 900, 1100} and print both results plus whether they agree, and the actual subsequence (not just its length) from the tabulation version.

Sample output:

prices: [200, 450, 130, 780, 320, 900, 1100]
memoization length:  5
tabulation length:   5
same length: true
subsequence: [200, 450, 780, 900, 1100]
Show the solutions for Part 16 (14 files)

solutions/ex01.java

public class ex01 {

    static int linearScanSteps(int[] seats, int target) {
        int steps = 0;
        for (int seat : seats) {
            steps++;
            if (seat == target) {
                return steps;
            }
        }
        return -steps; // negative: not found, magnitude is still the step count
    }

    static long countAllPairsSteps(int n) {
        long steps = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                steps++;
            }
        }
        return steps;
    }

    public static void main(String[] args) {
        long n500 = countAllPairsSteps(500);
        long n1000 = countAllPairsSteps(1000);
        long n2000 = countAllPairsSteps(2000);

        System.out.println("n=500  -> " + n500 + " comparisons");
        System.out.println("n=1000 -> " + n1000 + " comparisons (" + String.format("%.1f", (double) n1000 / n500) + "x)");
        System.out.println("n=2000 -> " + n2000 + " comparisons (" + String.format("%.1f", (double) n2000 / n1000) + "x)");

        double ratio = (double) n2000 / n1000;
        System.out.println("ratio confirms O(n^2): " + (ratio >= 3.9 && ratio <= 4.1));
    }
}

solutions/ex02.java

import java.util.HashMap;
import java.util.Map;

public class ex02 {

    static int[] twoSum(int[] prices, int target) {
        Map<Integer, Integer> seenAt = new HashMap<>();
        for (int i = 0; i < prices.length; i++) {
            int complement = target - prices[i];
            if (seenAt.containsKey(complement)) {
                return new int[]{seenAt.get(complement), i};
            }
            seenAt.put(prices[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] prices = {249, 99, 149, 399, 599};

        int[] result = twoSum(prices, 498); // 99 + 399
        System.out.println("indices: " + java.util.Arrays.toString(result)
                + " (" + prices[result[0]] + " + " + prices[result[1]] + ")");

        int[] noPair = twoSum(prices, 10_000);
        System.out.println(noPair == null ? "no pair found" : java.util.Arrays.toString(noPair));
    }
}

solutions/ex03.java

public class ex03 {

    static double bestWindowAverage(int[] dailySteps, int windowSize) {
        int windowSum = 0;
        for (int i = 0; i < windowSize; i++) {
            windowSum += dailySteps[i];
        }
        int best = windowSum;
        for (int end = windowSize; end < dailySteps.length; end++) {
            windowSum += dailySteps[end] - dailySteps[end - windowSize];
            best = Math.max(best, windowSum);
        }
        return Math.round(best / (double) windowSize * 10) / 10.0;
    }

    static double bruteForceBestWindowAverage(int[] dailySteps, int windowSize) {
        int best = Integer.MIN_VALUE;
        for (int start = 0; start + windowSize <= dailySteps.length; start++) {
            int sum = 0;
            for (int i = start; i < start + windowSize; i++) {
                sum += dailySteps[i];
            }
            best = Math.max(best, sum);
        }
        return Math.round(best / (double) windowSize * 10) / 10.0;
    }

    public static void main(String[] args) {
        int[] steps = {4200, 6100, 3900, 8800, 5200, 7000, 6600, 4100, 9300, 5500};
        int windowSize = 7;

        System.out.println("steps: " + java.util.Arrays.toString(steps));
        double sliding = bestWindowAverage(steps, windowSize);
        double brute = bruteForceBestWindowAverage(steps, windowSize);
        System.out.println("sliding window best 7-day average: " + sliding);
        System.out.println("brute force best 7-day average:    " + brute);
        System.out.println("match: " + (sliding == brute));
    }
}

solutions/ex04.java

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

public class ex04 {

    static boolean isBalanced(String text) {
        Deque<Character> openBrackets = new ArrayDeque<>();
        for (char c : text.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                openBrackets.push(c);
            } else if (c == ')' || c == ']' || c == '}') {
                if (openBrackets.isEmpty()) {
                    return false;
                }
                char last = openBrackets.pop();
                boolean matches = (c == ')' && last == '(')
                        || (c == ']' && last == '[')
                        || (c == '}' && last == '{');
                if (!matches) {
                    return false;
                }
            }
            // every other character is ignored
        }
        return openBrackets.isEmpty();
    }

    public static void main(String[] args) {
        String balanced = "{ \"routes\": [ (1,2), (3,4) ] }";
        String broken = "{ \"routes\": [ (1,2), (3,4) }";

        System.out.println(balanced + " -> balanced: " + isBalanced(balanced));
        System.out.println(broken + " -> balanced: " + isBalanced(broken));
    }
}

solutions/ex05.java

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

public class ex05 {

    static final class BoundedUndo<T> {
        private final Deque<T> history = new ArrayDeque<>();
        private final int capacity;

        BoundedUndo(int capacity) {
            this.capacity = capacity;
        }

        void record(T action) {
            history.push(action);
            if (history.size() > capacity) {
                history.removeLast(); // drop the OLDEST, from the opposite end of push
            }
        }

        T undo() {
            return history.poll(); // null if empty; poll() reads from the same end push() writes to
        }

        int size() {
            return history.size();
        }
    }

    public static void main(String[] args) {
        BoundedUndo<String> history = new BoundedUndo<>(20);
        for (int i = 1; i <= 25; i++) {
            history.record("stroke-" + i);
        }

        for (int i = 1; i <= 3; i++) {
            System.out.println("undo " + i + ": " + history.undo());
        }
        System.out.println("remaining history size: " + history.size());
    }
}

solutions/ex06.java

import java.util.ArrayList;
import java.util.List;

public class ex06 {

    static List<List<List<String>>> validGroupings(List<String> rollNumbers) {
        List<List<List<String>>> results = new ArrayList<>();
        backtrack(rollNumbers, new boolean[rollNumbers.size()], new ArrayList<>(), -1,
                new ArrayList<>(), results);
        return results;
    }

    // lastIndex keeps every group's members in ASCENDING index order, and lets a new
    // group's first pick be any smallest-still-unused index -- both together mean each
    // distinct partition into groups is generated exactly once, not once per reordering.
    private static void backtrack(List<String> rollNumbers, boolean[] used,
                                    List<String> currentGroup, int lastIndex,
                                    List<List<String>> currentGrouping,
                                    List<List<List<String>>> results) {
        if (currentGrouping.size() * 3 == rollNumbers.size() && currentGroup.isEmpty()) {
            results.add(deepCopy(currentGrouping));
            return;
        }
        if (currentGroup.size() == 3) {
            currentGrouping.add(new ArrayList<>(currentGroup));
            backtrack(rollNumbers, used, new ArrayList<>(), -1, currentGrouping, results);
            currentGrouping.remove(currentGrouping.size() - 1);
            return;
        }
        // Starting a brand-new group must use the smallest still-unused index: combined
        // with the ascending-within-group rule above, every distinct partition into groups
        // is then generated exactly once, however many ways there were to reach it.
        if (currentGroup.isEmpty()) {
            int smallest = firstUnused(used);
            if (smallest == -1) {
                return;
            }
            if (conflictFree(currentGroup, rollNumbers.get(smallest))) {
                used[smallest] = true;
                currentGroup.add(rollNumbers.get(smallest));
                backtrack(rollNumbers, used, currentGroup, smallest, currentGrouping, results);
                currentGroup.remove(currentGroup.size() - 1);
                used[smallest] = false;
            }
            return;
        }
        for (int i = lastIndex + 1; i < rollNumbers.size(); i++) {
            if (used[i]) {
                continue;
            }
            String candidate = rollNumbers.get(i);
            boolean conflicts = currentGroup.stream()
                    .anyMatch(existing -> existing.charAt(0) == candidate.charAt(0));
            if (conflicts) {
                continue; // prune: same first-letter conflict inside this partial group
            }
            used[i] = true;
            currentGroup.add(candidate);
            backtrack(rollNumbers, used, currentGroup, i, currentGrouping, results);
            currentGroup.remove(currentGroup.size() - 1);
            used[i] = false;
        }
    }

    private static int firstUnused(boolean[] used) {
        for (int i = 0; i < used.length; i++) {
            if (!used[i]) {
                return i;
            }
        }
        return -1;
    }

    private static boolean conflictFree(List<String> currentGroup, String candidate) {
        return currentGroup.stream().noneMatch(existing -> existing.charAt(0) == candidate.charAt(0));
    }

    private static List<List<String>> deepCopy(List<List<String>> grouping) {
        List<List<String>> copy = new ArrayList<>();
        for (List<String> group : grouping) {
            copy.add(new ArrayList<>(group));
        }
        return copy;
    }

    public static void main(String[] args) {
        List<String> rollNumbers = List.of("A101", "B204", "A305", "C110", "B220", "C330");
        List<List<List<String>>> groupings = validGroupings(rollNumbers);

        System.out.println("roll numbers: " + rollNumbers);
        System.out.println("valid groupings found: " + groupings.size());
        System.out.println("first grouping: " + groupings.get(0));
    }
}

solutions/ex07.java

import java.util.Arrays;

public class ex07 {

    static int[] mergeSort(int[] values) {
        if (values.length <= 1) {
            return values;
        }
        int mid = values.length / 2;
        int[] left = mergeSort(Arrays.copyOfRange(values, 0, mid));
        int[] right = mergeSort(Arrays.copyOfRange(values, mid, values.length));
        return merge(left, right);
    }

    private static int[] merge(int[] left, int[] right) {
        int[] merged = new int[left.length + right.length];
        int i = 0, j = 0, k = 0;
        while (i < left.length && j < right.length) {
            merged[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];
        }
        while (i < left.length) {
            merged[k++] = left[i++];
        }
        while (j < right.length) {
            merged[k++] = right[j++];
        }
        return merged;
    }

    private static void check(int[] input) {
        int[] expected = input.clone();
        Arrays.sort(expected);
        int[] actual = mergeSort(input.clone());
        System.out.println(Arrays.toString(input) + " -> " + Arrays.toString(actual)
                + " matches: " + Arrays.equals(actual, expected));
    }

    public static void main(String[] args) {
        check(new int[]{});
        check(new int[]{7});
        check(new int[]{1, 2, 3, 4});
        check(new int[]{9, 7, 5, 3, 1});
        check(new int[]{4, 1, 4, 2, 1});
    }
}

solutions/ex08.java

import java.util.Arrays;

public class ex08 {

    static int insertionIndex(int[] sortedScores, int newScore) {
        int low = 0;
        int high = sortedScores.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (sortedScores[mid] == newScore) {
                return mid; // an exact match: insert here, before any existing duplicates
            } else if (sortedScores[mid] < newScore) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }

    static int[] insertSorted(int[] sortedScores, int newScore) {
        int index = insertionIndex(sortedScores, newScore);
        int[] result = new int[sortedScores.length + 1];
        System.arraycopy(sortedScores, 0, result, 0, index);
        result[index] = newScore;
        System.arraycopy(sortedScores, index, result, index + 1, sortedScores.length - index);
        return result;
    }

    public static void main(String[] args) {
        int[] scores = {10, 25, 40, 40, 70};
        System.out.println("scores: " + Arrays.toString(scores));

        int index35 = insertionIndex(scores, 35);
        System.out.println("insert 35 -> index " + index35 + " -> " + Arrays.toString(insertSorted(scores, 35)));

        int index40 = insertionIndex(scores, 40);
        System.out.println("insert 40 -> index " + index40 + " -> " + Arrays.toString(insertSorted(scores, 40))
                + " (inserted before the existing 40s)");
    }
}

solutions/ex09.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ex09 {

    static final class Node<T> {
        T value;
        Node<T> prev;
        Node<T> next;

        Node(T value) {
            this.value = value;
        }
    }

    static final class History<T> {
        private Node<T> head;
        private final Map<T, Node<T>> nodesByValue = new HashMap<>();

        void moveToFront(T value) {
            Node<T> existing = nodesByValue.get(value);
            if (existing != null) {
                unlink(existing);
            } else {
                existing = new Node<>(value);
                nodesByValue.put(value, existing);
            }
            existing.prev = null;
            existing.next = head;
            if (head != null) {
                head.prev = existing;
            }
            head = existing;
        }

        private void unlink(Node<T> node) {
            if (node.prev != null) {
                node.prev.next = node.next;
            } else {
                head = node.next;
            }
            if (node.next != null) {
                node.next.prev = node.prev;
            }
            node.prev = null;
            node.next = null;
        }

        List<T> toList() {
            List<T> result = new ArrayList<>();
            Node<T> current = head;
            while (current != null) {
                result.add(current.value);
                current = current.next;
            }
            return result;
        }
    }

    public static void main(String[] args) {
        History<String> history = new History<>();

        history.moveToFront("home");
        System.out.println("visit home:        " + history.toList());

        history.moveToFront("search");
        System.out.println("visit search:       " + history.toList());

        history.moveToFront("product-42");
        System.out.println("visit product-42:   " + history.toList());

        history.moveToFront("cart");
        System.out.println("visit cart:          " + history.toList());

        history.moveToFront("search");
        System.out.println("revisit search:      " + history.toList());
    }
}

solutions/ex10.java

import java.util.ArrayList;
import java.util.List;

public class ex10 {

    static final class Node {
        int value;
        Node left;
        Node right;

        Node(int value) {
            this.value = value;
        }
    }

    static final class BinarySearchTree {
        private Node root;

        void insert(int value) {
            root = insert(root, value);
        }

        private Node insert(Node node, int value) {
            if (node == null) {
                return new Node(value);
            }
            if (value < node.value) {
                node.left = insert(node.left, value);
            } else if (value > node.value) {
                node.right = insert(node.right, value);
            }
            return node;
        }

        void delete(int value) {
            root = delete(root, value);
        }

        private Node delete(Node node, int value) {
            if (node == null) {
                return null;
            }
            if (value < node.value) {
                node.left = delete(node.left, value);
            } else if (value > node.value) {
                node.right = delete(node.right, value);
            } else {
                // found the node to delete
                if (node.left == null && node.right == null) {
                    return null; // leaf: just remove it
                }
                if (node.left == null) {
                    return node.right; // one child: splice it into the parent's place
                }
                if (node.right == null) {
                    return node.left;
                }
                // two children: replace with the in-order successor (smallest of the right subtree)
                int successorValue = smallestValue(node.right);
                node.value = successorValue;
                node.right = delete(node.right, successorValue);
            }
            return node;
        }

        private int smallestValue(Node node) {
            while (node.left != null) {
                node = node.left;
            }
            return node.value;
        }

        List<Integer> inOrder() {
            List<Integer> result = new ArrayList<>();
            inOrder(root, result);
            return result;
        }

        private void inOrder(Node node, List<Integer> result) {
            if (node == null) {
                return;
            }
            inOrder(node.left, result);
            result.add(node.value);
            inOrder(node.right, result);
        }
    }

    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();
        for (int value : new int[]{50, 30, 70, 20, 40, 60, 80}) {
            tree.insert(value);
        }
        System.out.println("initial in-order:        " + tree.inOrder());

        tree.delete(30); // two children
        System.out.println("after delete(30):         " + tree.inOrder());

        tree.delete(80); // leaf
        System.out.println("after delete(80):         " + tree.inOrder());

        tree.delete(70); // one child, after 80 is gone
        System.out.println("after delete(70):         " + tree.inOrder());
    }
}

solutions/ex11.java

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

public class ex11 {

    record WordCount(String word, int count) {
    }

    static List<WordCount> topKFrequent(List<String> words, int k) {
        Map<String, Integer> frequency = new HashMap<>();
        for (String word : words) {
            frequency.merge(word, 1, Integer::sum);
        }

        // Keeping the k LARGEST counts: bound a MIN-heap, evicting the current smallest
        // once it grows past k. Ties broken by word so the heap orders smallest-count-
        // then-latest-alphabetically first, matching the eviction we actually want.
        Comparator<WordCount> byCountThenReverseAlpha = Comparator
                .comparingInt(WordCount::count)
                .thenComparing(Comparator.comparing(WordCount::word).reversed());
        PriorityQueue<WordCount> heap = new PriorityQueue<>(byCountThenReverseAlpha);

        for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
            heap.offer(new WordCount(entry.getKey(), entry.getValue()));
            if (heap.size() > k) {
                heap.poll();
            }
        }

        List<WordCount> result = new ArrayList<>(heap);
        result.sort(Comparator.comparingInt(WordCount::count).reversed()
                .thenComparing(WordCount::word));
        return result;
    }

    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        addWord(words, "refund", 5);
        addWord(words, "delay", 3);
        addWord(words, "damaged", 3);
        addWord(words, "slow", 1);
        addWord(words, "rude", 1);
        addWord(words, "wrong-item", 1);
        addWord(words, "late", 1);

        List<WordCount> top3 = topKFrequent(words, 3);
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < top3.size(); i++) {
            WordCount wc = top3.get(i);
            sb.append(wc.word()).append("(").append(wc.count()).append(")");
            if (i < top3.size() - 1) {
                sb.append(", ");
            }
        }
        sb.append("]");
        System.out.println("top 3: " + sb);
    }

    private static void addWord(List<String> words, String word, int count) {
        for (int i = 0; i < count; i++) {
            words.add(word);
        }
    }
}

solutions/ex12.java

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

public class ex12 {

    record Edge(String to, int weight) {
    }

    static final class WeightedGraph {
        private final Map<String, List<Edge>> adjacency = new HashMap<>();

        void addEdge(String from, String to, int weight) {
            adjacency.computeIfAbsent(from, k -> new ArrayList<>()).add(new Edge(to, weight));
            adjacency.computeIfAbsent(to, k -> new ArrayList<>()).add(new Edge(from, weight));
        }

        List<Edge> neighborsOf(String node) {
            return adjacency.getOrDefault(node, List.of());
        }
    }

    static List<String> bfsPath(WeightedGraph graph, String start, String end) {
        Map<String, String> cameFrom = new HashMap<>();
        Set<String> visited = new HashSet<>();
        Deque<String> queue = new ArrayDeque<>();
        queue.offer(start);
        visited.add(start);
        while (!queue.isEmpty()) {
            String node = queue.poll();
            if (node.equals(end)) {
                break;
            }
            for (Edge edge : graph.neighborsOf(node)) {
                if (visited.add(edge.to())) {
                    cameFrom.put(edge.to(), node);
                    queue.offer(edge.to());
                }
            }
        }
        return buildPath(cameFrom, start, end);
    }

    static List<String> dijkstraPath(WeightedGraph graph, String start, String end) {
        Map<String, Integer> best = new HashMap<>();
        Map<String, String> cameFrom = new HashMap<>();
        PriorityQueue<Edge> frontier = new PriorityQueue<>(Comparator.comparingInt(Edge::weight));
        best.put(start, 0);
        frontier.offer(new Edge(start, 0));
        while (!frontier.isEmpty()) {
            Edge current = frontier.poll();
            int knownCost = best.get(current.to());
            if (current.weight() > knownCost) {
                continue;
            }
            for (Edge edge : graph.neighborsOf(current.to())) {
                int candidate = knownCost + edge.weight();
                if (candidate < best.getOrDefault(edge.to(), Integer.MAX_VALUE)) {
                    best.put(edge.to(), candidate);
                    cameFrom.put(edge.to(), current.to());
                    frontier.offer(new Edge(edge.to(), candidate));
                }
            }
        }
        return buildPath(cameFrom, start, end);
    }

    private static List<String> buildPath(Map<String, String> cameFrom, String start, String end) {
        List<String> path = new ArrayList<>();
        String current = end;
        while (current != null) {
            path.add(current);
            if (current.equals(start)) {
                break;
            }
            current = cameFrom.get(current);
        }
        java.util.Collections.reverse(path);
        return path;
    }

    static int totalWeight(WeightedGraph graph, List<String> path) {
        int total = 0;
        for (int i = 0; i < path.size() - 1; i++) {
            String from = path.get(i);
            String to = path.get(i + 1);
            for (Edge edge : graph.neighborsOf(from)) {
                if (edge.to().equals(to)) {
                    total += edge.weight();
                    break;
                }
            }
        }
        return total;
    }

    public static void main(String[] args) {
        WeightedGraph roads = new WeightedGraph();
        roads.addEdge("Warehouse", "Aundh", 20);
        roads.addEdge("Warehouse", "Baner", 9);
        roads.addEdge("Baner", "Aundh", 6);
        roads.addEdge("Aundh", "Camp", 25);
        roads.addEdge("Warehouse", "Kothrud", 15);
        roads.addEdge("Kothrud", "Camp", 10);

        List<String> bfsResult = bfsPath(roads, "Warehouse", "Aundh");
        List<String> dijkstraResult = dijkstraPath(roads, "Warehouse", "Aundh");

        System.out.println("BFS path (fewest hops):      " + bfsResult
                + " (" + (bfsResult.size() - 1) + " hop" + ((bfsResult.size() - 1) == 1 ? "" : "s")
                + ", " + totalWeight(roads, bfsResult) + " min)");
        System.out.println("Dijkstra path (cheapest):    " + dijkstraResult
                + " (" + (dijkstraResult.size() - 1) + " hop" + ((dijkstraResult.size() - 1) == 1 ? "" : "s")
                + ", " + totalWeight(roads, dijkstraResult) + " min)");
        System.out.println("paths differ: " + !bfsResult.equals(dijkstraResult));
    }
}

solutions/ex13.java

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ex13 {

    enum State { UNVISITED, VISITING, VISITED }

    // dependsOn: key depends on everything in its list (must run AFTER them).
    static List<String> topologicalOrder(Map<String, List<String>> dependsOn) {
        Map<String, State> state = new LinkedHashMap<>();
        for (String node : dependsOn.keySet()) {
            state.put(node, State.UNVISITED);
        }
        List<String> order = new ArrayList<>();
        for (String node : dependsOn.keySet()) {
            if (state.get(node) == State.UNVISITED) {
                visit(node, dependsOn, state, order);
            }
        }
        return order;
    }

    private static void visit(String node, Map<String, List<String>> dependsOn,
                               Map<String, State> state, List<String> order) {
        state.put(node, State.VISITING);
        for (String dependency : dependsOn.getOrDefault(node, List.of())) {
            State depState = state.get(dependency);
            if (depState == State.VISITING) {
                throw new IllegalStateException("Cycle detected involving: " + dependency);
            }
            if (depState == State.UNVISITED) {
                visit(dependency, dependsOn, state, order);
            }
        }
        state.put(node, State.VISITED);
        order.add(node); // dependencies are already in 'order' by now: this node can finally run
    }

    public static void main(String[] args) {
        Map<String, List<String>> pipeline = new LinkedHashMap<>();
        pipeline.put("compile", List.of());
        pipeline.put("lint", List.of("compile"));
        pipeline.put("test", List.of("compile"));
        pipeline.put("package", List.of("lint", "test"));
        pipeline.put("deploy", List.of("package"));

        List<String> order = topologicalOrder(pipeline);
        System.out.println("valid order: " + order);

        Map<String, List<String>> broken = new LinkedHashMap<>(pipeline);
        broken.put("compile", List.of("test")); // compile now also depends on test -> cycle with test->compile
        try {
            topologicalOrder(broken);
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
    }
}

solutions/ex14.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ex14 {

    // Top-down / memoization: lisEndingAt(i) = longest increasing run ending exactly at index i.
    static int longestIncreasingSubsequenceMemo(int[] prices) {
        int[] memo = new int[prices.length];
        Arrays.fill(memo, -1);
        int best = 0;
        for (int i = 0; i < prices.length; i++) {
            best = Math.max(best, lisEndingAt(prices, i, memo));
        }
        return best;
    }

    private static int lisEndingAt(int[] prices, int i, int[] memo) {
        if (memo[i] != -1) {
            return memo[i];
        }
        int best = 1; // the element alone is a subsequence of length 1
        for (int j = 0; j < i; j++) {
            if (prices[j] < prices[i]) {
                best = Math.max(best, lisEndingAt(prices, j, memo) + 1);
            }
        }
        memo[i] = best;
        return best;
    }

    // Bottom-up / tabulation: fill table[i] left to right, no recursion.
    static int[] longestIncreasingSubsequenceTable(int[] prices) {
        int[] table = new int[prices.length];
        Arrays.fill(table, 1);
        for (int i = 1; i < prices.length; i++) {
            for (int j = 0; j < i; j++) {
                if (prices[j] < prices[i]) {
                    table[i] = Math.max(table[i], table[j] + 1);
                }
            }
        }
        return table;
    }

    static List<Integer> reconstruct(int[] prices, int[] table) {
        int bestIndex = 0;
        for (int i = 1; i < table.length; i++) {
            if (table[i] > table[bestIndex]) {
                bestIndex = i;
            }
        }
        List<Integer> sequence = new ArrayList<>();
        int currentLength = table[bestIndex];
        for (int i = bestIndex; i >= 0; i--) {
            if (prices[i] < prices[bestIndex] || i == bestIndex) {
                if (table[i] == currentLength) {
                    sequence.add(prices[i]);
                    bestIndex = i;
                    currentLength--;
                }
            }
        }
        java.util.Collections.reverse(sequence);
        return sequence;
    }

    public static void main(String[] args) {
        int[] prices = {200, 450, 130, 780, 320, 900, 1100};
        System.out.println("prices: " + Arrays.toString(prices));

        int memoLength = longestIncreasingSubsequenceMemo(prices);
        int[] table = longestIncreasingSubsequenceTable(prices);
        int tableLength = Arrays.stream(table).max().getAsInt();

        System.out.println("memoization length:  " + memoLength);
        System.out.println("tabulation length:   " + tableLength);
        System.out.println("same length: " + (memoLength == tableLength));
        System.out.println("subsequence: " + reconstruct(prices, table));
    }
}

Common mistakes

Mistake Why it is wrong Fix
Timing with a stopwatch instead of counting operations Timings depend on the machine and JVM warm-up, not the algorithm Reason in Big-O; use timings only to confirm the shape (section 1)
Reaching for a nested loop before trying a HashMap/HashSet Turns an O(n) problem into O(n²) by habit Ask "have I seen this?" or "what pairs with this?" — that's almost always hashing
Two pointers from both ends on unsorted data The "move left in, sum goes up" assumption only holds when sorted Sort first, or use hashing instead (section 2 vs. section 3)
java.util.Stack or casting Queue in new code Legacy, synchronized, slower than needed ArrayDeque, used as a stack or a queue (section 4)
A redo stack that doesn't clear on a new action Redo "resurrects" a future that no longer exists after a fresh edit Clear the redo stack the moment any new action is taken (the undo build)
A recursive case that never shrinks toward the base case StackOverflowError, not an infinite loop you can interrupt as easily Double-check every recursive call passes a strictly smaller sub-problem
Assuming Arrays.sort is always the same algorithm Primitives get Dual-Pivot Quicksort (unstable); objects get TimSort (stable) Know which one you're calling when stability matters (section 6)
Binary search on data that might not be sorted Returns a wrong, confident-looking "not found" or a wrong index Sort first — binary search never checks the precondition for you (section 7)
Deleting from a singly linked list without tracking the previous node Can't relink previous.next if you don't have previous Walk with a previous pointer alongside current (section 8)
Inserting already-sorted data into a plain BST Degrades to a linked list: O(n) height instead of O(log n) Know the caveat; reach for a self-balancing tree (TreeMap/TreeSet) when it matters (section 9)
Bounding the wrong kind of heap for top-k Keeping the k smallest needs a MAX-heap to evict from (and vice versa) Say out loud which end you're evicting from before writing the comparator (section 10)
Using BFS when edges have different weights Finds fewest hops, not fastest/cheapest route Dijkstra: a priority queue ordered by accumulated cost, not a plain queue (section 11)
Reaching for DP when sub-problems don't actually overlap Extra bookkeeping for no benefit Confirm the same sub-problem gets asked for more than once before adding a cache or a table (section 12)

Quick recap

  • Big-O measures how work grows with input size; compare ratios as n grows, not raw timings.
  • Hashing (HashMap/HashSet) turns "have I seen this?" from O(n²) into O(n).
  • Two pointers and sliding windows replace a nested loop with one coordinated pass; two pointers from both ends needs sorted data.
  • Deque is both a stack and a queue; prefer it over Stack and Queue casts.
  • Recursion needs a base case and a shrinking recursive case; backtracking adds choose/explore/un-choose, often with pruning.
  • Four classic sorts build the intuition Arrays.sort relies on: quicksort for primitives, TimSort (stable merge sort) for objects.
  • Binary search is O(log n) but requires sorted data — it never checks that precondition for you.
  • A singly linked list gives O(1) insert-at-head but needs a previous pointer to delete anything else.
  • A BST gives O(log n) operations only while balanced; sorted-order inserts skew it to O(n).
  • PriorityQueue is Java's heap; bound it to size k (the right end, min or max) for top-k without a full sort.
  • An adjacency list represents a graph; BFS (queue) finds fewest hops, DFS (stack/recursion) explores depth-first, Dijkstra (priority queue) finds the cheapest weighted path.
  • Dynamic programming reuses overlapping sub-problem answers, top-down (memoization) or bottom-up (tabulation); it needs both optimal substructure and actual overlap to be worth it.

Checklist

  • I can explain Big-O by counting operations, not by timing code, and I know why n² means "doubling n roughly quadruples the work."
  • I replaced an O(n²) brute force with an O(n) hashing solution myself.
  • I solved a two-pointer problem on sorted data and a sliding-window problem (fixed and variable size).
  • I used Deque as both a stack and a queue, and built the undo-button example end to end.
  • I wrote a recursive function with a base case, and a backtracking function with pruning.
  • I implemented bubble, insertion, merge and quicksort by hand, and can say which Arrays.sort actually runs for primitives vs. objects.
  • I implemented binary search by hand, then used Arrays.binarySearch/Collections.binarySearch, and reproduced the wrong-answer-on-unsorted-data bug myself.
  • I built a singly linked list by hand: insert, delete, reverse, and Floyd's cycle detection.
  • I built a binary search tree by hand: insert, search, all four traversal orders, and I can explain why a skewed tree degrades to O(n).
  • I used PriorityQueue as a min-heap and a max-heap, and solved a bounded top-k problem — and built the trending-posts example.
  • I represented a graph with an adjacency list, ran BFS and DFS, and built the Dijkstra-based delivery-route example.
  • I solved one problem with memoization and the same problem with tabulation, and got the same answer both ways.

Search the guide