Data Structures & Algorithms Tutorial
A complete Java-first DSA learning path covering arrays, strings, linked lists, trees, heaps, graphs, greedy methods, and dynamic programming with first-principles explanations.
1: Java Foundations for DSA
Goal: Build enough Java fluency to solve beginner DSA problems without getting stuck on syntax, containers, or program structure.
Outcome: By the end of this chapter, you can write clean Java methods, use arrays and strings safely, choose between ArrayList, HashMap, and HashSet, define simple classes with comparators, and start every DSA problem from a reusable coding template.
1. Intuition First
Java for DSA is a workshop. Variables are labeled boxes. Loops are repeated actions. Methods are reusable tools. Arrays and strings are simple storage shelves. Collections are smarter containers. Classes let you model real data, and comparators tell Java how to order that data.
This chapter matters because beginner DSA problems are rarely hard because of the algorithm alone. They are hard because learners try to think about the algorithm, the syntax, the data structure, and the output format all at once. That overload causes avoidable mistakes.
The simplest real-world analogy is a kitchen prep station. Before cooking a meal, you need containers, measuring rules, a cutting sequence, and a clean workspace. DSA problem solving works the same way. You need a stable setup before speed or cleverness matters.
The most common beginner confusion point is not "What is a loop?" It is "Which Java tool should I pick here?" Should this be an array or an ArrayList? Should I count with a HashMap? Should I make a helper method? This chapter answers those decisions early so later chapters can focus on actual algorithmic thinking.
In the roadmap, this chapter is the language foundation. It does not teach advanced algorithms. It teaches how to express them cleanly when they arrive.
2. Core Concepts and Techniques
Concept Cluster: Variables, Data Types, and Operators
Key concepts in this block:
- 1.1 Variables, data types, and operators
Intuition
A variable is a named box. A data type tells Java what can go inside that box. An operator is the action you perform on those values.
Why It Matters
DSA problems depend on correct state updates. If you pick the wrong type or misunderstand an operator, the algorithm can fail before the real logic even starts.
How It Works
The most common beginner Java types are:
intfor whole numbers in a moderate rangelongfor larger whole numbersdoublefor decimal valuesbooleanfor true or false statecharfor a single characterStringfor text
The main operator groups are:
- arithmetic:
+,-,*,/,% - comparison:
==,!=,<,<=,>,>= - logical:
&&,||,! - assignment:
=,+=,-=,*=,/=
Two beginner rules matter immediately:
- integer division drops the fractional part, so
5 / 2is2 - multiplication can overflow
int, so uselongwhen constraints may grow large
Java Implementation Notes
- Use
longfor sums, products, and large counters when problem constraints may exceed about 2 billion. - Add parentheses when expression order is not obvious. Clear grouping is better than trusting precedence memory.
- Use final local variables when a value should not change after initialization.
Common Mistakes
- Using
intfor a value that should belong - Expecting
7 / 2to produce3.5 - Mixing comparison and assignment thinking
- Writing expressions that rely on operator precedence instead of making grouping explicit
Quick Example
static long computeScore(int solvedProblems, int bonusPerProblem, boolean submittedOnTime) {
long score = (long) solvedProblems * bonusPerProblem;
if (!submittedOnTime) {
score -= 5;
}
return Math.max(score, 0L);
}
Debugging Tip
When arithmetic looks wrong, print every intermediate value before the final assignment. Most beginner bugs come from one unexpected expression, not from the whole method.
Advanced Note
Even simple DSA problems can fail because of overflow. If a problem uses values up to 10^9, a product of two such values does not fit in int.
Concept Cluster: Conditions, Loops, and Methods
Key concepts in this block:
- 1.2 Conditions, loops, and methods
Intuition
Conditions choose a path. Loops repeat work. Methods package logic so you can reuse and test it.
Why It Matters
Most DSA solutions are nothing more than careful state updates inside loops, plus a few helper methods that keep the code readable.
How It Works
Use:
if,else if, andelsewhen the program must choose between casesforwhen the number of steps is naturally tied to an index or rangewhilewhen repetition depends on a changing condition- methods to isolate one logical job at a time
For DSA, a strong beginner habit is: keep main small, put logic in methods, and let each method answer one clear question.
Java Implementation Notes
- Prefer enhanced for-loops when you only need values, not indexes.
- Prefer indexed loops when you need element positions or need to modify array entries.
- Use early returns in methods to reduce nesting.
Common Mistakes
- Infinite loops caused by forgetting to update loop state
- Off-by-one errors such as using
i <= arr.length - 1instead ofi < arr.length - Writing one very large method instead of a few focused helper methods
Quick Example
static int countPositiveEvenNumbers(int[] values) {
int count = 0;
for (int value : values) {
if (value > 0 && value % 2 == 0) {
count++;
}
}
return count;
}
Debugging Tip
If a loop produces the wrong answer, print the loop index, the current value, and the state variable after each update. That usually reveals the first wrong transition.
Advanced Note
Good methods do not just improve readability. They also make dry runs, test cases, and future refactoring much easier.
Concept Cluster: Arrays and Strings in Java
Key concepts in this block:
- 1.3 Arrays and strings in Java
Intuition
An array is a fixed-size row of boxes. A string is a sequence of characters. Arrays are mutable. Strings are immutable, which means their contents do not change after creation.
Why It Matters
Most early DSA problems are about traversing arrays or reading patterns from strings. If you understand indexing and immutability early, later chapters become much easier.
How It Works
Key points:
- array size is fixed after creation
- array indexing starts at
0 - array length is
arr.length - string length is
text.length() - character access is
text.charAt(index)
Because strings are immutable, repeated concatenation in a loop creates many temporary strings. That is acceptable for tiny problems but inefficient for heavy output or repeated edits.
Java Implementation Notes
- Use arrays when the size is known and fixed.
- Use strings for read-only text handling.
- Be careful with
charAt(index)because it throws an exception if the index is invalid.
Common Mistakes
- Confusing
arr.lengthwithtext.length() - Accessing
arr[arr.length], which is out of bounds - Using
==to compare strings instead of.equals() - Building a long output string with repeated
+inside a loop
Quick Example
static int countOccurrences(String text, char target) {
int count = 0;
for (int index = 0; index < text.length(); index++) {
if (text.charAt(index) == target) {
count++;
}
}
return count;
}
Debugging Tip
When string logic fails, print the index and the current character. When array logic fails, print the valid index range before the loop starts.
Advanced Note
Strings are immutable for safety and predictability. Later, when performance matters, StringBuilder becomes the better tool for repeated text construction.
Concept Cluster: ArrayList, HashMap, and HashSet Basics
Key concepts in this block:
- 1.4 ArrayList, HashMap, and HashSet basics
Intuition
ArrayList is a dynamic array. HashMap stores key-value pairs. HashSet stores unique values.
Why It Matters
These three tools solve a huge share of beginner DSA tasks:
- store a growing list
- count frequencies
- check whether a value has already appeared
How It Works
ArrayList<E>supports fast append and indexed accessHashMap<K, V>supports averageO(1)insert and lookup by keyHashSet<E>supports averageO(1)membership checks
Use:
ArrayListwhen size changes over timeHashMapwhen you need counts, grouping, or direct lookup by keyHashSetwhen only existence or uniqueness matters
Java Implementation Notes
map.getOrDefault(key, 0)is a standard frequency-counting pattern.set.add(value)returnstrueonly if the value was not already present.- Generic types matter:
HashMap<String, Integer>is much clearer than raw types.
Common Mistakes
- Using
ArrayList.contains()repeatedly when aHashSetis the better fit - Forgetting that
HashMapiteration order is not sorted - Confusing keys with values when reading or updating a map
Quick Example
static java.util.HashMap<String, Integer> buildFrequencyMap(String[] words) {
java.util.HashMap<String, Integer> frequency = new java.util.HashMap<>();
for (String word : words) {
frequency.put(word, frequency.getOrDefault(word, 0) + 1);
}
return frequency;
}
Debugging Tip
If frequency logic is wrong, print the map after each update for a tiny sample input of three or four elements.
Advanced Note
Average O(1) does not mean ordered. When order matters, you may need a different structure later, but HashMap and HashSet remain the default fast lookup tools.
Concept Cluster: Classes, Objects, and Comparators
Key concepts in this block:
- 1.5 Classes, objects, and comparators
Intuition
A class is a blueprint. An object is one actual instance built from that blueprint. A comparator is a rule that tells Java how two objects should be ordered.
Why It Matters
Real DSA problems rarely stay as plain integers forever. You often need to store multiple fields together such as name, score, and age, then sort by one field and break ties with another.
How It Works
Use a class when multiple values belong together. Use a comparator when sorting needs a custom rule such as:
- score descending
- then name ascending
This is cleaner than trying to keep related values in separate arrays.
Java Implementation Notes
- Keep fields focused and constructor initialization clear.
- Prefer comparators for sorting rules that may change from problem to problem.
- Name comparators by intent, not by syntax.
Common Mistakes
- Splitting related data into parallel arrays instead of one class
- Writing comparator rules that forget tie-breaking conditions
- Returning inconsistent ordering logic, which can make sorting behavior unreliable
Quick Example
static final class Student {
final String name;
final int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
}
static java.util.Comparator<Student> byScoreDescendingThenNameAscending() {
return (left, right) -> {
if (left.score != right.score) {
return Integer.compare(right.score, left.score);
}
return left.name.compareTo(right.name);
};
}
Debugging Tip
If sorting looks wrong, print the data both before and after sorting, and manually compare two items that appear out of order.
Advanced Note
Comparators are one of the first places where clean design shows up in DSA code. A good comparator makes the sorting rule visible instead of burying it inside unrelated logic.
Concept Cluster: Fast Input/Output and a Reusable Coding Template
Key concepts in this block:
- 1.6 Fast input/output and a reusable coding template
Intuition
Fast I/O is a stable entry point for problems with large input. A reusable template reduces setup mistakes and lets you focus on the actual problem.
Why It Matters
For small examples, Scanner is fine. For larger inputs, it can become noticeably slow. A lightweight template with a fast scanner and clean solve() method is the standard Java DSA starting point.
How It Works
A beginner-friendly template usually contains:
- a
FastScannerfor token-based input - a
solve()method for the real logic - a
mainmethod that only callssolve() StringBuilderorPrintWriterfor efficient output
Java Implementation Notes
- Keep the template minimal. Do not copy a huge personal library before you understand it.
- Start with one fast scanner class and one place for helper methods.
- Use
StringBuilderwhen producing many lines of output.
Common Mistakes
- Putting all logic inside
main - Copying a template without understanding how it reads tokens
- Mixing slow and fast I/O styles carelessly
- Forgetting to handle empty input in a reusable template
Quick Example
import java.io.BufferedInputStream;
import java.io.IOException;
public class Main {
private static final class FastScanner {
private final BufferedInputStream input = new BufferedInputStream(System.in);
private final byte[] buffer = new byte[1 << 16];
private int pointer = 0;
private int bytesRead = 0;
private int read() throws IOException {
if (pointer >= bytesRead) {
bytesRead = input.read(buffer);
pointer = 0;
if (bytesRead <= 0) {
return -1;
}
}
return buffer[pointer++];
}
int nextInt() throws IOException {
int current;
do {
current = read();
} while (current <= ' ');
int sign = 1;
if (current == '-') {
sign = -1;
current = read();
}
int value = 0;
while (current > ' ') {
value = value * 10 + current - '0';
current = read();
}
return value * sign;
}
}
public static void main(String[] args) throws Exception {
FastScanner scanner = new FastScanner();
int count = scanner.nextInt();
long sum = 0;
for (int index = 0; index < count; index++) {
sum += scanner.nextInt();
}
System.out.println(sum);
}
}
Debugging Tip
When fast input fails, first test the scanner with a tiny input of one or two numbers. Scanner bugs are easier to isolate before the full solution exists.
Advanced Note
The best template is not the biggest template. It is the one you fully understand and can debug under pressure.
3. Worked Examples and Full Solutions
Worked Example 1: Count Distinct Numbers
Problem Statement
Given an integer array, return how many distinct values it contains.
Why This Example Matters
This is one of the cleanest first examples for choosing between brute force and the right Java container. It reinforces arrays, loops, methods, and HashSet.
Constraints or Assumptions
- The array may be empty.
- Values may repeat.
- Values may be negative.
Brute-Force Approach
Keep a second array or list of values seen so far. For every new number, scan that stored collection linearly to check whether the number already exists. If not, add it.
This works, but in the worst case every new number scans all previous unique values, so the total time becomes O(n^2).
Better Approach
Use a HashSet<Integer>. Add every value once, then return the set size.
Why the Better Approach Works
A set stores each unique value only once. The repeated "have I seen this before?" question becomes an average O(1) membership operation instead of a linear scan.
Pragmatic Java Choice
For uniqueness checks, HashSet is the default starting point. It is clearer and less bug-prone than maintaining manual duplicate logic.
Java Solution
import java.util.HashSet;
import java.util.Set;
public class DistinctCounter {
public static int countDistinct(int[] values) {
Set<Integer> seen = new HashSet<>();
for (int value : values) {
seen.add(value);
}
return seen.size();
}
public static void main(String[] args) {
int[] values = {4, 2, 4, 1, 2, 5};
System.out.println(countDistinct(values));
}
}
Dry Run
Input: [4, 2, 4, 1, 2, 5]
- Start with
seen = {} - Read
4, set becomes{4} - Read
2, set becomes{2, 4} - Read
4, set stays{2, 4} - Read
1, set becomes{1, 2, 4} - Read
2, set stays{1, 2, 4} - Read
5, set becomes{1, 2, 4, 5} - Final answer:
4
Time and Space Complexity
- Brute force:
O(n^2)time,O(n)space - Better approach: average
O(n)time,O(n)space
Edge Cases
- Empty array returns
0 - Single element returns
1 - All values equal returns
1
Common Mistakes
- Using
ArrayList.contains()repeatedly instead of a set - Forgetting that uniqueness, not order, is the goal here
- Returning the array length instead of the set size
Worked Example 2: Most Frequent Word in a Sentence
Problem Statement
Given a lowercase sentence with words separated by spaces, return the most frequent word. If multiple words have the same highest frequency, return the lexicographically smallest one.
Why This Example Matters
This example shows why HashMap is one of the most important DSA tools in Java. It turns repeated counting from a slow nested-loop process into a clean one-pass pattern.
Constraints or Assumptions
- Input may be empty or blank.
- Words contain only lowercase English letters.
- Words are separated by one or more spaces.
Brute-Force Approach
Split the sentence into words. For each word, scan the full array again to count how many times it appears. Track the best answer with tie-breaking.
This is straightforward but costs O(n^2) time because counting one word requires another full pass.
Better Approach
Split once, maintain a frequency map, and update the best answer while building the map.
Why the Better Approach Works
Each word contributes one increment to its own count. The map remembers the frequency seen so far, so no repeated full-array scanning is needed.
Pragmatic Java Choice
Use HashMap<String, Integer> for counting. It is the standard Java frequency-map pattern and appears in many later chapters.
Java Solution
import java.util.HashMap;
import java.util.Map;
public class MostFrequentWord {
public static String mostFrequentWord(String text) {
if (text == null || text.isBlank()) {
return "";
}
String[] words = text.trim().split("\\s+");
Map<String, Integer> frequency = new HashMap<>();
String bestWord = "";
int bestCount = 0;
for (String word : words) {
int updatedCount = frequency.getOrDefault(word, 0) + 1;
frequency.put(word, updatedCount);
if (updatedCount > bestCount
|| (updatedCount == bestCount
&& (bestWord.isEmpty() || word.compareTo(bestWord) < 0))) {
bestCount = updatedCount;
bestWord = word;
}
}
return bestWord;
}
public static void main(String[] args) {
String text = "java loops java map loops java";
System.out.println(mostFrequentWord(text));
}
}
Dry Run
Input: "java loops java map loops java"
- Start with empty map,
bestWord = "",bestCount = 0 - Read
java, map becomes{java=1}, best becomesjava - Read
loops, map becomes{java=1, loops=1}, tie does not beatjava - Read
java, map becomes{java=2, loops=1}, best becomesjava - Read
map, map becomes{java=2, loops=1, map=1} - Read
loops, map becomes{java=2, loops=2, map=1}, tie betweenjavaandloops, lexicographicallyjavastays smaller - Read
java, map becomes{java=3, loops=2, map=1}, best staysjava - Final answer:
java
Time and Space Complexity
- Brute force:
O(n^2)time,O(n)space for split words - Better approach: average
O(n)time,O(n)space
Edge Cases
- Blank input returns
"" - One word returns that word
- Full tie uses lexicographic order
Common Mistakes
- Forgetting to trim or split on repeated spaces
- Updating the map but forgetting to update the current best answer
- Using
==instead of.equals()when comparing string content elsewhere
Worked Example 3: Build a Simple Leaderboard
Problem Statement
Read n student records. Each record contains a one-word name and an integer score. Print the students sorted by score descending, then by name ascending.
Why This Example Matters
This example combines multiple Chapter 1 ideas in one place: classes, objects, comparators, arrays, fast input, and efficient output.
Constraints or Assumptions
- Student names are single tokens.
nmay be large enough that fast input is useful.- Duplicate names are allowed.
Brute-Force Approach
Use Scanner, store each student in parallel arrays, and manually selection-sort the result.
That works for learning, but it mixes related data poorly and uses an O(n^2) sorting approach when Java already provides a better sorting API.
Better Approach
Create a Student class, store records in an array, define a comparator for the sorting rule, and use Arrays.sort. Use a fast scanner and StringBuilder for input/output overhead.
Why the Better Approach Works
The class keeps related fields together. The comparator makes the ordering rule explicit. Arrays.sort uses a well-optimized library implementation and removes a lot of manual sorting bugs.
Pragmatic Java Choice
When multiple fields belong together, model them with a class. When sorting rules are custom, use a comparator instead of scattering sort logic across the program.
Java Solution
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Arrays;
public class LeaderboardBuilder {
private static final class Student {
final String name;
final int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
}
private static final class FastScanner {
private final BufferedInputStream input = new BufferedInputStream(System.in);
private final byte[] buffer = new byte[1 << 16];
private int pointer = 0;
private int bytesRead = 0;
private int read() throws IOException {
if (pointer >= bytesRead) {
bytesRead = input.read(buffer);
pointer = 0;
if (bytesRead <= 0) {
return -1;
}
}
return buffer[pointer++];
}
String next() throws IOException {
int current;
do {
current = read();
} while (current != -1 && current <= ' ');
if (current == -1) {
return null;
}
StringBuilder token = new StringBuilder();
while (current > ' ') {
token.append((char) current);
current = read();
}
return token.toString();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws Exception {
FastScanner scanner = new FastScanner();
int count = scanner.nextInt();
Student[] students = new Student[count];
for (int index = 0; index < count; index++) {
String name = scanner.next();
int score = scanner.nextInt();
students[index] = new Student(name, score);
}
Arrays.sort(students, (left, right) -> {
if (left.score != right.score) {
return Integer.compare(right.score, left.score);
}
return left.name.compareTo(right.name);
});
StringBuilder output = new StringBuilder();
for (Student student : students) {
output.append(student.name)
.append(' ')
.append(student.score)
.append('\n');
}
System.out.print(output);
}
}
Dry Run
Sample input:
4
Mira 90
Arun 95
Zoya 90
Ishaan 95
Steps:
- Read 4 students into an array of
Studentobjects - Compare by score descending first
- For the two students with score 95, compare names:
Aruncomes beforeIshaan - For the two students with score 90, compare names:
Miracomes beforeZoya - Final order:
Arun 95Ishaan 95Mira 90Zoya 90
Time and Space Complexity
- Brute force with manual selection sort:
O(n^2)time,O(n)space for storage - Better approach:
O(n log n)time for sorting,O(n)space for storage and output building
Edge Cases
n = 0should print nothing- Equal scores must be ordered by name
- One student should still work correctly
Common Mistakes
- Splitting name and score into unrelated parallel arrays
- Forgetting the tie-break comparator rule
- Using
Scannerfor very large inputs without noticing the slowdown - Appending output line by line with repeated string concatenation
4. Complexity and Decision Guide
The main lesson of this chapter is not to optimize everything early. It is to choose the right basic tool.
- Use arrays when size is known and indexed access matters. Array access is
O(1). - Use
ArrayListwhen the collection grows dynamically and indexed access still matters. - Use
HashSetwhen the real question is membership or uniqueness. - Use
HashMapwhen the real question is lookup, counting, or grouping by key. - Use a class when multiple fields describe one logical item.
- Use a comparator when sorting depends on more than one field or on a custom ordering rule.
Recognition signals:
- "count frequency" usually means
HashMap - "have we seen this before" usually means
HashSet - "store a list that grows" usually means
ArrayList - "sort by score, then by name" usually means class plus comparator
- "large input" often means fast I/O template
Signals not to force a technique:
- If the size is fixed and simple, an array may be better than
ArrayList. - If you only need a yes-or-no existence check, do not build a full map.
- If the program is tiny and the input is tiny, fast I/O is optional.
- If data belongs together, do not force separate arrays just because arrays were introduced earlier.
Brute force is still useful in Chapter 1 because it teaches the bottleneck clearly. The goal is to understand why the better structure helps, not to memorize containers without context.
5. Edge Cases, Pitfalls, and Debugging
Common pitfalls in early Java DSA code:
- confusing
arr.lengthandtext.length() - accessing an array out of bounds
- using
==for string content comparison - forgetting to reset or update a state variable inside a loop
- choosing
intwhenlongis safer - storing related values in separate arrays instead of one class
- using a list for repeated membership checks instead of a set
Boundary conditions to test early:
- empty input
- one element
- all values equal
- all values distinct
- smallest and largest allowed numeric values
- tie cases during sorting or counting
Short debugging checklist:
- Write the smallest sample input that still reproduces the bug.
- Print the loop index and the main state variable after each update.
- For maps and sets, print the container after each insert on a tiny example.
- For comparators, manually compare two specific objects that appear misordered.
- For input bugs, test the scanner separately before testing the whole algorithm.
- Dry run one example on paper before changing the code again.
6. Practice Problems
Easy
Count Positive Numbers
One-line prompt: Given an array of integers, return how many elements are greater than zero.
Expected pattern or core idea: Array traversal with a simple counter.First Duplicate Value
One-line prompt: Return the first value that appears more than once in an integer array, or-1if none exists.
Expected pattern or core idea:HashSetmembership tracking.Vowel Counter
One-line prompt: Given a string, count how many vowels it contains.
Expected pattern or core idea: String traversal with conditions.
Medium
Student Pass Report
One-line prompt: Given student names and scores, print all passing students sorted by score descending and name ascending.
Expected pattern or core idea: Class plus comparator plus filtering.Word Frequency Summary
One-line prompt: Given a sentence, print each word with its frequency.
Expected pattern or core idea:HashMapfrequency counting.Unique Sorted Numbers
One-line prompt: Readnintegers, remove duplicates, and print the remaining values in ascending order.
Expected pattern or core idea:HashSetfor uniqueness, then list conversion and sorting.
Hard
Mini Contact Directory
One-line prompt: Support commandsADD name number,FIND name, andCOUNTfor many operations.
Expected pattern or core idea: Reusable template plusHashMaplookup.Contest Ranking Engine
One-line prompt: Given many submissions with participant name and score, keep each participant's best score and print the final ranking.
Expected pattern or core idea:HashMapaggregation plus class and comparator.Character Frequency Tie Breaker
One-line prompt: Return the most frequent character in a string, breaking ties by earliest position.
Expected pattern or core idea: Counting plus careful tie-handling logic.
7. Short Recap
The core idea of this chapter is that good DSA code starts with stable Java basics: correct types, controlled loops, focused methods, and the right container for the job.
The most important optimization insight is simple: replace repeated scanning with the right lookup structure. HashSet removes manual duplicate checks, and HashMap removes repeated counting passes.
The most important implementation warning is that many beginner bugs come from structure, not algorithms: wrong index bounds, wrong type choice, wrong container, or unclear method design.
This chapter prepares the next one by giving you the raw Java tools needed to analyze efficiency instead of just making code run.
8. Coverage Check
- 1.1 Variables, data types, and operators
- 1.2 Conditions, loops, and methods
- 1.3 Arrays and strings in Java
- 1.4 ArrayList, HashMap, and HashSet basics
- 1.5 Classes, objects, and comparators
- 1.6 Fast input/output and a reusable coding template
- Coverage Summary: 6/6 official subtopics covered
Next: 2: Complexity and Problem-Solving Basics
2: Complexity and Problem-Solving Basics
Goal: Teach learners how to measure algorithm cost, compare approaches honestly, read constraints carefully, and choose a fitting data structure before writing code.
Outcome: By the end of this chapter, you can estimate time and space complexity, separate best, average, worst, and amortized reasoning, read constraints with purpose, and make better early decisions about arrays, hash-based structures, and preprocessing.
1. Intuition First
Complexity is how you estimate the cost of a solution before you run it. In DSA, that matters because a correct solution can still fail if it does too much work or uses too much memory.
A simple real-world analogy is choosing transportation for a daily commute. Walking, cycling, and driving can all get you to the same destination, but the right choice depends on distance, traffic, budget, and how often you make the trip. Algorithms work the same way. Several approaches may be correct, but the input size and constraints decide which one is practical.
The core mental model is growth. Do not ask only, "How many steps does this take on one small example?" Ask, "How does the work grow when the input doubles, or becomes 100 times larger?"
The most common beginner confusion point is treating syntax complexity and algorithmic complexity as the same thing. A short piece of code is not automatically fast. A long piece of code is not automatically slow. The real question is how many operations it performs as input size grows.
In the larger roadmap, this chapter is the judgment layer. It helps you stop guessing. From here onward, each new pattern should come with an efficiency argument, not just working code.
2. Core Concepts and Techniques
Concept Cluster: Measuring Work and Memory
Key concepts in this block:
- 2.1 Time complexity
- 2.2 Space complexity
Intuition
Time complexity measures how the number of operations grows with input size. Space complexity measures how much extra memory the algorithm needs while it runs.
Why It Matters
If n is tiny, many approaches work. If n is large, a small change in growth rate can decide whether the solution finishes in time. Space matters for the same reason. An algorithm that is fast but uses too much extra memory can still be unusable.
How It Works
Use n for input size and describe growth with Big-O notation.
Common patterns:
O(1): constant work, such as readingarr[0]O(log n): work shrinks by a fraction each stepO(n): one full pass through the inputO(n log n): sorting-like behaviorO(n^2): two nested passes over the input
For space complexity, separate input storage from extra storage.
Examples:
- summing an array with one variable uses
O(1)extra space - copying the array into another array uses
O(n)extra space - using a
HashSetof seen values can also useO(n)extra space
When analyzing, ignore small constants and lower-order terms. 3n + 5 grows like O(n). n^2 + n grows like O(n^2).
Java Implementation Notes
- Count loop structure, not line count.
- Temporary arrays,
HashMap,HashSet, and recursion stacks all affect space complexity. - Be explicit about whether you mean total memory or auxiliary memory. In interviews and DSA tutorials, auxiliary space is usually the focus.
Common Mistakes
- Saying two consecutive loops are
O(n^2)when they are reallyO(n) + O(n) = O(n) - Forgetting that nested loops may still be linear if pointers only move forward overall
- Ignoring the memory cost of helper structures such as sets or frequency arrays
- Confusing faster-looking code with faster asymptotic growth
Quick Example
static int sumArray(int[] values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
This method is O(n) time and O(1) extra space.
Debugging Tip
When complexity reasoning feels unclear, write down exactly what each loop variable can do over the full execution. That usually reveals whether the total work is linear, quadratic, or something else.
Advanced Note
Big-O describes growth, not exact runtime. A slower O(n) implementation can still beat a poorly optimized O(n log n) one on small inputs. Complexity gives the main trend, not the full performance story.
Concept Cluster: Case Analysis and Amortized Thinking
Key concepts in this block:
- 2.3 Best, average, and worst case analysis
- 2.4 Amortized analysis
Intuition
Not every input triggers the same amount of work. Some are easy, some typical, and some painful. Amortized analysis asks what the average cost per operation is across a long sequence of operations, even if a few individual operations are expensive.
Why It Matters
Without case analysis, you can misjudge risk. Without amortized analysis, dynamic structures such as resizable arrays look worse than they really are.
How It Works
Best, average, and worst case:
- best case: the luckiest valid input
- average case: the expected cost across typical inputs under some model
- worst case: the maximum cost on any valid input
Example with linear search:
- best case: target is at index
0, soO(1) - worst case: target is absent or at the end, so
O(n) - average case: target tends to appear somewhere in the middle, still linear growth
Amortized analysis:
- a resizable array append is sometimes expensive because resizing copies all elements
- but if capacity doubles when full, those expensive copies happen rarely
- across many appends, the average cost per append is
O(1)amortized
Java Implementation Notes
ArrayListappend is a classic amortizedO(1)operation.- Be careful not to confuse amortized
O(1)with guaranteedO(1)for every single operation. - In Java, library methods may hide resizing or copying work. That hidden work still matters in analysis.
Common Mistakes
- Reporting the best case as if it represents normal behavior
- Assuming average case without saying what "average" means
- Treating one expensive resize as proof that all appends are linear
- Forgetting that worst-case analysis is often the safest default in interviews
Quick Example
class SimpleDynamicArray {
private int[] data = new int[2];
private int size = 0;
void add(int value) {
if (size == data.length) {
int[] next = new int[data.length * 2];
System.arraycopy(data, 0, next, 0, data.length);
data = next;
}
data[size++] = value;
}
}
Most add calls cost constant time. A resize costs linear time, but not on every call. That is why append is amortized O(1).
Debugging Tip
If one test case is much slower than the rest, check whether you are looking at a worst-case input or at a hidden expensive operation such as copying or reallocation.
Advanced Note
Amortized reasoning is strongest when you can prove that each element is copied or moved only a limited number of times over the full sequence.
Concept Cluster: Constraints, Feasibility, and Data Structure Choice
Key concepts in this block:
- 2.5 Reading problem constraints
- 2.6 Choosing the right data structure
Intuition
Problem constraints are not decoration. They tell you what kind of solution the problem is asking for. Data structures are the tools that let you achieve that target complexity.
Why It Matters
Many wrong approaches are rejected before coding even starts. If n = 10^5, a quadratic solution usually will not fit. If the problem asks for fast membership checks, a HashSet may fit better than repeated linear scans.
How It Works
Read constraints with these questions:
- how large can the input become?
- is there one query or many queries?
- do we need updates, lookups, ordering, or uniqueness?
- do values fit in
int, or do we needlong? - is extra memory acceptable?
Useful early choices:
- array: fixed-size sequential storage with fast indexed access
ArrayList: dynamic sequence with fast appendHashSet: fast membership and uniqueness checksHashMap: fast key-value lookup and frequency counting
Match the data structure to the dominant operation:
- repeated membership queries ->
HashSet - counting frequencies ->
HashMap - indexed access -> array or
ArrayList - append-heavy dynamic storage ->
ArrayList
Java Implementation Notes
- Use
longwhen constraints suggest sums or products may overflowint. - Prefer the simplest structure that meets the performance target.
- If the problem needs sorted order, a plain
HashMaporHashSetmay not be enough.
Common Mistakes
- Ignoring repeated queries and solving each one from scratch
- Using a list for membership checks when a set is more appropriate
- Using a map when a small fixed-size frequency array would be simpler
- Picking a structure by habit instead of by operation cost
Quick Example
static boolean containsDuplicate(int[] values) {
java.util.HashSet<Integer> seen = new java.util.HashSet<>();
for (int value : values) {
if (seen.contains(value)) {
return true;
}
seen.add(value);
}
return false;
}
The main gain comes from replacing repeated scanning with fast membership checks.
Debugging Tip
Before coding, write one sentence that starts with: "The slow part of the naive approach is..." Then choose a data structure that directly attacks that bottleneck.
Advanced Note
The right data structure is sometimes the difference between O(n^2) and O(n). Most early optimization is not about clever math. It is about storing information so you do not recompute it.
3. Worked Examples and Full Solutions
Worked Example 1: Detect Whether an Array Contains Duplicates
Problem Statement
Given an integer array, return true if any value appears at least twice. Otherwise, return false.
Why This Example Matters
This is one of the clearest early examples of how a data structure choice changes complexity.
Constraints or Assumptions
1 <= values.length <= 100000- integers fit in Java
int - order does not matter for the final answer
Brute-Force Approach
Compare every pair of positions. If any pair has the same value, a duplicate exists.
That means two nested loops, which leads to O(n^2) time and O(1) extra space.
Better Approach
Use a HashSet to track values seen so far. While scanning the array once, check whether the current value is already in the set.
Why the Better Approach Works
The brute-force method recomputes membership information again and again. The set stores that information as you go, so each value is checked once.
Pragmatic Java Choice
Use HashSet<Integer> because the important operation is membership testing, not ordering.
Java Solution
import java.util.HashSet;
import java.util.Set;
class DuplicateChecker {
static boolean containsDuplicateBruteForce(int[] values) {
for (int left = 0; left < values.length; left++) {
for (int right = left + 1; right < values.length; right++) {
if (values[left] == values[right]) {
return true;
}
}
}
return false;
}
static boolean containsDuplicateOptimized(int[] values) {
Set<Integer> seen = new HashSet<>();
for (int value : values) {
if (seen.contains(value)) {
return true;
}
seen.add(value);
}
return false;
}
}
Dry Run
Use values = [3, 1, 4, 1].
Brute force:
- compare
3with1,4,1 - compare first
1with4, then second1 - match found on the pair
(1, 1)
Optimized:
- start with
seen = {} - read
3, not present, add it ->{3} - read
1, not present, add it ->{3, 1} - read
4, not present, add it ->{3, 1, 4} - read
1, already present -> returntrue
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Optimized:
O(n)average time,O(n)extra space
Edge Cases
- empty array ->
false - one element ->
false - negative values -> handled normally
- all equal values -> early duplicate detection
Common Mistakes
- forgetting that
HashSetuses extra space - using a list instead of a set and losing the time improvement
- checking after adding only if you do not understand
addsemantics clearly
Worked Example 2: Answer Many Membership Queries
Problem Statement
Given an integer array values and another integer array queries, return a boolean array where each answer tells whether the query value exists in values.
Why This Example Matters
It shows how reading constraints changes the solution. One lookup may tolerate a scan. Thousands of lookups usually should not.
Constraints or Assumptions
1 <= values.length, queries.length <= 100000- duplicates may exist in
values - each query is independent
Brute-Force Approach
For every query, scan the full array until the value is found or the scan ends.
This costs O(values.length * queries.length) time.
Better Approach
Build a HashSet from values once, then answer each query with a constant-time average membership check.
Why the Better Approach Works
The expensive part is repeating the same array scan for each query. Preprocessing stores the searchable information once.
Pragmatic Java Choice
Use a HashSet<Integer> for preprocessing and a boolean[] for answers.
Java Solution
import java.util.HashSet;
import java.util.Set;
class MembershipQueries {
static boolean[] answerQueriesBruteForce(int[] values, int[] queries) {
boolean[] answers = new boolean[queries.length];
for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
int target = queries[queryIndex];
for (int value : values) {
if (value == target) {
answers[queryIndex] = true;
break;
}
}
}
return answers;
}
static boolean[] answerQueriesOptimized(int[] values, int[] queries) {
Set<Integer> valueSet = new HashSet<>();
for (int value : values) {
valueSet.add(value);
}
boolean[] answers = new boolean[queries.length];
for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
answers[queryIndex] = valueSet.contains(queries[queryIndex]);
}
return answers;
}
}
Dry Run
Use values = [8, 2, 5, 9] and queries = [5, 7, 8].
Optimized:
- build set
{8, 2, 5, 9} - query
5-> present ->true - query
7-> absent ->false - query
8-> present ->true
Final answer: [true, false, true]
Time and Space Complexity
- Brute force:
O(nq)time,O(1)extra space - Optimized:
O(n + q)average time,O(n)extra space
Here, n = values.length and q = queries.length.
Edge Cases
- empty
values-> every answer isfalse - empty
queries-> return an empty boolean array - duplicate items in
values-> harmless because the set stores uniqueness
Common Mistakes
- solving many-query problems as if they were one-query problems
- using
ArrayList.contains, which is still linear - forgetting to define what should happen when
queriesis empty
Worked Example 3: Build a Simple Dynamic Integer Array
Problem Statement
Implement a growable integer array with these operations:
add(int value)appends a valueget(int index)returns the value at that positionsize()returns the number of stored elements
Why This Example Matters
This is the cleanest way to understand amortized analysis instead of treating it like a formula to memorize.
Constraints or Assumptions
- appends can happen many times
- indexed access should remain fast
- invalid indexes should be rejected clearly
Brute-Force Approach
Whenever the array is full and a new value arrives, create a new array of size oldLength + 1, copy all elements, then append the new value.
This makes every full append expensive, and if you do it on every append, the total cost across n appends becomes quadratic.
Better Approach
Keep a capacity and double it when the array becomes full.
Why the Better Approach Works
Resizing is still expensive when it happens, but it happens rarely. Each element is copied only a limited number of times across a long sequence of appends, so the average append cost becomes amortized O(1).
Pragmatic Java Choice
In production or interviews, use ArrayList<Integer> unless the problem explicitly asks for a manual implementation. Here, we implement it ourselves to make the complexity visible.
Java Solution
class DynamicIntArrayDemo {
static class DynamicIntArray {
private int[] data;
private int size;
DynamicIntArray() {
this.data = new int[2];
this.size = 0;
}
void add(int value) {
ensureCapacity();
data[size] = value;
size++;
}
int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return data[index];
}
int size() {
return size;
}
private void ensureCapacity() {
if (size < data.length) {
return;
}
int[] next = new int[data.length * 2];
System.arraycopy(data, 0, next, 0, data.length);
data = next;
}
}
}
Dry Run
Start with capacity 2.
- add
10-> data becomes[10, _], size1 - add
20-> data becomes[10, 20], size2 - add
30-> array is full, resize to length4, copy old values, then append ->[10, 20, 30, _], size3 - add
40->[10, 20, 30, 40], size4
One append was expensive, but not all of them were.
Time and Space Complexity
get:O(1)time,O(1)extra spaceadd: amortizedO(1)time, worst-caseO(n)when resizing happens- total stored space:
O(n)
Edge Cases
- invalid negative index -> throw exception
- index equal to size -> out of bounds
- many appends -> repeated resizing still keeps amortized append efficient
Common Mistakes
- resizing by only one slot each time
- forgetting to copy old data into the new array
- not separating
sizefromcapacity - calling amortized
O(1)the same as worst-caseO(1)
4. Complexity and Decision Guide
Across this chapter, the main trade-off is simple:
- brute force often saves memory and is easy to reason about
- optimized solutions often save time by storing extra information
Common decisions:
- choose brute force when input sizes are tiny, or when you only need one quick check and code simplicity matters most
- choose preprocessing when the same data will be queried many times
- choose hash-based structures when fast membership or counting is the bottleneck
- accept amortized analysis when the occasional expensive step is rare and predictable
Recognition signals that this chapter's techniques apply:
- the problem gives large
n, such as10^5or higher - the naive solution repeats the same scan many times
- the task needs fast lookup, uniqueness checks, or frequency counts
- the statement contains many queries on mostly fixed data
Signals not to force optimization:
nis so small thatO(n^2)is still fine and clearer- memory is tightly constrained and extra structures are too costly
- the dominant difficulty is correctness, not speed, so a simpler baseline is better first
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- counting source lines instead of actual repeated operations
- forgetting that helper structures consume extra memory
- assuming average-case performance without explaining the assumption
- using the wrong numeric type for constraints involving large sums or products
Boundary and data-handling risks:
- empty arrays and empty query lists
- index errors in manual array implementations
- stale state when reusing a set or map across multiple test cases
- hidden copying cost in resizing or string building
Short debugging checklist:
- What is the input size variable?
- Which loop or operation dominates the total work?
- Am I repeating the same lookup or computation unnecessarily?
- What extra memory am I using, and is that acceptable?
- Does the problem have many queries, updates, or both?
- Is my chosen data structure optimized for the main operation?
6. Practice Problems
Easy
- Title: Contains Duplicate
- One-line prompt: Return whether any value appears at least twice in the array.
- Expected pattern or core idea: Compare pairwise checking with
HashSetmembership.
- Title: Number of Good Pairs
- One-line prompt: Count pairs
(i, j)wherei < jandnums[i] == nums[j]. - Expected pattern or core idea: Start with nested loops, then use frequency counting.
- One-line prompt: Count pairs
- Title: Running Sum of 1D Array
- One-line prompt: Replace each position with the sum of all values up to that index.
- Expected pattern or core idea: Practice linear scans and space reasoning.
Medium
- Title: Range Sum Query - Immutable
- One-line prompt: Answer many subarray sum queries efficiently.
- Expected pattern or core idea: Recognize repeated work and preprocess once.
- Title: Design HashSet
- One-line prompt: Implement a set structure that supports add, remove, and contains.
- Expected pattern or core idea: Connect operation cost to data-structure design.
- Title: Top K Frequent Elements
- One-line prompt: Return the
kmost frequent values in the array. - Expected pattern or core idea: Frequency counting plus a structure that matches the output requirement.
- One-line prompt: Return the
Hard
- Title: First Missing Positive
- One-line prompt: Find the smallest missing positive integer in linear time and constant extra space.
- Expected pattern or core idea: Constraints force you away from naive counting structures.
- Title: Sliding Window Maximum
- One-line prompt: Return the maximum value in every window of size
k. - Expected pattern or core idea: Use complexity reasoning to reject repeated full scans.
- One-line prompt: Return the maximum value in every window of size
- Title: Median of Two Sorted Arrays
- One-line prompt: Find the median of two sorted arrays under a strict runtime target.
- Expected pattern or core idea: Read the required complexity before deciding the algorithm.
7. Short Recap
The core idea of this chapter is that correct code is only half of a solution. You also need to understand how its work and memory grow.
The most important optimization insight is to store information when recomputation is the bottleneck. A set, map, or preprocessing step often turns repeated work into one-time work.
The most important implementation warning is not to confuse average, worst, and amortized reasoning. They answer different questions.
This chapter prepares the next chapter by giving you the complexity language needed to compare array operations instead of just memorizing them.
8. Coverage Check
- 2.1 Time complexity
- 2.2 Space complexity
- 2.3 Best, average, and worst case analysis
- 2.4 Amortized analysis
- 2.5 Reading problem constraints
- 2.6 Choosing the right data structure
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 3: Arrays
3: Arrays
Goal: Build strong array problem-solving habits by teaching traversal, indexing, updates, lookup choices, rotation patterns, prefix sums, and Kadane's algorithm in a way that stays beginner-friendly but interview-relevant.
Outcome: By the end of this chapter, you can scan arrays safely, insert and delete with shifting, choose a lookup strategy based on constraints, solve common rotation and rearrangement tasks, use prefix sums for repeated range queries, and compute the maximum subarray sum with Kadane's algorithm.
1. Intuition First
An array is a row of numbered boxes. Each box has a fixed position, and that position matters as much as the value inside it. Most beginner DSA problems start here because arrays are simple to store, fast to access by index, and rich enough to express many patterns.
A simple real-world analogy is seats in a theater. Every seat has a number. You can jump directly to seat 25 if you know the index, but if you want to insert a new seat in the middle, every seat after it must shift. That is the core trade-off of arrays: indexed access is easy, but structural changes in the middle are expensive.
The core mental model is that arrays reward sequential thinking. You usually solve array problems by deciding:
- how to traverse the positions
- what state to carry while traversing
- whether you should store extra summary information
- whether the array should be modified in place or left unchanged
The most common beginner confusion point is mixing up values and indexes. Many bugs come from reading the right value from the wrong position, or from updating an index boundary incorrectly.
In the larger roadmap, arrays are the first real pattern laboratory. Prefix sums, rearrangement, and Kadane's algorithm all teach you how to reuse earlier work instead of recomputing it.
2. Core Concepts and Techniques
Concept Cluster: Traversal, Indexing, and Lookup
Key concepts in this block:
- 3.1 Traversal and indexing patterns
- 3.3 Searching and lookup strategies
Intuition
Traversal is the order in which you visit array positions. Indexing is how you refer to those positions. Searching is the process of finding a value or deciding it is absent.
Why It Matters
Almost every array solution starts with a traversal choice. A wrong loop boundary or a poor search strategy can make even simple problems fail.
How It Works
Common traversal patterns:
- left to right when earlier positions influence later ones
- right to left when shifting or suffix information matters
- two ends moving inward for symmetric checks or pair reasoning
- full scan with running state for counts, sums, or best-so-far values
Common lookup strategies:
- linear search for unsorted arrays or one-off lookups
- early stopping if the array is sorted and the current value already exceeds the target
- preprocessing or extra structures when the same lookup happens many times
Java Implementation Notes
- Use
for (int index = 0; index < values.length; index++)when you need positions. - Use enhanced for-loops only when the index itself is irrelevant.
- Guard against
values[index + 1]orvalues[index - 1]access before touching neighbors.
Common Mistakes
- starting from index
1when the problem needs index0 - reading beyond array bounds on neighbor checks
- confusing the element value with the index position
- using a slow full scan repeatedly when the problem has many lookups
Quick Example
static int findFirstIndex(int[] values, int target) {
for (int index = 0; index < values.length; index++) {
if (values[index] == target) {
return index;
}
}
return -1;
}
Debugging Tip
When an array answer is wrong, print both the index and the value at that index. Printing only the value often hides the real bug.
Advanced Note
Searching strategy depends on structure. An unsorted array and a sorted array do not invite the same approach, even if both store the same values.
Concept Cluster: Updates, Rotation, and Rearrangement
Key concepts in this block:
- 3.2 Insertion and deletion
- 3.4 Rotation and rearrangement problems
Intuition
Arrays are fixed-size blocks of contiguous storage. If you insert or delete in the middle, elements must shift. Rotation and rearrangement problems ask you to move values while preserving or intentionally changing order.
Why It Matters
This is where learners first feel the real cost of array updates. It also introduces in-place modification, which is common in interviews.
How It Works
Insertion and deletion:
- insertion at the end is easy if capacity exists
- insertion in the middle shifts elements right
- deletion in the middle shifts elements left
Rotation and rearrangement:
- repeated one-step movement is often correct but too slow
- better solutions usually exploit structure, such as reversal or careful index mapping
- many rearrangement problems become easier when you write down where each value should move
Java Implementation Notes
- Shift from right to left during insertion so you do not overwrite values you still need.
- Shift from left to right during deletion to close the gap.
- Normalize rotation count with
k %= values.lengthwhenkmay be larger than the array size.
Common Mistakes
- overwriting values during a shift
- forgetting to reduce the logical size after deletion
- not handling
k = 0orklarger than the array length - using extra arrays even when an in-place solution is possible and expected
Quick Example
static int deleteAtIndex(int[] values, int size, int deleteIndex) {
for (int index = deleteIndex; index < size - 1; index++) {
values[index] = values[index + 1];
}
return size - 1;
}
Debugging Tip
For movement problems, draw the array before and after one operation. If the first small step is wrong, the full algorithm will stay wrong.
Advanced Note
In-place rearrangement often trades simpler reasoning for better space usage. For beginner practice, correctness comes first, but you should still notice when a pattern supports constant extra space.
Concept Cluster: Prefix Sums and Maximum Subarray Thinking
Key concepts in this block:
- 3.5 Prefix sum arrays
- 3.6 Kadane's algorithm
Intuition
Prefix sums store cumulative totals so later range sums become cheap. Kadane's algorithm stores the best subarray ending at the current position so the global best can be updated in one pass.
Why It Matters
These are two early examples of the same important idea: save the right summary of earlier work, and you avoid recomputation.
How It Works
Prefix sums:
- build an array where
prefix[i]stores the sum of the firstielements - then the sum from
lefttorightbecomesprefix[right + 1] - prefix[left]
Kadane's algorithm:
- at each position, decide whether to extend the current subarray or start fresh at the current value
- keep the best running sum ending here
- keep the overall maximum seen so far
Java Implementation Notes
- Use
longfor prefix sums when values or ranges can make totals exceedint. - For Kadane's algorithm, initialize from the first element so all-negative arrays are handled correctly.
- Be explicit about whether an empty subarray is allowed. In classic maximum subarray problems, it usually is not.
Common Mistakes
- off-by-one errors when building or querying prefix sums
- rebuilding a range sum from scratch even after constructing prefix data
- resetting Kadane's running sum to zero blindly and breaking all-negative cases
- mixing subarray problems with subsequence thinking
Quick Example
static long[] buildPrefixSum(int[] values) {
long[] prefix = new long[values.length + 1];
for (int index = 0; index < values.length; index++) {
prefix[index + 1] = prefix[index] + values[index];
}
return prefix;
}
Debugging Tip
When prefix or Kadane logic fails, write the running state after each index. These techniques are simple once you can see the evolving summary.
Advanced Note
Kadane's algorithm is an early form of state compression. Later dynamic programming chapters will formalize this style of reasoning.
3. Worked Examples and Full Solutions
Worked Example 1: Rotate an Array to the Right by k Positions
Problem Statement
Given an integer array and a non-negative integer k, rotate the array to the right by k positions.
Why This Example Matters
It teaches movement cost, index normalization, and how structure can replace repeated work.
Constraints or Assumptions
0 <= k- the array may be empty
- in-place modification is preferred
Brute-Force Approach
Perform a one-step right rotation exactly k times. Each one-step rotation moves every element once.
That approach is correct, but it costs O(nk) time.
Better Approach
Use the reversal method:
- reverse the full array
- reverse the first
kelements - reverse the remaining
n - kelements
Why the Better Approach Works
Reversal changes position groups in bulk. Instead of moving elements one step at a time, it rearranges the array in three linear passes.
Pragmatic Java Choice
Use an in-place reverse helper. It keeps the code short and exposes the core pattern clearly.
Java Solution
class RotateArrayExample {
static void rotateBruteForce(int[] values, int k) {
if (values == null || values.length == 0) {
return;
}
int rotations = k % values.length;
for (int step = 0; step < rotations; step++) {
int last = values[values.length - 1];
for (int index = values.length - 1; index > 0; index--) {
values[index] = values[index - 1];
}
values[0] = last;
}
}
static void rotateOptimized(int[] values, int k) {
if (values == null || values.length == 0) {
return;
}
int rotations = k % values.length;
if (rotations == 0) {
return;
}
reverse(values, 0, values.length - 1);
reverse(values, 0, rotations - 1);
reverse(values, rotations, values.length - 1);
}
private static void reverse(int[] values, int left, int right) {
while (left < right) {
int temp = values[left];
values[left] = values[right];
values[right] = temp;
left++;
right--;
}
}
}
Dry Run
Use values = [1, 2, 3, 4, 5, 6, 7] and k = 3.
Optimized approach:
- reverse all ->
[7, 6, 5, 4, 3, 2, 1] - reverse first 3 ->
[5, 6, 7, 4, 3, 2, 1] - reverse last 4 ->
[5, 6, 7, 1, 2, 3, 4]
That is the array rotated right by 3 positions.
Time and Space Complexity
- Brute force:
O(nk)time,O(1)extra space - Optimized:
O(n)time,O(1)extra space
Edge Cases
- empty array -> do nothing
k = 0-> unchangedkis a multiple of array length -> unchanged after normalization- one-element array -> unchanged
Common Mistakes
- forgetting
k %= values.length - reversing the wrong subarray boundaries
- using left-to-right shifting and overwriting values during brute-force rotation
Worked Example 2: Answer Multiple Range Sum Queries
Problem Statement
Given an integer array and several queries [left, right], return the sum of values in each inclusive range.
Why This Example Matters
This is the classic reason prefix sums exist. It turns repeated linear work into fast queries.
Constraints or Assumptions
0 <= left <= right < values.length- many queries may be asked on the same array
- sums may exceed
int, solongis safer
Brute-Force Approach
For each query, loop from left to right and add the values.
This costs O(length of range) per query, which becomes expensive across many queries.
Better Approach
Build one prefix sum array, then answer every query with subtraction.
Why the Better Approach Works
The prefix array stores cumulative totals. The sum of a middle range is the difference between two cumulative sums.
Pragmatic Java Choice
Use a long[] prefix with length values.length + 1. The extra leading zero removes special cases for left = 0.
Java Solution
class RangeSumQueries {
static long[] answerQueriesBruteForce(int[] values, int[][] queries) {
long[] answers = new long[queries.length];
for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
int left = queries[queryIndex][0];
int right = queries[queryIndex][1];
long sum = 0;
for (int index = left; index <= right; index++) {
sum += values[index];
}
answers[queryIndex] = sum;
}
return answers;
}
static long[] answerQueriesOptimized(int[] values, int[][] queries) {
long[] prefix = new long[values.length + 1];
for (int index = 0; index < values.length; index++) {
prefix[index + 1] = prefix[index] + values[index];
}
long[] answers = new long[queries.length];
for (int queryIndex = 0; queryIndex < queries.length; queryIndex++) {
int left = queries[queryIndex][0];
int right = queries[queryIndex][1];
answers[queryIndex] = prefix[right + 1] - prefix[left];
}
return answers;
}
}
Dry Run
Use values = [4, -2, 7, 1, 3] and queries [[0, 2], [2, 4], [1, 1]].
Build prefix:
prefix[0] = 0prefix[1] = 4prefix[2] = 2prefix[3] = 9prefix[4] = 10prefix[5] = 13
Answer queries:
[0, 2]->prefix[3] - prefix[0] = 9[2, 4]->prefix[5] - prefix[2] = 11[1, 1]->prefix[2] - prefix[1] = -2
Time and Space Complexity
- Brute force:
O(q * n)in the worst case,O(1)extra space - Optimized:
O(n + q)time,O(n)extra space
Edge Cases
- empty query list -> return an empty answer array
- single-element ranges -> still work with the same formula
- negative numbers -> prefix sums still work correctly
Common Mistakes
- forgetting the extra leading zero in the prefix array
- using
prefix[right] - prefix[left]instead ofprefix[right + 1] - prefix[left] - storing large cumulative sums in
int
Worked Example 3: Maximum Subarray Sum
Problem Statement
Given an integer array, return the maximum possible sum of a non-empty contiguous subarray.
Why This Example Matters
Kadane's algorithm is one of the first important "one-pass state" techniques in DSA. It rewards understanding over memorization.
Constraints or Assumptions
- the array is non-empty
- values may be positive, zero, or negative
- the subarray must be contiguous
Brute-Force Approach
Try every possible start index. For each start, extend the end index and track the running sum. Keep the best sum seen.
This is O(n^2) time.
Better Approach
Use Kadane's algorithm. At each position, decide whether the best subarray ending here should extend the previous one or start fresh at the current element.
Why the Better Approach Works
If the previous running sum is negative, carrying it forward only makes the new subarray worse. If it is positive, extending it helps. That local decision is enough to build the global answer.
Pragmatic Java Choice
Use two variables:
currentBestEndingHereglobalBest
This keeps the logic readable and handles all-negative arrays when initialized from the first value.
Java Solution
class MaximumSubarrayExample {
static int maxSubarrayBruteForce(int[] values) {
int best = values[0];
for (int start = 0; start < values.length; start++) {
int runningSum = 0;
for (int end = start; end < values.length; end++) {
runningSum += values[end];
best = Math.max(best, runningSum);
}
}
return best;
}
static int maxSubarrayKadane(int[] values) {
int currentBestEndingHere = values[0];
int globalBest = values[0];
for (int index = 1; index < values.length; index++) {
currentBestEndingHere = Math.max(values[index], currentBestEndingHere + values[index]);
globalBest = Math.max(globalBest, currentBestEndingHere);
}
return globalBest;
}
}
Dry Run
Use values = [-2, 1, -3, 4, -1, 2, 1, -5, 4].
Kadane's algorithm:
- start:
current = -2,best = -2 - index 1 value
1:current = max(1, -1) = 1,best = 1 - index 2 value
-3:current = max(-3, -2) = -2,best = 1 - index 3 value
4:current = max(4, 2) = 4,best = 4 - index 4 value
-1:current = 3,best = 4 - index 5 value
2:current = 5,best = 5 - index 6 value
1:current = 6,best = 6 - index 7 value
-5:current = 1,best = 6 - index 8 value
4:current = 5,best = 6
Final answer: 6, from subarray [4, -1, 2, 1].
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Kadane's algorithm:
O(n)time,O(1)extra space
Edge Cases
- all-negative array -> answer is the largest single element
- single-element array -> that element is the answer
- zeros mixed with negatives -> zero may be the best answer
Common Mistakes
- resetting the running sum to zero without handling all-negative arrays
- confusing subarray with subsequence
- thinking Kadane's algorithm works by magic instead of by the "extend or restart" rule
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- traversal is usually
O(n)and should be your default baseline - insertion and deletion in the middle are
O(n)because shifting is unavoidable in arrays - repeated one-step rotation is often correct but too slow for large
k - prefix sums trade
O(n)extra space for much faster repeated range queries - Kadane's algorithm reduces maximum subarray search from quadratic to linear time without extra arrays
Choose the simpler approach when:
- there is only one query and the array is small
- code clarity matters more than a small constant-factor improvement
- the optimized approach adds complexity without changing feasibility
Choose the optimized approach when:
- there are many queries on the same array
- repeated movement or repeated summation is the bottleneck
- the input size makes quadratic behavior unsafe
Recognition signals for array techniques:
- the problem is index-based and contiguous order matters
- you need fast random access to positions
- the operation can be expressed as a left-to-right or right-to-left pass
Signals not to force arrays alone:
- you need fast insertion and deletion in the middle over and over
- you mainly need key-based lookup instead of positional access
- the problem is really about dynamic window state, hashing, or trees, which later chapters handle better
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- off-by-one errors in loop boundaries
- using the wrong start or end index in neighbor checks
- overwriting values during shifting or reversal
- forgetting whether the solution should modify the array in place
Boundary-condition handling:
- empty arrays
- one-element arrays
- rotation counts larger than array size
- range queries where
leftequalsright - all-negative inputs for maximum subarray problems
Stale-state and indexing risks:
- not resetting a running sum or counter between attempts
- reusing arrays without understanding their current logical size
- mixing inclusive and exclusive index boundaries in prefix sum formulas
Short debugging checklist:
- What does each index represent right now?
- Should the current loop include the last position or stop before it?
- Am I reading old data or data I already overwrote?
- Can I write the running state after each step on paper?
- Is this problem asking for one answer or many repeated queries?
6. Practice Problems
Easy
- Title: Remove Duplicates from Sorted Array
- One-line prompt: Compact a sorted array in place so each distinct value appears once.
- Expected pattern or core idea: Safe traversal, write index, and in-place updates.
- Title: Best Time to Buy and Sell Stock
- One-line prompt: Find the maximum profit from one buy and one sell.
- Expected pattern or core idea: One-pass tracking of the minimum seen so far.
- Title: Find Pivot Index
- One-line prompt: Return an index where the left sum equals the right sum.
- Expected pattern or core idea: Prefix-style sum reasoning without repeated scans.
Medium
- Title: Rotate Array
- One-line prompt: Rotate an array by
ksteps under realistic input sizes. - Expected pattern or core idea: Compare repeated shifts with reversal or extra-array methods.
- One-line prompt: Rotate an array by
- Title: Product of Array Except Self
- One-line prompt: Build each answer from all elements except the current one without division.
- Expected pattern or core idea: Prefix and suffix accumulation.
- Title: Maximum Product Subarray
- One-line prompt: Return the largest product among all contiguous subarrays.
- Expected pattern or core idea: One-pass state tracking with sign-sensitive updates.
Hard
- Title: First Missing Positive
- One-line prompt: Find the smallest missing positive value in linear time and constant extra space.
- Expected pattern or core idea: In-place index placement and careful boundary handling.
- Title: Trapping Rain Water
- One-line prompt: Compute how much water can be trapped between bars.
- Expected pattern or core idea: Array summaries, two-sided information, and movement reasoning.
- Title: Maximum Sum Circular Subarray
- One-line prompt: Find the best contiguous subarray sum when the array is circular.
- Expected pattern or core idea: Extend Kadane-style thinking to wraparound cases.
7. Short Recap
The core idea of this chapter is that arrays are simple in structure but rich in patterns. Good array solutions come from careful traversal, correct indexing, and awareness of movement cost.
The most important optimization insight is to save the right summary. Prefix sums answer repeated range queries quickly, and Kadane's algorithm keeps only the best running state needed for maximum subarray problems.
The most important implementation warning is to treat indexes precisely. Most array bugs come from boundaries, shifting, or mixing positions with values.
This chapter prepares the next chapter by carrying the same traversal discipline into strings, where characters replace numeric values but the indexing risks remain.
8. Coverage Check
- 3.1 Traversal and indexing patterns
- 3.2 Insertion and deletion
- 3.3 Searching and lookup strategies
- 3.4 Rotation and rearrangement problems
- 3.5 Prefix sum arrays
- 3.6 Kadane's algorithm
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 4: Strings
4: Strings
Goal: Teach learners how to reason about strings as indexed character sequences, handle traversal and counting safely, distinguish substrings from subsequences, solve basic palindrome tasks, and build efficient string solutions in Java.
Outcome: By the end of this chapter, you can work with String and char[] confidently, count character frequencies, explain the difference between substrings and subsequences, solve common palindrome checks, use StringBuilder when repeated updates are needed, and recognize several core interview-style string patterns.
1. Intuition First
Strings are arrays of meaning. Instead of storing just numbers, they store ordered characters that combine into words, identifiers, patterns, and encoded information. That makes them one of the most common interview data types.
A simple real-world analogy is a train of labeled carriages. Each carriage holds one character, and the order matters. If you change or remove one carriage, the full message may change. That is why string problems are usually about order, grouping, comparison, or transformation.
The core mental model is this: a string problem is usually an indexing problem in disguise. You solve it by deciding where to start, where to stop, what state to carry, and whether you should inspect, count, compare, or rebuild characters.
The most common beginner confusion point is forgetting that Java String objects are immutable. You can read characters easily, but you cannot edit a string in place. If you need repeated modifications, you usually want StringBuilder or a character array.
In the roadmap, this chapter turns raw indexing skill into text-processing skill. It prepares you for hashing, sliding windows, and more advanced pattern matching later.
2. Core Concepts and Techniques
Concept Cluster: String Basics, Character Arrays, and Frequency Counting
Key concepts in this block:
- 4.1 Character arrays and string fundamentals
- 4.2 String traversal and frequency counting
Intuition
A Java String is an immutable sequence of characters. A char[] is a mutable array of characters. Traversal means visiting characters in order. Frequency counting means recording how often each character appears.
Why It Matters
Many string problems are just careful traversal plus a good summary structure. If you understand what can and cannot be modified directly, your code becomes much safer.
How It Works
Core facts:
text.charAt(index)reads one charactertext.length()returns the number of characterstext.toCharArray()creates a mutable character array copyStringdoes not support in-place updates
Frequency counting choices:
- use
int[26]when the problem guarantees lowercase English letters - use
int[128]orint[256]for small fixed ASCII ranges - use a
HashMap<Character, Integer>when the character set is not small or fixed
Java Implementation Notes
- Compare strings with
.equals(), not==. - Use indexed loops when position matters.
- Convert to
char[]only when mutation or repeated access patterns make it useful.
Common Mistakes
- using
==to compare string contents - assuming
Stringcan be changed in place - using a fixed-size frequency array when the input may contain characters outside that range
- forgetting to normalize case when the problem says case should be ignored
Quick Example
static int[] lowercaseFrequency(String text) {
int[] frequency = new int[26];
for (int index = 0; index < text.length(); index++) {
char current = text.charAt(index);
frequency[current - 'a']++;
}
return frequency;
}
Debugging Tip
When character counting looks wrong, print the index, the character, and the bucket being updated. That usually reveals case or range assumptions immediately.
Advanced Note
Choosing a frequency array instead of a map is an early example of using problem constraints to simplify both code and complexity.
Concept Cluster: Substrings, Subsequences, and Palindromes
Key concepts in this block:
- 4.3 Substrings and subsequences
- 4.4 Palindrome problems
Intuition
A substring is a contiguous block of characters. A subsequence preserves order but can skip characters. A palindrome reads the same forward and backward.
Why It Matters
These definitions control the entire solution. Many beginner mistakes happen because a problem asks for a subsequence and the learner accidentally thinks in substrings, or because a palindrome problem is solved with unnecessary rebuilding.
How It Works
Key distinctions:
- substring: characters stay together without gaps
- subsequence: characters stay in order but may have gaps
- palindrome: compare symmetric positions from the ends inward
Common approaches:
- use
substring(left, rightExclusive)when you explicitly need a contiguous piece - use a scan over two strings to test subsequence relationships
- use either reverse-and-compare or inward comparison for palindrome checks
Java Implementation Notes
substring(begin, end)includesbeginand excludesend.- Be precise about inclusive and exclusive boundaries.
- For palindrome checks that ignore punctuation or case, normalize consistently before comparing.
Common Mistakes
- thinking substring and subsequence mean the same thing
- off-by-one errors with
substring - comparing raw characters when the problem says to ignore case or symbols
- building too many temporary strings inside loops
Quick Example
static boolean isSubsequence(String small, String large) {
int smallIndex = 0;
int largeIndex = 0;
while (smallIndex < small.length() && largeIndex < large.length()) {
if (small.charAt(smallIndex) == large.charAt(largeIndex)) {
smallIndex++;
}
largeIndex++;
}
return smallIndex == small.length();
}
Debugging Tip
For substring or palindrome bugs, write the exact left and right boundaries on paper. Most errors come from boundary interpretation, not from the comparison itself.
Advanced Note
Many advanced string algorithms are still built on these same definitions. If substring and subsequence are not stable concepts yet, harder string topics become confusing very quickly.
Concept Cluster: StringBuilder and Interview Workflows
Key concepts in this block:
- 4.5 StringBuilder and mutable string workflows
- 4.6 Common interview string patterns
Intuition
StringBuilder is a mutable buffer for text. It lets you append, delete, reverse, and edit characters without creating a new String on every change.
Why It Matters
Repeated string concatenation inside loops can quietly become expensive. StringBuilder is the standard Java tool for efficient incremental string construction.
How It Works
Useful interview string patterns:
- normalize input first if case, spaces, or punctuation should be ignored
- count characters when equality or grouping depends on composition
- compare from both ends for palindrome-style questions
- build the final answer incrementally with
StringBuilder - parse one character at a time when tokens or groups matter
Java Implementation Notes
builder.append(...)is usually the main operation.builder.reverse()is useful when reversal is the final goal.builder.length()tells you whether to insert separators such as spaces or commas.
Common Mistakes
- using
result = result + nextPartinside a long loop - forgetting that
StringBuilderitself is mutable and may need clearing between test cases - appending separators in the wrong place and then trimming awkwardly later
- treating a parsing problem as a one-line library trick before understanding the character rules
Quick Example
static String normalizeLettersOnly(String text) {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < text.length(); index++) {
char current = text.charAt(index);
if (Character.isLetter(current)) {
builder.append(Character.toLowerCase(current));
}
}
return builder.toString();
}
Debugging Tip
If the built string is almost correct but formatting is off, print the builder state after each append. Separator bugs usually become obvious immediately.
Advanced Note
Efficient string building is often the difference between a clean linear solution and a slower solution with hidden quadratic behavior.
3. Worked Examples and Full Solutions
Worked Example 1: Check Whether Two Strings Are Anagrams
Problem Statement
Given two strings first and second, return true if one string is an anagram of the other. Assume the strings contain only lowercase English letters.
Why This Example Matters
It is one of the clearest demonstrations of how frequency counting beats repeated or heavier comparison work.
Constraints or Assumptions
- both strings contain only lowercase English letters
- order does not matter, but character counts must match exactly
- equal lengths are required
Brute-Force Approach
Convert both strings to character arrays, sort them, and compare the sorted arrays.
This works because anagrams have the same characters after sorting, but sorting costs O(n log n) time.
Better Approach
Use a frequency array of size 26. Count characters from the first string and subtract characters from the second.
Why the Better Approach Works
An anagram condition is really a frequency equality condition. Sorting proves that indirectly. Counting proves it directly.
Pragmatic Java Choice
For lowercase English letters, int[26] is simpler and faster than a HashMap<Character, Integer>.
Java Solution
import java.util.Arrays;
class ValidAnagramExample {
static boolean isAnagramBruteForce(String first, String second) {
if (first.length() != second.length()) {
return false;
}
char[] left = first.toCharArray();
char[] right = second.toCharArray();
Arrays.sort(left);
Arrays.sort(right);
return Arrays.equals(left, right);
}
static boolean isAnagramOptimized(String first, String second) {
if (first.length() != second.length()) {
return false;
}
int[] frequency = new int[26];
for (int index = 0; index < first.length(); index++) {
frequency[first.charAt(index) - 'a']++;
frequency[second.charAt(index) - 'a']--;
}
for (int count : frequency) {
if (count != 0) {
return false;
}
}
return true;
}
}
Dry Run
Use first = "listen" and second = "silent".
Optimized approach:
- count
listen-> buckets forl, i, s, t, e, nincrease - subtract
silent-> the same buckets decrease back to zero - every frequency entry ends at zero -> return
true
Time and Space Complexity
- Brute force:
O(n log n)time,O(n)extra space for sorted arrays - Optimized:
O(n)time,O(1)extra space because the frequency array size is fixed
Edge Cases
- different lengths -> immediately
false - both empty strings ->
true - repeated characters -> handled by counts naturally
Common Mistakes
- forgetting the equal-length check
- using a 26-size array when the input is not guaranteed to be lowercase English letters
- sorting strings repeatedly inside a loop instead of once
Worked Example 2: Valid Palindrome Ignoring Case and Symbols
Problem Statement
Given a string, return true if it reads the same forward and backward after ignoring non-alphanumeric characters and letter case.
Why This Example Matters
It teaches normalization, boundary movement, and a very common interview comparison pattern.
Constraints or Assumptions
- letters, digits, spaces, and punctuation may all appear
- comparison should ignore non-alphanumeric characters
- comparison should ignore case
Brute-Force Approach
Build a cleaned lowercase string containing only alphanumeric characters. Reverse that cleaned string and compare it with the original cleaned string.
This is correct, but it builds extra strings.
Better Approach
Use two indexes, one from the left and one from the right. Skip non-alphanumeric characters on both sides and compare lowercase characters directly.
Why the Better Approach Works
Palindrome logic only needs symmetric comparison. Once both pointers land on valid comparable characters, you can decide immediately whether the string remains a candidate.
Pragmatic Java Choice
Use Character.isLetterOrDigit and Character.toLowerCase so the code stays clear and handles letters and digits correctly.
Java Solution
class ValidPalindromeExample {
static boolean isPalindromeBruteForce(String text) {
StringBuilder cleaned = new StringBuilder();
for (int index = 0; index < text.length(); index++) {
char current = text.charAt(index);
if (Character.isLetterOrDigit(current)) {
cleaned.append(Character.toLowerCase(current));
}
}
String normalized = cleaned.toString();
String reversed = cleaned.reverse().toString();
return normalized.equals(reversed);
}
static boolean isPalindromeOptimized(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(text.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(text.charAt(right))) {
right--;
}
char leftChar = Character.toLowerCase(text.charAt(left));
char rightChar = Character.toLowerCase(text.charAt(right));
if (leftChar != rightChar) {
return false;
}
left++;
right--;
}
return true;
}
}
Dry Run
Use text = "A man, a plan, a canal: Panama".
Optimized approach:
- left
A, righta-> equal after lowercase - skip spaces and punctuation until left
m, rightm - continue inward with matching pairs
- no mismatch appears -> return
true
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Optimized:
O(n)time,O(1)extra space
Edge Cases
- empty string ->
true - string with only punctuation ->
trueafter ignoring all symbols - mixed digits and letters -> digits compare normally
Common Mistakes
- comparing raw characters without lowercasing
- forgetting to skip symbols on one side or both
- thinking an empty cleaned string should be
false
Worked Example 3: Reverse Words in a Sentence
Problem Statement
Given a string that may contain leading, trailing, or repeated spaces, return a new string with the words in reverse order and exactly one space between words.
Why This Example Matters
This is a practical StringBuilder problem. It also shows how interview string tasks often combine parsing and formatting rules.
Constraints or Assumptions
- words are separated by spaces
- the output should not contain leading or trailing spaces
- multiple spaces between words should collapse to one space in the result
Brute-Force Approach
Split the trimmed string into words and rebuild the answer using repeated string concatenation with +.
This is easy to write, but repeated concatenation inside a loop creates many temporary strings.
Better Approach
Scan from the end of the string, locate each word boundary, and append each word to a StringBuilder.
Why the Better Approach Works
The scan processes each character a small number of times and builds the output incrementally without repeated full-string copying.
Pragmatic Java Choice
Use StringBuilder because the output is assembled piece by piece.
Java Solution
class ReverseWordsExample {
static String reverseWordsBruteForce(String text) {
String trimmed = text.trim();
if (trimmed.isEmpty()) {
return "";
}
String[] words = trimmed.split("\\s+");
String result = "";
for (int index = words.length - 1; index >= 0; index--) {
result += words[index];
if (index > 0) {
result += " ";
}
}
return result;
}
static String reverseWordsOptimized(String text) {
StringBuilder builder = new StringBuilder();
int end = text.length() - 1;
while (end >= 0) {
while (end >= 0 && text.charAt(end) == ' ') {
end--;
}
if (end < 0) {
break;
}
int start = end;
while (start >= 0 && text.charAt(start) != ' ') {
start--;
}
if (builder.length() > 0) {
builder.append(' ');
}
builder.append(text, start + 1, end + 1);
end = start - 1;
}
return builder.toString();
}
}
Dry Run
Use text = " the sky is blue ".
Optimized approach:
- skip trailing spaces
- find word
blue, append ->"blue" - find word
is, append ->"blue is" - find word
sky, append ->"blue is sky" - find word
the, append ->"blue is sky the"
Time and Space Complexity
- Brute force: often
O(n^2)total time because of repeated concatenation, plus split storage - Optimized:
O(n)time,O(n)extra space for the output builder
Edge Cases
- all spaces -> return empty string
- one word only -> unchanged except trimming
- repeated internal spaces -> collapse to one space in the output
Common Mistakes
- forgetting to trim or skip extra spaces
- appending an extra space at the front or end
- using repeated
+concatenation in a long loop and hiding the real cost
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- simple traversal is usually
O(n)and should be your default baseline - sorting-based string comparison often costs
O(n log n) - frequency counting can reduce many comparison problems to
O(n) - reverse-and-compare palindrome solutions are simple but often use extra memory
StringBuilderavoids the hidden repeated-copy cost of string concatenation in loops
Choose the simpler approach when:
- the input is small and clarity matters most
- the one-off transformation is easy to reason about with a cleaned copy
- extra memory is acceptable and improves readability
Choose the optimized approach when:
- you are traversing large strings
- the solution builds or edits the result repeatedly
- the same comparison can be expressed through fixed-size counting
Recognition signals for string techniques:
- order of characters matters
- case or punctuation rules affect comparison
- the task asks for counting, grouping, or equivalence
- the answer is itself another string that must be built incrementally
Signals not to force these techniques:
- the problem is mainly about key-based counting across many items, where hashing may fit better
- the solution requires window movement or advanced pattern search, which later chapters handle directly
- you are using substring creation heavily when a simple index range would be enough
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- off-by-one errors in string boundaries
- assuming a string can be modified directly
- forgetting to normalize case, spaces, or symbols when the problem requires it
- using the wrong frequency structure for the character set
Null, empty, and boundary-condition handling:
- empty strings
- strings made only of spaces or punctuation
- single-character strings
- mismatched lengths in comparison problems
Stale-state and mutation risks:
- reusing a
StringBuilderwithout clearing it - reversing a builder and forgetting it has changed permanently
- mixing cleaned and original indexes in the same logic
Short debugging checklist:
- What does each index point to right now?
- Am I treating substring and subsequence as different concepts?
- Did I normalize exactly what the problem says to ignore?
- Am I building the answer efficiently or recreating many temporary strings?
- Does my frequency structure match the character set assumptions?
6. Practice Problems
Easy
- Title: Valid Anagram
- One-line prompt: Decide whether two strings contain the same characters with the same counts.
- Expected pattern or core idea: Sorting baseline versus frequency counting.
- Title: Is Subsequence
- One-line prompt: Return whether one string appears in another in order, but not necessarily contiguously.
- Expected pattern or core idea: Separate substring thinking from subsequence thinking and scan carefully.
- Title: Longest Common Prefix
- One-line prompt: Find the longest prefix shared by all strings in an array.
- Expected pattern or core idea: Character-by-character comparison with early stopping.
Medium
- Title: Group Anagrams
- One-line prompt: Group strings that are anagrams of each other.
- Expected pattern or core idea: Use normalized representations and frequency signatures.
- Title: Longest Palindromic Substring
- One-line prompt: Return the longest contiguous palindrome in the string.
- Expected pattern or core idea: Palindrome expansion and careful boundary movement.
- Title: Reverse Words in a String
- One-line prompt: Reverse the word order while cleaning up spaces.
- Expected pattern or core idea: Parsing plus efficient output construction.
Hard
- Title: Minimum Window Substring
- One-line prompt: Find the smallest substring that contains all characters of another string.
- Expected pattern or core idea: Frequency counting combined with dynamic window state.
- Title: Palindrome Partitioning II
- One-line prompt: Split a string into palindromic pieces using the fewest cuts.
- Expected pattern or core idea: Build on palindrome recognition and later dynamic programming ideas.
- Title: Regular Expression Matching
- One-line prompt: Match a string against a pattern containing
.and*. - Expected pattern or core idea: Careful state reasoning and formal recurrence design.
- One-line prompt: Match a string against a pattern containing
7. Short Recap
The core idea of this chapter is that string problems become much easier when you treat a string as an indexed sequence of characters and choose the right representation for the job.
The most important optimization insight is that counting and StringBuilder often remove unnecessary work. Many string problems do not need repeated sorting or repeated concatenation.
The most important implementation warning is to be precise about immutability, boundaries, and normalization rules.
This chapter prepares the next chapter by turning character counting and lookup intuition into the hashing mindset used throughout DSA.
8. Coverage Check
- 4.1 Character arrays and string fundamentals
- 4.2 String traversal and frequency counting
- 4.3 Substrings and subsequences
- 4.4 Palindrome problems
- 4.5 StringBuilder and mutable string workflows
- 4.6 Common interview string patterns
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 5: Hashing
5: Hashing
Goal: Teach learners how to use hashing for fast lookup, membership checks, frequency counting, and custom key design in Java.
Outcome: By the end of this chapter, you can choose between HashMap and HashSet, replace many nested-loop lookups with average O(1) operations, explain what collisions mean, and write correct equals() and hashCode() methods for custom keys.
1. Intuition First
Hashing is a shortcut system. Instead of scanning every item until you find what you want, you compute a key and jump near the answer immediately.
A simple real-world analogy is a library locker wall. If every book request required checking lockers one by one, retrieval would be slow. A hash function is the rule that tells you which locker area to check first. It is not magic. It is structured guessing backed by a fast data structure.
The core mental model is this: hashing trades ordered storage for fast access by key. A HashMap answers "what value belongs to this key?" A HashSet answers "have I seen this value before?" Many brute-force solutions become much faster once repeated searching is replaced by remembered lookup state.
The most common beginner confusion point is thinking hashing gives guaranteed O(1) time in every case. In practice, Java hash-based collections are designed for average-case constant-time work, but collisions and poor key design still matter.
In the larger roadmap, hashing is the first chapter where preprocessing and remembered state start to beat straightforward scanning in a consistent way. That idea returns in sliding windows, prefix sums with maps, graph visitation, and dynamic programming memoization.
2. Core Concepts and Techniques
Concept Cluster: Hash-Based Lookup Containers
Key concepts in this block:
- 5.1 HashMap fundamentals
- 5.2 HashSet fundamentals
Intuition
A HashMap stores pairs. A HashSet stores unique values. Both are built for fast access by hashing the incoming key or value.
Why It Matters
Many beginner solutions use a nested loop only because the program forgets what it has already seen. Hash-based containers fix that by remembering answers from earlier work.
How It Works
Use HashMap<K, V> when you need:
- counts
- indexes
- groups
- any mapping from one piece of information to another
Use HashSet<E> when you need:
- uniqueness
- fast membership checks
- deduplication
- quick detection of repeats
Common operations:
- map insert/update:
put(key, value) - map lookup:
get(key)orgetOrDefault(key, fallback) - map membership:
containsKey(key) - set insert:
add(value) - set membership:
contains(value)
Java Implementation Notes
- Prefer
getOrDefaultfor counting patterns. HashSet.add(value)returnsfalseif the value was already present.- Hash-based collections do not preserve sorted order.
- If you need insertion order, that is a different container choice and a different trade-off.
Common Mistakes
- using a
HashMapwhen only uniqueness is needed - using a
HashSetwhen counts are needed - assuming iteration order means anything stable
- forgetting that primitive values such as
intare stored through wrapper types likeInteger
Quick Example
import java.util.HashSet;
class ContainsDuplicateQuickExample {
static boolean containsDuplicate(int[] values) {
HashSet<Integer> seen = new HashSet<>();
for (int value : values) {
if (!seen.add(value)) {
return true;
}
}
return false;
}
}
Debugging Tip
If a hash-based solution looks wrong, print the map or set after each update. Many bugs come from updating the structure at the wrong time, not from the collection itself.
Advanced Note
Hashing is usually about average-case speed. When a problem also requires sorted order or minimum and maximum queries, a hash-based collection may not be the right tool.
Concept Cluster: Frequency Maps and Collision Thinking
Key concepts in this block:
- 5.3 Frequency maps and counting patterns
- 5.4 Collision handling basics
Intuition
A frequency map is a ledger. Every time a value appears, its count increases. A collision happens when different keys land in the same internal bucket area.
Why It Matters
Frequency counting is one of the most reusable DSA patterns. Collisions matter because they explain why hashing is fast in practice but still based on careful internal structure.
How It Works
Frequency map pattern:
- if a key has not appeared, treat its count as
0 - increment by
1 - store the updated result back in the map
Collision basics:
- Java hashes a key into an integer
- internal bucket selection uses that hash
- two different keys may map to the same bucket area
- collisions do not break correctness because Java still uses equality checks to distinguish keys
The key lesson is that equal keys must have equal hash codes, but different keys may still share a hash bucket.
Java Implementation Notes
frequency.put(key, frequency.getOrDefault(key, 0) + 1)is the standard counting line.- Never rely on hash code uniqueness.
- Avoid mutable objects as hash keys unless you are certain the fields used by
equals()andhashCode()will never change while the object sits inside the collection.
Common Mistakes
- treating collisions as errors instead of normal behavior
- assuming unequal objects must have different hash codes
- mutating a key after inserting it into a map or set
- recomputing counts with repeated scans instead of storing them once
Quick Example
import java.util.HashMap;
import java.util.Map;
class FrequencyQuickExample {
static Map<String, Integer> countWords(String[] words) {
Map<String, Integer> frequency = new HashMap<>();
for (String word : words) {
frequency.put(word, frequency.getOrDefault(word, 0) + 1);
}
return frequency;
}
}
Debugging Tip
When counts are wrong, inspect the exact key string or value being used. Hidden whitespace, case differences, or premature normalization errors are common causes.
Advanced Note
Collision handling affects performance, but equality rules affect correctness. If equality is wrong, the collection can behave incorrectly even when hashing looks fast.
Concept Cluster: Custom Hashing and Equality in Java
Key concepts in this block:
- 5.5 Custom hashing and equality in Java
Intuition
For custom objects, Java needs two answers:
- when should two objects be treated as logically equal?
- how should they be placed into hash buckets?
Why It Matters
If you store custom objects in a HashSet or use them as HashMap keys without correct equality rules, duplicates may not be recognized and lookups may fail unexpectedly.
How It Works
The core contract is:
- if
a.equals(b)istrue, thena.hashCode()must equalb.hashCode() - if two objects are unequal, their hash codes may still be the same
For value-style objects, define equality using the fields that identify the object logically.
Java Implementation Notes
- Override both
equals()andhashCode()together. - Use
instanceofor exact-class checks consistently. Objects.hash(...)is simple and readable for beginner code.- Java 17 records generate value-based equality automatically, but writing the methods manually once is still important for understanding.
Common Mistakes
- overriding
equals()but nothashCode() - comparing fields that should not define logical identity
- using mutable fields inside the hash definition and then changing them later
- confusing object identity with logical equality
Quick Example
import java.util.Objects;
class Point {
private final int row;
private final int column;
Point(int row, int column) {
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Point point)) {
return false;
}
return row == point.row && column == point.column;
}
@Override
public int hashCode() {
return Objects.hash(row, column);
}
}
Debugging Tip
If a HashSet seems to contain duplicates of a custom object, print both equals() results and hash codes for the suspicious values.
Advanced Note
Good equality rules are part of data modeling, not just syntax. Poorly chosen identity fields create bugs that hashing merely exposes.
3. Worked Examples and Full Solutions
Worked Example 1: First Non-Repeating Integer
Problem Statement
Given an integer array, return the first value that appears exactly once. If no such value exists, return -1.
Why This Example Matters
It shows the most common beginner hashing pattern: count first, answer second.
Constraints or Assumptions
- the array may contain duplicates
- order matters because the answer is the first unique value by original position
- negative numbers are allowed
Brute-Force Approach
For each element, scan the full array again and count how many times it appears. Return the first element whose count is 1.
This works, but it costs O(n^2) time because every element triggers another full scan.
Better Approach
Build a frequency map in one pass, then scan the array a second time and return the first value whose count is 1.
Why the Better Approach Works
The first pass stores all repeated information once. The second pass preserves original order while using constant-time average lookup for the count.
Pragmatic Java Choice
Use HashMap<Integer, Integer> because the problem is explicitly about value-to-count mapping.
Java Solution
import java.util.HashMap;
import java.util.Map;
class FirstNonRepeatingIntegerExample {
static int firstNonRepeatingBruteForce(int[] values) {
for (int value : values) {
int count = 0;
for (int candidate : values) {
if (candidate == value) {
count++;
}
}
if (count == 1) {
return value;
}
}
return -1;
}
static int firstNonRepeatingOptimized(int[] values) {
Map<Integer, Integer> frequency = new HashMap<>();
for (int value : values) {
frequency.put(value, frequency.getOrDefault(value, 0) + 1);
}
for (int value : values) {
if (frequency.get(value) == 1) {
return value;
}
}
return -1;
}
}
Dry Run
Use values = [4, 5, 1, 2, 1, 2, 4].
Optimized approach:
- first pass builds
{4=2, 5=1, 1=2, 2=2} - second pass checks
4-> count2 - checks
5-> count1 - return
5
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach: average
O(n)time,O(n)extra space
Edge Cases
- empty array -> return
-1 - all values repeated -> return
-1 - first element already unique -> return it immediately in the second pass
Common Mistakes
- returning the smallest unique value instead of the first unique by position
- counting correctly but iterating over map keys instead of the original array order
- using a set when counts are actually needed
Worked Example 2: Longest Consecutive Sequence
Problem Statement
Given an unsorted integer array, return the length of the longest run of consecutive integers.
Why This Example Matters
It demonstrates why HashSet is not just for duplicate detection. It can also support fast expansion from carefully chosen starting points.
Constraints or Assumptions
- input may be unsorted
- duplicates may exist
- the answer depends on values, not original positions
Brute-Force Approach
Sort the array and then scan to measure the longest consecutive run.
This is much better than a naive nested search, but sorting still costs O(n log n) time.
Better Approach
Insert all unique values into a HashSet. Start a run only from numbers that do not have a predecessor value - 1. Then extend forward while the next consecutive value exists.
Why the Better Approach Works
Every consecutive chain has exactly one true start: the first value whose predecessor is absent. By only expanding from starts, the algorithm avoids redundant work.
Pragmatic Java Choice
Use HashSet<Integer> because the task is pure membership checking.
Java Solution
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
class LongestConsecutiveSequenceExample {
static int longestConsecutiveBruteForce(int[] values) {
if (values.length == 0) {
return 0;
}
int[] copy = Arrays.copyOf(values, values.length);
Arrays.sort(copy);
int best = 1;
int current = 1;
for (int index = 1; index < copy.length; index++) {
if (copy[index] == copy[index - 1]) {
continue;
}
if (copy[index] == copy[index - 1] + 1) {
current++;
} else {
current = 1;
}
best = Math.max(best, current);
}
return best;
}
static int longestConsecutiveOptimized(int[] values) {
Set<Integer> present = new HashSet<>();
for (int value : values) {
present.add(value);
}
int best = 0;
for (int value : present) {
if (present.contains(value - 1)) {
continue;
}
int currentLength = 1;
int currentValue = value;
while (present.contains(currentValue + 1)) {
currentValue++;
currentLength++;
}
best = Math.max(best, currentLength);
}
return best;
}
}
Dry Run
Use values = [100, 4, 200, 1, 3, 2].
Optimized approach:
- set becomes
{100, 4, 200, 1, 3, 2} 100has no predecessor99, run length is14has predecessor3, so skip as a start200has no predecessor199, run length is11has no predecessor0, expand to2,3,4- best becomes
4
Time and Space Complexity
- Brute force:
O(n log n)time,O(n)extra space for the copy - Better approach: average
O(n)time,O(n)extra space
Edge Cases
- empty array ->
0 - all duplicates ->
1 - negative values work exactly the same way
Common Mistakes
- starting a scan from every value instead of only true sequence starts
- forgetting to skip duplicates in the sorting approach
- using a map when simple membership is enough
Worked Example 3: Count Unique Grid Points with a Custom Key
Problem Statement
Given a list of integer coordinate pairs, return how many distinct points appear.
Why This Example Matters
It is the clearest beginner example of why custom classes need correct equality and hashing rules when used inside a HashSet.
Constraints or Assumptions
- points are defined only by
(row, column) - duplicate coordinates should count once
- point order does not matter
Brute-Force Approach
For each point, scan all earlier points and check whether the same coordinates already appeared.
This works, but duplicate detection costs O(n^2) time.
Better Approach
Create a Point class with correct equals() and hashCode(), insert every point into a HashSet<Point>, and return the set size.
Why the Better Approach Works
The set delegates duplicate detection to the custom equality rules. Once logical identity is defined correctly, insertion and membership are fast on average.
Pragmatic Java Choice
Manual equals() and hashCode() are better here than a string-encoding shortcut because they teach the actual Java rule behind custom hashing.
Java Solution
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class DistinctPointsExample {
static final class Point {
private final int row;
private final int column;
Point(int row, int column) {
this.row = row;
this.column = column;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Point point)) {
return false;
}
return row == point.row && column == point.column;
}
@Override
public int hashCode() {
return Objects.hash(row, column);
}
}
static int countDistinctBruteForce(int[][] coordinates) {
int distinct = 0;
for (int index = 0; index < coordinates.length; index++) {
boolean seenEarlier = false;
for (int previous = 0; previous < index; previous++) {
if (coordinates[index][0] == coordinates[previous][0]
&& coordinates[index][1] == coordinates[previous][1]) {
seenEarlier = true;
break;
}
}
if (!seenEarlier) {
distinct++;
}
}
return distinct;
}
static int countDistinctOptimized(int[][] coordinates) {
Set<Point> points = new HashSet<>();
for (int[] coordinate : coordinates) {
points.add(new Point(coordinate[0], coordinate[1]));
}
return points.size();
}
}
Dry Run
Use coordinates = [[1, 2], [3, 4], [1, 2], [5, 1]].
Optimized approach:
- add
(1, 2)-> set size1 - add
(3, 4)-> set size2 - add
(1, 2)again -> equality says it already exists, size stays2 - add
(5, 1)-> set size3 - return
3
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach: average
O(n)time,O(n)extra space
Edge Cases
- empty input ->
0 - all points identical ->
1 - negative coordinates still hash and compare normally
Common Mistakes
- overriding
equals()but forgettinghashCode() - using mutable coordinate fields and changing them after insertion
- assuming matching hash codes alone mean objects are equal
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- nested-loop lookup and counting often cost
O(n^2) - sorting can reduce some problems to
O(n log n)without hashing - hash-based lookup often brings the cost down to average
O(n)withO(n)extra space - custom-key hashing adds implementation responsibility even when the asymptotic complexity stays strong
Choose brute force or sorting when:
- the input is tiny
- the ordering created by sorting is directly useful
- extra hash-based state would make a simple one-off solution harder to read than necessary
Choose hashing when:
- the same lookup happens repeatedly
- the problem asks for counts, membership, first repeats, or grouping by key
- you want to remove repeated scanning from a baseline solution
Recognition signals for hashing:
- "have we seen this before?"
- "how many times does this appear?"
- "group equal items together"
- "find a complement quickly"
- "deduplicate these records"
Signals not to force hashing:
- the problem depends mainly on sorted order or minimum and maximum access
- the input is a short fixed alphabet, where an array may be simpler than a map
- the solution needs contiguous-window logic more than standalone lookup
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- using the wrong container type for the actual question
- updating the map in the wrong order
- assuming iteration order is meaningful
- forgetting custom equality rules for object keys
Null, empty input, and boundary-condition handling:
- empty arrays or lists
- blank input for string-based counting tasks
- single-element cases where the answer is immediate
- repeated identical values that should collapse to one set entry or many map counts
Collision, mutation, and stale-state risks:
- mutable keys inside a hash-based collection
- comparing reference identity instead of logical equality
- reusing one map across test cases without clearing it
Short debugging checklist:
- What exact key am I inserting?
- Should this problem use a map or a set?
- Am I preserving original order when the answer requires it?
- If I use a custom class, do
equals()andhashCode()describe the same identity? - Did I accidentally rely on iteration order from a hash-based collection?
6. Practice Problems
Easy
- Title: Contains Duplicate
- One-line prompt: Return whether any value appears at least twice in the array.
- Expected pattern or core idea: HashSet membership check.
- Title: Two Sum
- One-line prompt: Find two indexes whose values add to a target.
- Expected pattern or core idea: Complement lookup in a HashMap.
- Title: First Unique Character in a String
- One-line prompt: Return the first index whose character appears exactly once.
- Expected pattern or core idea: Frequency counting followed by an order-preserving scan.
Medium
- Title: Group Anagrams
- One-line prompt: Group strings that contain the same character multiset.
- Expected pattern or core idea: Build a stable key and map strings to that key.
- Title: Longest Consecutive Sequence
- One-line prompt: Return the longest run of consecutive values in an unsorted array.
- Expected pattern or core idea: HashSet membership with true-sequence-start detection.
- Title: Top K Frequent Elements
- One-line prompt: Return the
kmost frequent values from an array. - Expected pattern or core idea: Frequency map followed by ordering or bucket selection.
- One-line prompt: Return the
Hard
- Title: Subarray Sum Equals K
- One-line prompt: Count how many subarrays sum to
k. - Expected pattern or core idea: Prefix sums combined with hashing.
- One-line prompt: Count how many subarrays sum to
- Title: Longest Substring with At Most K Distinct Characters
- One-line prompt: Return the maximum-length substring containing at most
kdistinct characters. - Expected pattern or core idea: HashMap frequency state inside a sliding window.
- One-line prompt: Return the maximum-length substring containing at most
- Title: Design HashMap
- One-line prompt: Build a hash map implementation that supports insert, delete, and get.
- Expected pattern or core idea: Collision handling and bucket design.
7. Short Recap
The core idea of this chapter is that hashing lets you remember what earlier work discovered, so later lookups stop repeating the same scan.
The most important optimization insight is that many O(n^2) lookup and counting tasks become average O(n) once you store counts or seen values explicitly.
The most important implementation warning is that correctness depends on equality rules. Custom objects must define equals() and hashCode() together.
This chapter prepares the next chapter by teaching how to eliminate repeated work. Two-pointer techniques continue that idea, but with movement rules instead of remembered lookup state.
8. Coverage Check
- 5.1 HashMap fundamentals
- 5.2 HashSet fundamentals
- 5.3 Frequency maps and counting patterns
- 5.4 Collision handling basics
- 5.5 Custom hashing and equality in Java
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 6: Two Pointers
6: Two Pointers
Goal: Teach learners how to solve linear-time problems by moving two indexes deliberately instead of restarting scans or using nested loops.
Outcome: By the end of this chapter, you can recognize when opposite-direction, same-direction, fast-and-slow, or partition-style pointer movement removes repeated work, and you can explain the invariant that makes each pattern correct.
1. Intuition First
Two pointers means you track two positions in the same structure and let their movement encode the algorithm.
A simple real-world analogy is searching a long shelf with two markers. Sometimes one marker starts at the left end and the other at the right end. Sometimes both move left to right, but at different roles: one reads and one writes. Sometimes one moves twice as fast as the other to detect a cycle or a meeting point.
The core mental model is that each pointer move must eliminate impossible answers or preserve a useful invariant. This is why two-pointer solutions are fast. They do not re-check large regions once the movement rule proves those regions cannot help.
The most common beginner confusion point is thinking two pointers is just "use variables named left and right." That is not the pattern. The real pattern is controlled movement with a reason for every move.
In the roadmap, this chapter is the bridge from basic scanning to stronger pattern recognition. Once you can justify pointer motion, you are ready for sliding windows, linked-list pointer manipulation, and many interview array problems.
2. Core Concepts and Techniques
Concept Cluster: Opposite-Direction and Same-Direction Pointers
Key concepts in this block:
- 6.1 Opposite-direction pointers
- 6.2 Same-direction pointers
Intuition
Opposite-direction pointers start from different ends and move inward. Same-direction pointers both move left to right, but they represent different roles, such as "read here" and "write here."
Why It Matters
These two forms solve a large share of linear array and string problems without extra nested loops.
How It Works
Opposite-direction pointers fit when:
- the array is sorted and you need a pair or a comparison
- you compare symmetric positions, such as palindrome checks
- moving one side can safely eliminate a region
Same-direction pointers fit when:
- you are compacting valid elements forward
- duplicates or unwanted values must be skipped
- one boundary marks processed output while the other explores input
Java Implementation Notes
- Use descriptive names like
left,right,readIndex, andwriteIndex. - Write the invariant in plain language before the loop if the logic feels subtle.
- Be precise about whether a pointer move happens before or after using the current value.
Common Mistakes
- moving both pointers when only one should move
- forgetting the array must often be sorted for opposite-direction pair logic
- updating the write pointer before the placement is complete
- letting the read and write regions overlap without understanding why it is safe
Quick Example
class OppositePointerQuickExample {
static boolean hasPairWithTargetSum(int[] sortedValues, int target) {
int left = 0;
int right = sortedValues.length - 1;
while (left < right) {
int sum = sortedValues[left] + sortedValues[right];
if (sum == target) {
return true;
}
if (sum < target) {
left++;
} else {
right--;
}
}
return false;
}
}
Debugging Tip
Print both pointer positions and the current window after each move. If the algorithm fails, the first unjustified move is usually the real bug.
Advanced Note
The difference between opposite-direction and same-direction pointers is not cosmetic. It changes what facts each movement step can safely eliminate.
Concept Cluster: Fast and Slow Pointer Technique and Recognition
Key concepts in this block:
- 6.3 Fast and slow pointer technique
- 6.5 Recognizing two-pointer problems
Intuition
Fast and slow pointers traverse the same state space at different speeds. If a cycle exists, the fast one eventually catches the slow one.
Why It Matters
This gives you cycle detection or middle-position discovery without extra memory. It also trains you to think about movement rules rather than just positions.
How It Works
Recognition signals for two pointers:
- the input is already sorted or can be treated as ordered
- you care about pairs, symmetry, or contiguous regions
- the answer can be improved or validated by moving one boundary at a time
- you want in-place updates instead of extra arrays
- you want to detect cycles or repeated states without a set
Fast-and-slow specifically fits when:
- a structure may contain a cycle
- repeated state transitions define a hidden cycle
- you need a middle position in one traversal
Java Implementation Notes
- Keep the transition logic in a helper method when the next state is not obvious.
- Guard loop conditions carefully so fast movement never reads beyond valid state.
- For state-transition problems, name the helper something like
nextStateornextValue.
Common Mistakes
- using fast-and-slow when a normal window is the real pattern
- forgetting that opposite-direction pointer logic often needs sorted data
- moving the wrong pointer after comparing two values
- failing to justify why a movement step cannot skip the answer
Quick Example
class MiddleIndexQuickExample {
static int middleIndex(int[] values) {
int slow = 0;
int fast = 0;
while (fast < values.length - 1) {
slow++;
fast += 2;
}
return slow;
}
}
Debugging Tip
State the invariant in a sentence before coding. For example: "All values before writeIndex are already in their final kept order." That sentence often prevents wrong pointer updates.
Advanced Note
Fast-and-slow pointers are really cycle reasoning in disguise. Later chapters apply the same idea to linked lists more directly.
Concept Cluster: Partitioning and Rearrangement
Key concepts in this block:
- 6.4 Partitioning and rearrangement
Intuition
Partitioning divides the data into regions such as valid and invalid, small and large, zero and non-zero, or processed and unprocessed.
Why It Matters
Many interview problems are not about finding an answer separately from the array. They are about reshaping the array in place while preserving some ordering rule.
How It Works
Typical partition layout:
- left side already satisfies the target property
- middle is the unexplored region
- right side is either unexplored or already classified differently
Rearrangement problems usually become simpler once you write down what each region means before the loop starts.
Java Implementation Notes
- Swapping is often safer than repeated shifting when order does not matter.
- Overwriting with a write pointer is often cleaner when order must be preserved.
- Do not mix stable and unstable rearrangement ideas by accident.
Common Mistakes
- not deciding whether relative order must be preserved
- swapping too early and destroying an unprocessed value
- forgetting to handle already-correct elements
- changing both ends of a partition when only one boundary should move
Quick Example
class ParityPartitionQuickExample {
static void moveEvenNumbersFirst(int[] values) {
int writeIndex = 0;
for (int readIndex = 0; readIndex < values.length; readIndex++) {
if (values[readIndex] % 2 == 0) {
int temporary = values[writeIndex];
values[writeIndex] = values[readIndex];
values[readIndex] = temporary;
writeIndex++;
}
}
}
}
Debugging Tip
Draw the array as regions, not just raw values. If you cannot label the regions clearly, the implementation is probably not ready yet.
Advanced Note
Partition problems are often one small invariant away from being simple. Without that invariant, they feel messy and ad hoc.
3. Worked Examples and Full Solutions
Worked Example 1: Pair Sum in a Sorted Array
Problem Statement
Given a sorted array and a target value, return the indexes of two numbers whose sum equals the target. If no such pair exists, return [-1, -1].
Why This Example Matters
It is the classic opposite-direction two-pointer problem. It shows exactly how pointer movement eliminates impossible pairs.
Constraints or Assumptions
- the array is sorted in non-decreasing order
- exactly one valid pair may or may not exist
- indexes are zero-based for this chapter
Brute-Force Approach
Try every pair with nested loops and return the first matching pair.
This is simple, but it costs O(n^2) time.
Better Approach
Start one pointer at the left end and one at the right end. Compare their sum with the target.
Why the Better Approach Works
Because the array is sorted:
- if the sum is too small, the left pointer must move right to increase it
- if the sum is too large, the right pointer must move left to decrease it
No skipped pair can become valid once the sorted order rules out that region.
Pragmatic Java Choice
Two integer indexes and one loop are enough. No extra collection is needed because sorted order already gives the structure.
Java Solution
class SortedTwoSumExample {
static int[] twoSumBruteForce(int[] values, int target) {
for (int left = 0; left < values.length; left++) {
for (int right = left + 1; right < values.length; right++) {
if (values[left] + values[right] == target) {
return new int[]{left, right};
}
}
}
return new int[]{-1, -1};
}
static int[] twoSumOptimized(int[] values, int target) {
int left = 0;
int right = values.length - 1;
while (left < right) {
int sum = values[left] + values[right];
if (sum == target) {
return new int[]{left, right};
}
if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{-1, -1};
}
}
Dry Run
Use values = [1, 2, 4, 6, 10, 12] and target = 16.
Optimized approach:
left = 0,right = 5, sum is13, too small -> moveleftleft = 1,right = 5, sum is14, too small -> moveleftleft = 2,right = 5, sum is16, match found -> return[2, 5]
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- empty or one-element array -> no pair exists
- negative values still work as long as the array is sorted
- duplicate values can still form the answer if indexes are different
Common Mistakes
- applying the method to an unsorted array
- moving both pointers after one comparison
- returning values instead of indexes when the problem asks for indexes
Worked Example 2: Move Zeroes to the End
Problem Statement
Given an integer array, move all zeroes to the end while keeping the relative order of the non-zero values.
Why This Example Matters
It is one of the cleanest same-direction pointer and partitioning problems. One pointer reads, one pointer writes, and the invariant is easy to inspect.
Constraints or Assumptions
- the operation should modify the array in place
- the relative order of non-zero elements must remain unchanged
- zeroes may already be at the end
Brute-Force Approach
Build a temporary array. Copy all non-zero values into it, then fill the remaining positions with zeroes, and copy the result back.
This is correct, but it uses extra memory.
Better Approach
Use a readIndex to scan the array and a writeIndex to mark where the next non-zero value should go.
Why the Better Approach Works
At every step, all positions before writeIndex already contain the kept non-zero values in the correct order. The remaining region is either unexplored or safely swappable.
Pragmatic Java Choice
An in-place write-pointer solution is clearer here than repeated shifting. It is linear and preserves order.
Java Solution
class MoveZeroesExample {
static void moveZeroesBruteForce(int[] values) {
int[] copy = new int[values.length];
int writeIndex = 0;
for (int value : values) {
if (value != 0) {
copy[writeIndex++] = value;
}
}
while (writeIndex < copy.length) {
copy[writeIndex++] = 0;
}
System.arraycopy(copy, 0, values, 0, values.length);
}
static void moveZeroesOptimized(int[] values) {
int writeIndex = 0;
for (int readIndex = 0; readIndex < values.length; readIndex++) {
if (values[readIndex] != 0) {
int temporary = values[writeIndex];
values[writeIndex] = values[readIndex];
values[readIndex] = temporary;
writeIndex++;
}
}
}
}
Dry Run
Use values = [0, 1, 0, 3, 12].
Optimized approach:
readIndex = 0, value0, do nothingreadIndex = 1, value1, swap withwriteIndex = 0->[1, 0, 0, 3, 12],writeIndex = 1readIndex = 2, value0, do nothingreadIndex = 3, value3, swap withwriteIndex = 1->[1, 3, 0, 0, 12],writeIndex = 2readIndex = 4, value12, swap withwriteIndex = 2->[1, 3, 12, 0, 0]
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- all zeroes -> unchanged
- no zeroes -> unchanged
- empty array -> unchanged
Common Mistakes
- breaking relative order accidentally
- using repeated left shifts and turning a linear task into a slower one
- incrementing
writeIndexeven when the read value is zero
Worked Example 3: Happy Number
Problem Statement
Starting from a positive integer, repeatedly replace the number with the sum of the squares of its digits. Return true if the process reaches 1, otherwise return false.
Why This Example Matters
It is a strong transfer example for fast-and-slow pointers because the state space behaves like a hidden linked structure without actually using linked lists.
Constraints or Assumptions
- input is a positive integer
- the process either reaches
1or falls into a cycle
Brute-Force Approach
Keep a HashSet of previously seen values. If the process repeats a value before reaching 1, a cycle exists.
This is correct, but it uses extra memory.
Better Approach
Use a slow pointer that advances one transformation at a time and a fast pointer that advances two transformations at a time.
Why the Better Approach Works
If the process enters a cycle, fast and slow eventually meet inside it. If the fast pointer reaches 1, the process is happy.
Pragmatic Java Choice
Keep the state transition in a helper method. The main loop becomes much easier to reason about when nextValue is isolated.
Java Solution
import java.util.HashSet;
import java.util.Set;
class HappyNumberExample {
static int nextValue(int value) {
int result = 0;
while (value > 0) {
int digit = value % 10;
result += digit * digit;
value /= 10;
}
return result;
}
static boolean isHappyBruteForce(int value) {
Set<Integer> seen = new HashSet<>();
while (value != 1 && seen.add(value)) {
value = nextValue(value);
}
return value == 1;
}
static boolean isHappyOptimized(int value) {
int slow = value;
int fast = nextValue(value);
while (fast != 1 && slow != fast) {
slow = nextValue(slow);
fast = nextValue(nextValue(fast));
}
return fast == 1;
}
}
Dry Run
Use value = 19.
Optimized approach:
- slow starts at
19, fast starts at82 - next states:
19 -> 82 -> 68 -> 100 -> 1 - the fast pointer reaches
1, so returntrue
For a non-happy number like 2, the sequence enters a repeating cycle and slow and fast eventually meet.
Time and Space Complexity
- Brute force:
O(t)time andO(t)space, wheretis the number of generated states before termination or repetition - Better approach:
O(t)time andO(1)extra space
Edge Cases
1is already happy- single-digit values may or may not be happy
- the state sequence quickly shrinks, but the cycle logic still matters
Common Mistakes
- forgetting to advance the fast pointer twice
- mixing up the current number with the next transformed value
- using this pattern when a normal visited-set solution would be clearer for a different problem shape
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- brute-force pair checking often costs
O(n^2) - two-pointer scans often reduce that to
O(n) - same-direction compaction usually keeps
O(n)time while dropping extra space fromO(n)toO(1) - fast-and-slow pointers often trade extra memory for a more subtle invariant
Choose the simpler baseline when:
- the input is very small
- the invariant is not yet clear and you need a correctness reference
- the problem does not actually allow safe pointer elimination
Choose two pointers when:
- sorted order or symmetry lets one movement eliminate many impossible states
- the task is about keeping or discarding elements in place
- a contiguous region is expanding or shrinking
- repeated states form a cycle you can traverse
Recognition signals for two-pointer techniques:
- sorted array pair problems
- palindrome or symmetric comparisons
- remove duplicates, move zeroes, or stable compaction tasks
- partitioning by a condition
- cycle detection without extra memory
Signals not to force this technique:
- the problem is really about arbitrary key lookup, where hashing fits better
- the data is not ordered and pointer movement does not eliminate anything
- the best state is not attached to boundaries or positions
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- wrong pointer movement after comparison
- broken loop conditions that skip the last valid case
- treating a non-sorted problem as if opposite-direction logic were safe
- losing order during in-place rearrangement
Off-by-one and boundary risks:
left < rightversusleft <= right- when the write pointer should advance
- whether the fast pointer still has room to move twice
- empty arrays and single-element arrays
Mutation and stale-state risks:
- swapping values that are still needed later
- overwriting the write region before reading the current value
- reusing temporary state across test cases without resetting it
Short debugging checklist:
- What does each pointer represent right now?
- Why is this pointer move safe?
- What region is already solved after each iteration?
- Does this approach rely on sorted order or another property I have not guaranteed?
- If I stop the loop now, what cases remain unprocessed?
6. Practice Problems
Easy
- Title: Valid Palindrome
- One-line prompt: Return whether a string reads the same forward and backward after ignoring punctuation and case.
- Expected pattern or core idea: Opposite-direction pointers on normalized comparison.
- Title: Remove Duplicates from Sorted Array
- One-line prompt: Keep one copy of each value in a sorted array and return the new logical length.
- Expected pattern or core idea: Same-direction read and write pointers.
- Title: Merge Strings Alternately
- One-line prompt: Build a string by alternating characters from two inputs.
- Expected pattern or core idea: Coordinated same-direction traversal.
Medium
- Title: Container With Most Water
- One-line prompt: Choose two lines that trap the maximum area.
- Expected pattern or core idea: Opposite-direction pointers with elimination logic.
- Title: 3Sum
- One-line prompt: Return all unique triplets whose sum is zero.
- Expected pattern or core idea: Sorting plus a fixed index and inner two-pointer scan.
- Title: Sort Colors
- One-line prompt: Rearrange an array of
0,1, and2in one pass. - Expected pattern or core idea: Partitioning with multiple regions.
- One-line prompt: Rearrange an array of
Hard
- Title: Trapping Rain Water
- One-line prompt: Compute how much water is trapped after raining.
- Expected pattern or core idea: Opposite-direction pointers with running boundary maxima.
- Title: Find the Duplicate Number
- One-line prompt: Find the repeated value without modifying the array and using constant extra space.
- Expected pattern or core idea: Fast-and-slow pointer cycle interpretation.
- Title: Shortest Unsorted Continuous Subarray
- One-line prompt: Find the smallest window that must be sorted so the full array becomes sorted.
- Expected pattern or core idea: Boundary reasoning and pointer-based scans.
7. Short Recap
The core idea of this chapter is that pointer movement can replace repeated scanning when each move preserves a clear invariant.
The most important optimization insight is that sorted order, symmetry, compaction, and cycle structure often let you reduce O(n^2) work to O(n).
The most important implementation warning is to justify every pointer move. If you cannot explain why moving one side is safe, the algorithm is probably not correct yet.
This chapter prepares the next chapter by turning two moving boundaries into full sliding windows with explicit state such as sums and frequency counts.
8. Coverage Check
- 6.1 Opposite-direction pointers
- 6.2 Same-direction pointers
- 6.3 Fast and slow pointer technique
- 6.4 Partitioning and rearrangement
- 6.5 Recognizing two-pointer problems
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 7: Sliding Window
7: Sliding Window
Goal: Teach learners how to maintain a moving contiguous region efficiently by updating state incrementally instead of recomputing it from scratch.
Outcome: By the end of this chapter, you can solve fixed-size and variable-size window problems, manage window sums and frequency counts correctly, and recognize when a longest or shortest contiguous subarray problem can be solved in linear time.
1. Intuition First
A sliding window is a live segment of the array or string that moves across the input while carrying exactly the information the problem needs.
A simple real-world analogy is a camera frame moving along a long scene. You do not re-process the entire scene every time the frame shifts by one position. You remove what left the frame, add what entered the frame, and keep the running state updated.
The core mental model is this: a window works only when the answer for a contiguous region can be updated from the previous region by local changes. If you can add one item, remove one item, and still know the state, you probably have a sliding-window candidate.
The most common beginner confusion point is trying to use sliding windows on problems where the data is not contiguous or where negative values break the monotonic behavior needed for shrinking logic.
In the roadmap, this chapter is where two pointers become more powerful. Instead of just moving positions, you now maintain live state such as a running sum, a count of distinct values, or a frequency map.
2. Core Concepts and Techniques
Concept Cluster: Fixed-Size Windows
Key concepts in this block:
- 7.1 Fixed-size window
Intuition
A fixed-size window is a moving block of constant length k.
Why It Matters
It turns repeated contiguous computations such as sums, counts, or averages from O(nk) into O(n).
How It Works
For each shift by one position:
- remove the contribution of the outgoing element
- add the contribution of the incoming element
- update the answer
This works because the new window differs from the old one by only two boundary changes.
Java Implementation Notes
- Build the first full window once before sliding.
- Use
longfor sums when value ranges can overflowint. - Be explicit about what happens when
kis invalid.
Common Mistakes
- forgetting to subtract the outgoing value
- updating the answer before the first full window exists
- mixing window indexes and element values
Quick Example
class FixedWindowQuickExample {
static long firstWindowSum(int[] values, int k) {
long sum = 0;
for (int index = 0; index < k; index++) {
sum += values[index];
}
return sum;
}
}
Debugging Tip
Print the left boundary, right boundary, outgoing value, incoming value, and running state for the first few slides.
Advanced Note
Fixed-size windows are often the cleanest place to learn the pattern because the validity condition never changes.
Concept Cluster: Variable-Size Windows and Longest or Shortest Patterns
Key concepts in this block:
- 7.2 Variable-size window
- 7.4 Longest and shortest subarray patterns
Intuition
Variable-size windows expand to include more data and shrink only when a condition becomes invalid or when the current window is already sufficient.
Why It Matters
This pattern solves many substring and subarray problems in linear time when the condition behaves monotonically as the boundaries move.
How It Works
Typical workflow:
- expand the right boundary
- update the state
- while the window is invalid or overly large, move the left boundary and repair the state
- update the best answer when the window is in the right condition
Longest-window problems usually ask you to keep windows valid as large as possible. Shortest-window problems usually ask you to shrink aggressively once the current window becomes sufficient.
Java Implementation Notes
- Write the validity condition in a boolean-style sentence first.
- Keep the shrink loop separate and easy to read.
- For shortest-window problems, initialize the best answer to a sentinel such as
Integer.MAX_VALUE.
Common Mistakes
- forgetting to shrink repeatedly in a
whileloop - using this technique on data with negative values when the monotonic argument fails
- updating the best answer before the window becomes valid
- shrinking too far and losing the first valid state
Quick Example
class VariableWindowQuickExample {
static int minLengthAtLeastTarget(int[] values, int target) {
int left = 0;
int sum = 0;
int best = Integer.MAX_VALUE;
for (int right = 0; right < values.length; right++) {
sum += values[right];
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= values[left++];
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
}
Debugging Tip
When the answer is close but wrong, print the condition that decides whether the window should shrink. That condition is often the real source of the bug.
Advanced Note
Variable-size sliding windows work best when adding more elements moves the condition in one predictable direction.
Concept Cluster: Window State Management and Frequency-Based Problems
Key concepts in this block:
- 7.3 Window state management
- 7.5 Frequency-based sliding window problems
Intuition
Window state is the summary you maintain for the current boundaries. Frequency-based windows store how many times each relevant value appears inside the window.
Why It Matters
The boundaries alone are not enough. The state tells you whether the current window is valid and how to repair it when it is not.
How It Works
Common window state choices:
- running sum
- count of distinct values
- frequency map or array
- number of satisfied required characters
Frequency-based windows are especially useful for:
- duplicate control
- anagram matching
- substring coverage requirements
- windows with a bounded number of distinct values
Java Implementation Notes
- Use a
HashMapwhen the character set or value set is flexible. - Use a fixed-size array when the alphabet is small and known.
- Remove keys whose frequency becomes zero only if that simplifies your validity logic.
Common Mistakes
- not decrementing state correctly when the left boundary moves
- storing more state than the problem needs
- forgetting that distinct-count logic changes when a frequency crosses
0or1 - mixing up the window length with the count of unique values
Quick Example
import java.util.HashMap;
import java.util.Map;
class FrequencyWindowQuickExample {
static int distinctCharacters(String text, int left, int right) {
Map<Character, Integer> frequency = new HashMap<>();
for (int index = left; index <= right; index++) {
char current = text.charAt(index);
frequency.put(current, frequency.getOrDefault(current, 0) + 1);
}
return frequency.size();
}
}
Debugging Tip
Print the state structure whenever the window expands or shrinks. Sliding-window bugs are usually stale-state bugs, not boundary bugs alone.
Advanced Note
A good window solution stores the smallest state that still lets you decide validity and update the answer.
3. Worked Examples and Full Solutions
Worked Example 1: Maximum Sum of a Subarray of Size K
Problem Statement
Given an integer array and an integer k, return the maximum sum of any contiguous subarray of size k.
Why This Example Matters
It is the cleanest fixed-size sliding-window example. It shows the exact remove-one, add-one update pattern.
Constraints or Assumptions
kis positive- the array may contain negative numbers
- if
kis larger than the array length, return0
Brute-Force Approach
For every starting position, sum the next k elements directly.
This works, but it repeats most additions across overlapping windows.
Better Approach
Compute the first window sum once, then slide the window by subtracting the outgoing value and adding the incoming value.
Why the Better Approach Works
Adjacent windows share k - 1 elements. Recomputing the whole sum throws away work the previous window already performed.
Pragmatic Java Choice
Use long for the running sum so large inputs do not overflow accidentally.
Java Solution
class MaxSumFixedWindowExample {
static long maxSumBruteForce(int[] values, int k) {
if (k <= 0 || k > values.length) {
return 0;
}
long best = Long.MIN_VALUE;
for (int start = 0; start + k <= values.length; start++) {
long sum = 0;
for (int index = start; index < start + k; index++) {
sum += values[index];
}
best = Math.max(best, sum);
}
return best;
}
static long maxSumOptimized(int[] values, int k) {
if (k <= 0 || k > values.length) {
return 0;
}
long windowSum = 0;
for (int index = 0; index < k; index++) {
windowSum += values[index];
}
long best = windowSum;
for (int right = k; right < values.length; right++) {
windowSum += values[right];
windowSum -= values[right - k];
best = Math.max(best, windowSum);
}
return best;
}
}
Dry Run
Use values = [2, 1, 5, 1, 3, 2] and k = 3.
Optimized approach:
- first window
[2, 1, 5]has sum8 - slide to
[1, 5, 1]:8 - 2 + 1 = 7 - slide to
[5, 1, 3]:7 - 1 + 3 = 9 - slide to
[1, 3, 2]:9 - 5 + 2 = 6 - best sum is
9
Time and Space Complexity
- Brute force:
O(nk)time,O(1)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
k = 1-> answer is the maximum single valuekequal to array length -> answer is the full array sum- all negative values still work correctly
Common Mistakes
- forgetting to build the first complete window before sliding
- subtracting the wrong outgoing index
- using
intwhen the sum may exceed its range
Worked Example 2: Longest Substring Without Repeating Characters
Problem Statement
Given a string, return the length of the longest substring that contains no repeated characters.
Why This Example Matters
It is the standard frequency-based variable-size window problem. It forces you to maintain validity while expanding and shrinking.
Constraints or Assumptions
- the answer must be a contiguous substring
- characters may repeat anywhere in the string
- an empty string should return
0
Brute-Force Approach
Start from every index and extend the substring until a repeated character appears.
This is simpler than checking all substrings, but it still costs O(n^2) time in the worst case.
Better Approach
Use a variable-size sliding window with a frequency map. Expand the right boundary, and while the current character frequency exceeds 1, shrink from the left.
Why the Better Approach Works
The window invariant is: every character frequency inside the current window is at most 1. When the right boundary breaks that rule, the left boundary moves until the rule is restored.
Pragmatic Java Choice
Use a HashMap<Character, Integer> for clarity. If the character set were guaranteed small and fixed, an array would also be reasonable.
Java Solution
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class LongestUniqueSubstringExample {
static int lengthBruteForce(String text) {
int best = 0;
for (int start = 0; start < text.length(); start++) {
Set<Character> seen = new HashSet<>();
for (int end = start; end < text.length(); end++) {
char current = text.charAt(end);
if (seen.contains(current)) {
break;
}
seen.add(current);
best = Math.max(best, end - start + 1);
}
}
return best;
}
static int lengthOptimized(String text) {
Map<Character, Integer> frequency = new HashMap<>();
int left = 0;
int best = 0;
for (int right = 0; right < text.length(); right++) {
char current = text.charAt(right);
frequency.put(current, frequency.getOrDefault(current, 0) + 1);
while (frequency.get(current) > 1) {
char leftChar = text.charAt(left);
frequency.put(leftChar, frequency.get(leftChar) - 1);
if (frequency.get(leftChar) == 0) {
frequency.remove(leftChar);
}
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
}
Dry Run
Use text = "abcaef".
Optimized approach:
- add
a, window"a", best1 - add
b, window"ab", best2 - add
c, window"abc", best3 - add
a, window becomes invalid becausearepeats - shrink from left: remove first
a, window becomes"bca" - continue with
e,f, best becomes5for"bcaef"
Time and Space Complexity
- Brute force:
O(n^2)time,O(n)extra space in the worst case - Better approach:
O(n)time,O(n)extra space
Edge Cases
- empty string ->
0 - all identical characters ->
1 - all unique characters -> full string length
Common Mistakes
- shrinking only once instead of until the window is valid again
- confusing substring with subsequence
- forgetting to decrement the left-side frequency when shrinking
Worked Example 3: Minimum Size Subarray Sum
Problem Statement
Given an array of positive integers and a target sum, return the length of the shortest contiguous subarray whose sum is at least the target. If no such subarray exists, return 0.
Why This Example Matters
It is the canonical shortest-window pattern. It also shows why positivity matters for this style of shrinking logic.
Constraints or Assumptions
- all values are positive
- the answer must be a contiguous subarray
- return
0if the target cannot be reached
Brute-Force Approach
Start every subarray at every index and keep extending until the sum reaches or exceeds the target.
This is correct, but it costs O(n^2) time.
Better Approach
Expand the right boundary to grow the sum. As soon as the current sum reaches the target, shrink from the left as much as possible while the window still satisfies the requirement.
Why the Better Approach Works
Because all values are positive, removing elements from the left can only decrease the sum. That monotonic behavior makes the shrink loop safe and meaningful.
Pragmatic Java Choice
Keep the running sum as a simple integer or long. The algorithm does not need a map because only the total sum matters.
Java Solution
class MinimumSizeSubarrayExample {
static int minLengthBruteForce(int target, int[] values) {
int best = Integer.MAX_VALUE;
for (int start = 0; start < values.length; start++) {
int sum = 0;
for (int end = start; end < values.length; end++) {
sum += values[end];
if (sum >= target) {
best = Math.min(best, end - start + 1);
break;
}
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
static int minLengthOptimized(int target, int[] values) {
int left = 0;
int sum = 0;
int best = Integer.MAX_VALUE;
for (int right = 0; right < values.length; right++) {
sum += values[right];
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= values[left];
left++;
}
}
return best == Integer.MAX_VALUE ? 0 : best;
}
}
Dry Run
Use target = 7 and values = [2, 3, 1, 2, 4, 3].
Optimized approach:
- expand to
[2, 3, 1, 2], sum8, best4 - shrink to
[3, 1, 2], sum6, stop shrinking - expand with
4, window[3, 1, 2, 4], sum10 - shrink to
[1, 2, 4], sum7, best3 - shrink to
[2, 4], sum6, stop shrinking - expand with
3, window[2, 4, 3], sum9 - shrink to
[4, 3], sum7, best2 - shrink to
[3], sum3, stop shrinking
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- no subarray reaches the target ->
0 - one element already reaches the target ->
1 - the positivity assumption is essential; with negative values, this exact shrinking argument is not safe
Common Mistakes
- using the pattern without noticing that the array contains negative numbers
- updating the best answer after shrinking too far
- forgetting that shortest-window problems usually need a
whileshrink loop
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- fixed-size brute force often costs
O(nk) - variable-size brute force often costs
O(n^2) - well-formed sliding windows usually reduce these to
O(n) - frequency-based windows often need
O(k)orO(n)extra space depending on the state structure
Choose brute force when:
- the window idea is not yet clear and you need a correctness baseline
- the input is tiny
- the condition does not support efficient incremental updates
Choose sliding windows when:
- the problem is explicitly about a contiguous substring or subarray
- the answer can be updated when one element enters or leaves
- the validity condition depends on boundary-local changes
Recognition signals for sliding windows:
- fixed-size contiguous maximum or minimum problems
- longest substring or subarray satisfying a rule
- shortest window meeting a threshold or coverage requirement
- frequency limits such as no repeats or at most
kdistinct values
Signals not to force this technique:
- the problem is not contiguous
- negative values destroy the monotonic shrinking logic you planned to use
- the state needed for each region cannot be updated incrementally
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- stale sums or stale frequency counts
- shrinking too late or too early
- updating the answer before the window reaches a valid state
- forgetting that distinct-count logic changes when a frequency crosses zero
Boundary and validity risks:
- invalid
kvalues in fixed-size problems - empty input strings or arrays
- shortest-window sentinel values not being converted back to
0when no answer exists - positive-number assumptions being ignored
Short debugging checklist:
- What does the current window represent?
- What exact state do I maintain for it?
- When I move the left boundary, which state entries must decrease?
- Is the shrink loop supposed to run once or until validity is restored?
- Am I solving a contiguous problem, or should I stop forcing a window?
6. Practice Problems
Easy
- Title: Maximum Average Subarray I
- One-line prompt: Return the maximum average value of any contiguous subarray of length
k. - Expected pattern or core idea: Fixed-size sliding window with running sum.
- One-line prompt: Return the maximum average value of any contiguous subarray of length
- Title: Find All Anagrams in a String
- One-line prompt: Return all start indexes where a substring is an anagram of a target string.
- Expected pattern or core idea: Fixed-size frequency window.
- Title: Diet Plan Performance
- One-line prompt: Score a sequence based on sums of fixed-size daily windows.
- Expected pattern or core idea: Fixed-size sum maintenance.
Medium
- Title: Longest Substring Without Repeating Characters
- One-line prompt: Return the length of the longest substring with all unique characters.
- Expected pattern or core idea: Variable-size frequency window.
- Title: Minimum Size Subarray Sum
- One-line prompt: Return the shortest subarray length whose sum reaches a target.
- Expected pattern or core idea: Variable-size window on positive values.
- Title: Longest Repeating Character Replacement
- One-line prompt: Find the longest substring that can be made uniform after at most
kreplacements. - Expected pattern or core idea: Window validity driven by frequency state.
- One-line prompt: Find the longest substring that can be made uniform after at most
Hard
- Title: Minimum Window Substring
- One-line prompt: Return the smallest substring that contains all characters of another string.
- Expected pattern or core idea: Frequency-based coverage window with aggressive shrinking.
- Title: Subarrays with K Different Integers
- One-line prompt: Count subarrays that contain exactly
kdistinct values. - Expected pattern or core idea: Convert exact-count to at-most windows and subtract.
- One-line prompt: Count subarrays that contain exactly
- Title: Sliding Window Maximum
- One-line prompt: Return the maximum value in every fixed-size window.
- Expected pattern or core idea: Sliding window combined with a deque.
7. Short Recap
The core idea of this chapter is that a window can move across contiguous data without recomputing everything from scratch, as long as you maintain the right state.
The most important optimization insight is that fixed-size and variable-size windows often reduce O(nk) or O(n^2) work to O(n) by updating only what changes at the boundaries.
The most important implementation warning is that window boundaries and window state must stay synchronized. Most bugs happen when one changes without the other.
This chapter prepares the next chapter by showing how local cumulative state works. Prefix sums and difference arrays store similar information globally instead of for one live window.
8. Coverage Check
- 7.1 Fixed-size window
- 7.2 Variable-size window
- 7.3 Window state management
- 7.4 Longest and shortest subarray patterns
- 7.5 Frequency-based sliding window problems
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 8: Prefix Sum and Difference Techniques
8: Prefix Sum and Difference Techniques
Goal: Teach learners how to preprocess cumulative information so repeated range queries and range updates become efficient instead of repetitive.
Outcome: By the end of this chapter, you can build one-dimensional prefix sums, answer range sum queries in O(1), apply many updates with a difference array, reason about prefix XOR, and combine prefix data with hashing to count subarrays efficiently.
1. Intuition First
Prefix techniques turn repeated work into remembered work.
A simple real-world analogy is mile markers on a road. If you know the total distance from the origin to mile marker 10 and the total distance to mile marker 3, then the distance from 3 to 10 is just the difference between those two cumulative totals. You do not re-measure the entire road segment every time.
The core mental model is this: store enough cumulative information so a later query becomes subtraction, XOR cancellation, or one map lookup instead of a full scan.
The most common beginner confusion point is mixing up what the prefix array stores. A prefix array usually stores information up to, but not including, the current index in the original array. That extra offset is what removes many boundary special cases.
In the roadmap, this chapter is the first strong example of offline preprocessing. You spend time once, then answer many questions quickly.
2. Core Concepts and Techniques
Concept Cluster: One-Dimensional Prefix Sums and Range Sum Queries
Key concepts in this block:
- 8.1 One-dimensional prefix sums
- 8.2 Range sum queries
Intuition
A prefix sum array stores cumulative totals from the start of the array up to each position.
Why It Matters
Without preprocessing, repeated range sums can cost O(n) each. With prefix sums, each range query becomes O(1).
How It Works
The standard layout is:
prefix[0] = 0prefix[i + 1] = prefix[i] + values[i]
Then the sum from left to right inclusive is:
prefix[right + 1] - prefix[left]
That extra leading zero is the main boundary simplifier.
Java Implementation Notes
- Prefer a prefix array of length
n + 1. - Use
longif the total sum may overflowint. - Keep query formulas consistent about inclusive and exclusive boundaries.
Common Mistakes
- forgetting the leading zero entry
- using
prefix[right] - prefix[left]by mistake - mixing inclusive and exclusive boundaries mid-solution
- rebuilding ranges from scratch even after preprocessing
Quick Example
class PrefixSumQuickExample {
static long[] buildPrefix(int[] values) {
long[] prefix = new long[values.length + 1];
for (int index = 0; index < values.length; index++) {
prefix[index + 1] = prefix[index] + values[index];
}
return prefix;
}
}
Debugging Tip
Write out the prefix array for a tiny example by hand. If the prefix values are wrong, every query answer will also be wrong.
Advanced Note
Prefix sums are best when the underlying array stays mostly static. If updates are frequent and queries are frequent, later tree-based structures become more appropriate.
Concept Cluster: Difference Arrays
Key concepts in this block:
- 8.3 Difference arrays
Intuition
A difference array stores where a running effect starts and where it stops.
Why It Matters
If a problem applies many range updates to a static array, updating every element inside every range is wasteful. Difference arrays mark only the boundaries and reconstruct the final values later.
How It Works
For an update that adds delta on [left, right]:
- add
deltaatdifference[left] - subtract
deltaatdifference[right + 1]if that index exists
After all updates, prefix-summing the difference array reconstructs the final values.
Java Implementation Notes
- Difference arrays are ideal for offline batch updates.
- The final reconstruction pass is just a running sum.
- Be careful when
right + 1reaches the array boundary.
Common Mistakes
- forgetting the stop marker subtraction
- applying updates directly to the original array and losing the whole point of the technique
- mixing the original array and difference array semantics
- not checking the boundary before writing
right + 1
Quick Example
class DifferenceArrayQuickExample {
static int[] applySingleUpdate(int length, int left, int right, int delta) {
int[] difference = new int[length];
difference[left] += delta;
if (right + 1 < length) {
difference[right + 1] -= delta;
}
return difference;
}
}
Debugging Tip
When the final array is wrong, inspect the raw difference array before the reconstruction pass. Boundary mistakes show up there first.
Advanced Note
Difference arrays are the update-side mirror image of prefix sums. One makes queries cheap, the other makes updates cheap.
Concept Cluster: Prefix XOR and Prefix Data with Hashing
Key concepts in this block:
- 8.4 Prefix XOR
- 8.5 Combining prefix data with hashing
Intuition
Prefix XOR stores the XOR of all values up to each position. Combining prefix data with hashing means remembering how often a cumulative value has appeared so far.
Why It Matters
Many subarray count problems are really questions about relationships between two prefix states. Once you see that relationship, a map can count valid starts in constant time per position.
How It Works
For sums:
- if
prefixSum[right] - prefixSum[left] = target, then an earlier prefix value determines whether a valid subarray exists
For XOR:
- if
prefixXor ^ earlierPrefixXor = target, thenearlierPrefixXor = prefixXor ^ target
The map stores how many times each earlier prefix value has already appeared.
Java Implementation Notes
- Seed the map with the empty prefix value before scanning.
- For sums, the empty prefix is
0. - For XOR, the empty prefix is also
0. - Update the answer before inserting the current prefix count if you are counting subarrays ending at the current index.
Common Mistakes
- forgetting the initial prefix count of
0 - confusing prefix sum formulas with prefix XOR formulas
- updating the map in the wrong order
- treating subarray and subsequence problems as the same thing
Quick Example
import java.util.HashMap;
import java.util.Map;
class PrefixCountQuickExample {
static int countPrefixesEqualToValue(int[] values, int target) {
Map<Integer, Integer> count = new HashMap<>();
count.put(0, 1);
int prefix = 0;
int answer = 0;
for (int value : values) {
prefix += value;
answer += count.getOrDefault(prefix - target, 0);
count.put(prefix, count.getOrDefault(prefix, 0) + 1);
}
return answer;
}
}
Debugging Tip
Print the current prefix value and the map lookup target at each step. That reveals whether your algebra or your update order is wrong.
Advanced Note
Prefix-plus-hash solutions often look magical until you write the equation connecting two prefix states. Once that equation is clear, the map is just a counter of possible starting points.
3. Worked Examples and Full Solutions
Worked Example 1: Range Sum Query on a Static Array
Problem Statement
Given an integer array and many queries [left, right], return the sum of the values inside each inclusive range.
Why This Example Matters
It is the direct reason prefix sums exist. A single preprocessing pass turns repeated range queries into constant-time work.
Constraints or Assumptions
- the array does not change between queries
- there may be many queries
- range boundaries are inclusive
Brute-Force Approach
For each query, loop from left to right and add the values directly.
This is easy to write, but repeated queries become expensive.
Better Approach
Precompute a prefix sum array once. Then answer each query using subtraction.
Why the Better Approach Works
The prefix array stores total work from the start. Subtracting two cumulative totals isolates the middle range instantly.
Pragmatic Java Choice
A tiny wrapper class around the prefix array keeps query logic clean and avoids repeating the formula.
Java Solution
class RangeSumQueryExample {
static long sumRangeBruteForce(int[] values, int left, int right) {
long sum = 0;
for (int index = left; index <= right; index++) {
sum += values[index];
}
return sum;
}
static final class PrefixSumRangeQuery {
private final long[] prefix;
PrefixSumRangeQuery(int[] values) {
prefix = new long[values.length + 1];
for (int index = 0; index < values.length; index++) {
prefix[index + 1] = prefix[index] + values[index];
}
}
long sumRange(int left, int right) {
return prefix[right + 1] - prefix[left];
}
}
}
Dry Run
Use values = [2, 4, 5, 7] and query [1, 3].
Prefix array:
prefix[0] = 0prefix[1] = 2prefix[2] = 6prefix[3] = 11prefix[4] = 18
Query answer:
- sum from
1to3isprefix[4] - prefix[1] = 18 - 2 = 16
Time and Space Complexity
- Brute force:
O(length of range)time per query,O(1)extra space - Better approach:
O(n)preprocessing time,O(1)per query,O(n)extra space
Edge Cases
- query starting at
0 - query covering the full array
- negative numbers are handled normally
Common Mistakes
- forgetting that the query boundaries are inclusive
- building a prefix array of size
ninstead ofn + 1 - using
intwhen the total sum can grow large
Worked Example 2: Apply Many Range Increment Updates
Problem Statement
Given an array length n and a list of updates [left, right, delta], apply every increment to that inclusive range and return the final array.
Why This Example Matters
It shows the update-side version of preprocessing. Instead of making queries cheap, you make repeated range updates cheap.
Constraints or Assumptions
- the initial array contains all zeroes
- all updates are known in advance
- updates are inclusive ranges
Brute-Force Approach
For each update, loop from left to right and add delta to every element.
This is correct, but it costs O(number of updates * range length) in the worst case.
Better Approach
Use a difference array. Mark where each increment starts and where it stops, then reconstruct the final values with a prefix sum.
Why the Better Approach Works
Every range update contributes the same effect over a contiguous interval. Boundary markers are enough to represent that effect compactly until the reconstruction pass.
Pragmatic Java Choice
Keep the difference array separate from the final result array. That separation makes the update logic easier to debug.
Java Solution
class RangeAdditionExample {
static int[] applyUpdatesBruteForce(int length, int[][] updates) {
int[] values = new int[length];
for (int[] update : updates) {
int left = update[0];
int right = update[1];
int delta = update[2];
for (int index = left; index <= right; index++) {
values[index] += delta;
}
}
return values;
}
static int[] applyUpdatesOptimized(int length, int[][] updates) {
int[] difference = new int[length];
for (int[] update : updates) {
int left = update[0];
int right = update[1];
int delta = update[2];
difference[left] += delta;
if (right + 1 < length) {
difference[right + 1] -= delta;
}
}
int[] result = new int[length];
int running = 0;
for (int index = 0; index < length; index++) {
running += difference[index];
result[index] = running;
}
return result;
}
}
Dry Run
Use length = 5 and updates [[1, 3, 2], [2, 4, 3], [0, 2, -2]].
Difference updates:
- after
[1, 3, 2]->[0, 2, 0, 0, -2] - after
[2, 4, 3]->[0, 2, 3, 0, -2] - after
[0, 2, -2]->[-2, 2, 3, 2, -2]
Reconstruction by running sum:
- index
0:-2 - index
1:0 - index
2:3 - index
3:5 - index
4:3
Final array: [-2, 0, 3, 5, 3]
Time and Space Complexity
- Brute force:
O(q * n)in the worst case, whereqis the number of updates - Better approach:
O(q + n)time,O(n)extra space
Edge Cases
- one update covering the full array
rightalready at the last index- negative deltas work naturally
Common Mistakes
- forgetting to subtract at
right + 1 - reconstructing directly into the difference array and losing clarity
- trying to use this technique for online updates and queries without reconsidering the problem model
Worked Example 3: Count Subarrays with XOR Equal to K
Problem Statement
Given an integer array and a target k, return how many contiguous subarrays have XOR equal to k.
Why This Example Matters
It combines prefix XOR with hashing. This is the chapter's most important transfer pattern.
Constraints or Assumptions
- the answer counts contiguous subarrays
- values may repeat
- the array may contain zeroes
Brute-Force Approach
Start every subarray at every index and keep a running XOR as the end index extends.
This is correct, but it still costs O(n^2) time.
Better Approach
Maintain the prefix XOR as you scan. For each position, count how many earlier prefix XOR values satisfy earlierPrefix = currentPrefix ^ k.
Why the Better Approach Works
If prefixXor[0..right] ^ prefixXor[0..left - 1] = k, then the earlier prefix must be exactly currentPrefix ^ k. A map tells you how many such earlier prefixes already exist.
Pragmatic Java Choice
Use a HashMap<Integer, Integer> from prefix XOR value to occurrence count. Seed it with the empty prefix XOR 0.
Java Solution
import java.util.HashMap;
import java.util.Map;
class SubarrayXorCountExample {
static int countBruteForce(int[] values, int targetXor) {
int answer = 0;
for (int start = 0; start < values.length; start++) {
int runningXor = 0;
for (int end = start; end < values.length; end++) {
runningXor ^= values[end];
if (runningXor == targetXor) {
answer++;
}
}
}
return answer;
}
static int countOptimized(int[] values, int targetXor) {
Map<Integer, Integer> prefixCount = new HashMap<>();
prefixCount.put(0, 1);
int prefixXor = 0;
int answer = 0;
for (int value : values) {
prefixXor ^= value;
answer += prefixCount.getOrDefault(prefixXor ^ targetXor, 0);
prefixCount.put(prefixXor, prefixCount.getOrDefault(prefixXor, 0) + 1);
}
return answer;
}
}
Dry Run
Use values = [4, 2, 2, 6, 4] and targetXor = 6.
Optimized approach:
- start with map
{0=1} - read
4, prefix XOR4, look for4 ^ 6 = 2, not found - read
2, prefix XOR6, look for6 ^ 6 = 0, found once -> answer1 - read
2, prefix XOR4, look for2, still not found, map count for4becomes2 - read
6, prefix XOR2, look for4, found twice -> answer3 - read
4, prefix XOR6, look for0, found once -> answer4
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach: average
O(n)time,O(n)extra space
Edge Cases
- empty array ->
0 - target XOR
0is valid and often important - zero values can create repeated prefix XOR states
Common Mistakes
- forgetting the initial map entry for prefix XOR
0 - using sum subtraction logic instead of XOR algebra
- updating the map before counting the current position's answer and changing the meaning of the scan
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- direct range queries can cost
O(n)each without preprocessing - prefix sums trade
O(n)extra space forO(1)query time on static data - difference arrays trade
O(n)extra space for fast batched range updates - prefix-plus-hash solutions often reduce subarray counting from
O(n^2)to averageO(n)
Choose brute force when:
- there are very few queries or updates
- the input is tiny
- preprocessing would cost more mental overhead than it saves
Choose prefix sums when:
- the array is static
- you need many contiguous range sums
- the query formula is simple subtraction from cumulative totals
Choose difference arrays when:
- you know all range updates in advance
- you want the final array after all updates, not instant answers after each one
Recognition signals for prefix-plus-hash techniques:
- count subarrays with a target sum or XOR
- longest subarray with a given cumulative property
- repeated range questions on static data
Signals not to force this technique:
- the problem is about non-contiguous choices
- the data updates online between queries and you still need fast answers
- the cumulative algebra is not actually additive or XOR-canceling
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- off-by-one errors in prefix boundaries
- forgetting the empty prefix value
- confusing prefix sum and difference array semantics
- mixing update order and query order incorrectly in prefix-plus-map problems
Boundary and state risks:
left = 0queriesright + 1falling outside the array in difference logic- integer overflow in cumulative sums
- using subtraction rules for XOR or XOR rules for subtraction
Short debugging checklist:
- What exactly does
prefix[i]mean in this solution? - Do my formulas assume inclusive or exclusive boundaries?
- Did I seed the empty prefix state correctly?
- Am I solving many queries, many updates, or both?
- If I write out a tiny example by hand, does my prefix or difference array match it?
6. Practice Problems
Easy
- Title: Range Sum Query - Immutable
- One-line prompt: Answer many range-sum queries on a static array.
- Expected pattern or core idea: One-dimensional prefix sums.
- Title: Find Pivot Index
- One-line prompt: Find an index where the left sum equals the right sum.
- Expected pattern or core idea: Prefix sums or running left-right totals.
- Title: XOR Queries of a Subarray
- One-line prompt: Answer many range XOR queries efficiently.
- Expected pattern or core idea: Prefix XOR.
Medium
- Title: Subarray Sum Equals K
- One-line prompt: Count subarrays whose sum equals a target.
- Expected pattern or core idea: Prefix sums combined with hashing.
- Title: Range Addition
- One-line prompt: Apply many inclusive range increment operations and return the final array.
- Expected pattern or core idea: Difference array plus reconstruction.
- Title: Continuous Subarray Sum
- One-line prompt: Determine whether a subarray sum is a multiple of
k. - Expected pattern or core idea: Prefix remainder states stored in a map.
- One-line prompt: Determine whether a subarray sum is a multiple of
Hard
- Title: Count Subarrays with XOR K
- One-line prompt: Return how many subarrays have XOR equal to a target.
- Expected pattern or core idea: Prefix XOR with frequency hashing.
- Title: Maximum Size Subarray Sum Equals K
- One-line prompt: Return the maximum length of a subarray summing to
k. - Expected pattern or core idea: Earliest prefix occurrence mapping.
- One-line prompt: Return the maximum length of a subarray summing to
- Title: Corporate Flight Bookings
- One-line prompt: Apply many seat-booking increments on flight ranges.
- Expected pattern or core idea: Difference array on offline updates.
7. Short Recap
The core idea of this chapter is that cumulative state lets you answer repeated range questions or batched updates without recomputing the same work.
The most important optimization insight is that prefix sums, difference arrays, and prefix-plus-hash maps each compress many local operations into one scan plus cheap lookups.
The most important implementation warning is to define your prefix meaning precisely. Most bugs here are boundary-definition bugs.
This chapter prepares the next chapter by closing the array-preprocessing part of Part II. The next chapter moves to linked lists, where structure changes matter more than index arithmetic.
8. Coverage Check
- 8.1 One-dimensional prefix sums
- 8.2 Range sum queries
- 8.3 Difference arrays
- 8.4 Prefix XOR
- 8.5 Combining prefix data with hashing
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 9: Linked Lists
9: Linked Lists
Goal: Teach learners how linked lists are built node by node, how pointer updates change structure safely, and how to solve the most common reversal, merge, and cycle-detection problems in Java.
Outcome: By the end of this chapter, you can implement singly, doubly, and circular linked lists conceptually, reverse and merge lists with pointer manipulation, detect cycles, and explain when a linked list is a better fit than an array.
1. Intuition First
An array stores values next to each other in memory by index. A linked list stores values in separate nodes connected by references.
A simple real-world analogy is a train. Each carriage knows how to reach the next carriage. In a doubly linked train, each carriage can also reach the previous one. In a circular train, the last carriage connects back to the first.
The core mental model is this: a linked list is about connections, not positions. You rarely jump directly to index k. Instead, you walk node by node and change links carefully when restructuring the list.
The most common beginner confusion point is losing part of the list during mutation. If you change current.next before saving the next node you still need, the rest of the list can disappear from reach.
In the roadmap, this chapter is where pointer manipulation becomes concrete. The same pointer discipline later appears in stacks, queues, trees, and many interview list problems.
2. Core Concepts and Techniques
Concept Cluster: Singly, Doubly, and Circular Linked Lists
Key concepts in this block:
- 9.1 Singly linked lists
- 9.2 Doubly linked lists
- 9.3 Circular linked lists
Intuition
A singly linked list node points to the next node. A doubly linked list node points both forward and backward. A circular linked list reconnects the tail to the head instead of ending with null.
Why It Matters
The node shape determines what operations are cheap, what traversal directions are possible, and what mutation risks exist.
How It Works
Singly linked list:
- simplest node shape
- forward traversal only
- insertion after a known node is easy
Doubly linked list:
- supports backward movement
- deletion is easier when you already have the target node
- each mutation must update both directions consistently
Circular linked list:
- no
nulltail marker - useful when the structure should wrap around repeatedly
- traversal must stop by a logical condition, not by waiting for
null
Java Implementation Notes
- For interview problems, define a custom
ListNodeorDoublyNodeclass explicitly. - Java provides
java.util.LinkedList, but that class is usually better for queue or deque behavior than for pointer-manipulation interview problems. - Keep node fields minimal until the problem requires more.
Common Mistakes
- treating a linked list like an array with constant-time random access
- forgetting to update both
prevandnextin doubly linked lists - traversing a circular list with a
while (current != null)loop - losing the head or tail reference during updates
Quick Example
class SinglyLinkedListQuickExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static ListNode insertAfter(ListNode node, int value) {
ListNode newNode = new ListNode(value);
newNode.next = node.next;
node.next = newNode;
return newNode;
}
}
Debugging Tip
Draw the nodes and arrows before and after one pointer change. Linked-list bugs are usually visual bugs.
Advanced Note
Extra pointers make some operations easier, but they also double the mutation surface. Simpler structure is often better unless the use case clearly needs more.
Concept Cluster: Reversal, Merge, and Pointer Manipulation
Key concepts in this block:
- 9.4 Reversal techniques
- 9.6 Merge and pointer manipulation problems
Intuition
Reversal flips pointer direction. Merge interleaves or combines nodes while preserving a rule such as sorted order.
Why It Matters
These problems force you to reason about structure changes directly. They are a major interview checkpoint because they reveal whether you actually understand node references.
How It Works
Common pointer roles:
previousstores the already-reversed partcurrentis the node being processednextNodesaves the rest of the list before rewiringtailordummyhelps build merged output safely
The main safety rule is: save what you still need before changing any pointer that might disconnect it.
Java Implementation Notes
- Dummy nodes make merge logic cleaner by removing head-special cases.
- Iterative reversal is usually the first version to master before recursive reversal.
- When order must be preserved during merge, move nodes one by one instead of copying values unless a brute-force baseline is intentional.
Common Mistakes
- overwriting
current.nextbefore saving it - forgetting to move the tail pointer in a merge
- leaving the old
nextlink attached and creating an accidental cycle - returning the wrong head after reversal
Quick Example
class ReverseQuickExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static ListNode reverse(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode nextNode = current.next;
current.next = previous;
previous = current;
current = nextNode;
}
return previous;
}
}
Debugging Tip
At each step, ask three questions: What is already fixed? What am I processing now? What part of the list have I saved for later?
Advanced Note
Most linked-list problems are pointer bookkeeping problems, not algorithm-invention problems. Clear role naming matters a lot.
Concept Cluster: Cycle Detection
Key concepts in this block:
- 9.5 Cycle detection
Intuition
Cycle detection asks whether following next references can loop forever instead of ending at null.
Why It Matters
Cycle bugs are structural, not value-based. The problem teaches you to reason about list shape independently of node data.
How It Works
Two standard strategies:
- visited-set detection: remember nodes already seen
- Floyd's slow-and-fast pointer technique: if a cycle exists, fast and slow eventually meet
Java Implementation Notes
- A
HashSet<ListNode>is the easiest correctness baseline. - Floyd's algorithm is the space-optimized version to master after the baseline is clear.
- If you later need the cycle entry point, the same meeting logic extends naturally.
Common Mistakes
- comparing node values instead of node references
- forgetting that a single node can point to itself and still form a cycle
- moving the fast pointer unsafely when
fast.nextisnull
Quick Example
class CycleQuickExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Debugging Tip
When cycle detection fails, draw the meeting sequence for a tiny cyclic list. Pointer motion bugs become obvious quickly on a 3-node cycle.
Advanced Note
Cycle reasoning is one of the first places where node identity matters more than the node value.
3. Worked Examples and Full Solutions
Worked Example 1: Reverse a Singly Linked List
Problem Statement
Given the head of a singly linked list, reverse the list and return the new head.
Why This Example Matters
It is the foundation of linked-list pointer manipulation. If reversal is not stable yet, harder list problems remain fragile.
Constraints or Assumptions
- the list may be empty
- the list may contain one node
- reversal should preserve the nodes, not just the values conceptually
Brute-Force Approach
Copy all node values into an array-like list, then walk the original list again and overwrite node values from back to front.
This returns the reversed value sequence, but it uses extra memory and avoids the real pointer skill.
Better Approach
Reverse the next pointers in place using previous, current, and nextNode.
Why the Better Approach Works
At each step, the already-processed prefix is reversed and safely anchored at previous. Saving nextNode keeps the unexplored suffix reachable.
Pragmatic Java Choice
Master the iterative version first. It is explicit, efficient, and easier to debug than recursive reversal for beginners.
Java Solution
import java.util.ArrayList;
import java.util.List;
class ReverseLinkedListExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static ListNode reverseBruteForce(ListNode head) {
List<Integer> values = new ArrayList<>();
for (ListNode current = head; current != null; current = current.next) {
values.add(current.value);
}
int index = values.size() - 1;
for (ListNode current = head; current != null; current = current.next) {
current.value = values.get(index--);
}
return head;
}
static ListNode reverseOptimized(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode nextNode = current.next;
current.next = previous;
previous = current;
current = nextNode;
}
return previous;
}
}
Dry Run
Use 1 -> 2 -> 3 -> null.
Optimized approach:
- start:
previous = null,current = 1 - save
nextNode = 2, point1.nexttonull, movepreviousto1 - save
nextNode = 3, point2.nextto1, movepreviousto2 - save
nextNode = null, point3.nextto2, movepreviousto3 - return
3 -> 2 -> 1 -> null
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- empty list -> return
null - one-node list -> unchanged
- long list -> same logic scales linearly
Common Mistakes
- not saving
nextNodebefore rewiring - returning the old head instead of the new head
- accidentally creating a cycle by forgetting to terminate the new tail
Worked Example 2: Merge Two Sorted Linked Lists
Problem Statement
Given the heads of two sorted singly linked lists, merge them into one sorted list and return the new head.
Why This Example Matters
It combines traversal, comparison, and safe pointer stitching. It is one of the most common linked-list interview questions.
Constraints or Assumptions
- both input lists are sorted in non-decreasing order
- either list may be empty
- the result should preserve sorted order
Brute-Force Approach
Copy all values from both lists into an ArrayList, sort the list, and rebuild a new linked list.
This works, but it throws away the structural advantage of already sorted linked lists.
Better Approach
Use a dummy head and repeatedly attach the smaller current node from the two lists.
Why the Better Approach Works
At every step, the next node of the merged list must be the smaller of the two current candidates. The dummy head removes the need for a special first attachment case.
Pragmatic Java Choice
Use a dummy node for clarity. It is the standard way to simplify list-building logic in Java interviews.
Java Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class MergeSortedListsExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static ListNode mergeBruteForce(ListNode first, ListNode second) {
List<Integer> values = new ArrayList<>();
for (ListNode current = first; current != null; current = current.next) {
values.add(current.value);
}
for (ListNode current = second; current != null; current = current.next) {
values.add(current.value);
}
Collections.sort(values);
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int value : values) {
tail.next = new ListNode(value);
tail = tail.next;
}
return dummy.next;
}
static ListNode mergeOptimized(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
ListNode left = first;
ListNode right = second;
while (left != null && right != null) {
if (left.value <= right.value) {
tail.next = left;
left = left.next;
} else {
tail.next = right;
right = right.next;
}
tail = tail.next;
}
tail.next = (left != null) ? left : right;
return dummy.next;
}
}
Dry Run
Use first = 1 -> 3 -> 5 and second = 2 -> 4 -> 6.
Optimized approach:
- compare
1and2, attach1 - compare
3and2, attach2 - compare
3and4, attach3 - continue similarly until one list ends
- attach the remaining suffix directly
Result: 1 -> 2 -> 3 -> 4 -> 5 -> 6
Time and Space Complexity
- Brute force:
O((n + m) log(n + m))time,O(n + m)extra space - Better approach:
O(n + m)time,O(1)extra space if reusing the input nodes
Edge Cases
- one list empty -> return the other
- both lists empty -> return
null - duplicate values merge naturally
Common Mistakes
- forgetting to advance
tail - forgetting to attach the remaining suffix after one list finishes
- rebuilding the head repeatedly instead of keeping one stable dummy
Worked Example 3: Detect a Cycle in a Linked List
Problem Statement
Given the head of a singly linked list, return true if the list contains a cycle; otherwise return false.
Why This Example Matters
It shows how shape-based reasoning differs from value-based reasoning, and it revisits fast-and-slow pointers in the most classic linked-list form.
Constraints or Assumptions
- nodes may repeat by reference only if a cycle exists
- node values are irrelevant to cycle existence
- a node may point to itself
Brute-Force Approach
Use a HashSet to store visited node references. If a node appears again, a cycle exists.
This is easy to reason about, but it uses extra memory.
Better Approach
Use Floyd's slow-and-fast pointer technique.
Why the Better Approach Works
If there is no cycle, the fast pointer reaches null. If there is a cycle, the faster pointer laps the slower one and they eventually meet.
Pragmatic Java Choice
The visited-set version is a good correctness baseline. Floyd's algorithm is the optimized version you should aim to internalize.
Java Solution
import java.util.HashSet;
import java.util.Set;
class LinkedListCycleExample {
static final class ListNode {
int value;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
static boolean hasCycleBruteForce(ListNode head) {
Set<ListNode> visited = new HashSet<>();
ListNode current = head;
while (current != null) {
if (!visited.add(current)) {
return true;
}
current = current.next;
}
return false;
}
static boolean hasCycleOptimized(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Dry Run
Use 1 -> 2 -> 3 -> 4 -> 2 ....
Optimized approach:
- slow moves
1 -> 2 -> 3 -> 4 -> 2 ... - fast moves
1 -> 3 -> 2 -> 4 -> 3 ... - eventually both references land on the same node inside the cycle
- return
true
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- empty list ->
false - single node without self-loop ->
false - single node pointing to itself ->
true
Common Mistakes
- comparing node values instead of node references
- moving the fast pointer without checking
fast.next - assuming cycles only happen in longer lists
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- traversal is usually
O(n)because linked lists do not support constant-time random access - insertion or deletion after a known node is usually
O(1) - reversal and merge are usually linear-time pointer tasks
- visited-set cycle detection uses extra memory, while Floyd's algorithm keeps
O(1)extra space
Choose a linked list when:
- insertions and deletions in the middle are frequent once you already have the node reference
- the structure naturally grows node by node
- pointer-based reordering is easier than shifting array elements
Choose an array or ArrayList instead when:
- you need random access by index
- cache-friendly traversal and simple indexing matter more than pointer rewiring
- the structure is mostly read-only and contiguous memory helps
Recognition signals for linked-list techniques:
- node-by-node traversal
- reversal or reorder operations
- merge by pointer stitching
- cycle or middle-of-list questions
Signals not to force this technique:
- the problem is mainly about indexed lookup
- you plan to scan to the middle repeatedly and need random access
- a standard queue or deque library abstraction is enough without custom node work
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- losing the rest of the list during rewiring
- forgetting to update both directions in a doubly linked list
- returning the wrong head after mutation
- comparing values instead of references in structural problems
Null and boundary-condition handling:
- empty list
- single-node list
- head insertion or deletion
- tail updates
- circular traversal stop conditions
Mutation risks:
- overwriting
nextbefore saving it - leaving stale links and creating unintended cycles
- forgetting that a dummy node changes where the real head begins
Short debugging checklist:
- What node does each pointer represent right now?
- Have I saved the next node before rewiring?
- After this change, can I still reach the rest of the list?
- Am I mutating structure or just values?
- If this were a circular list, how would traversal know when to stop?
6. Practice Problems
Easy
- Title: Reverse Linked List
- One-line prompt: Reverse a singly linked list and return the new head.
- Expected pattern or core idea: Iterative pointer reversal.
- Title: Middle of the Linked List
- One-line prompt: Return the middle node of a linked list.
- Expected pattern or core idea: Slow and fast pointers.
- Title: Linked List Cycle
- One-line prompt: Return whether a linked list contains a cycle.
- Expected pattern or core idea: Visited set baseline versus Floyd's algorithm.
Medium
- Title: Remove Nth Node From End of List
- One-line prompt: Delete the nth node from the end in one pass.
- Expected pattern or core idea: Gap-based two-pointer traversal.
- Title: Odd Even Linked List
- One-line prompt: Group odd-indexed nodes before even-indexed nodes.
- Expected pattern or core idea: Careful pointer partitioning.
- Title: Reorder List
- One-line prompt: Reorder the list by alternating from the front and back halves.
- Expected pattern or core idea: Find middle, reverse second half, then merge.
Hard
- Title: Reverse Nodes in K-Group
- One-line prompt: Reverse nodes in groups of size
kwhile preserving the rest. - Expected pattern or core idea: Segment-based pointer reversal.
- One-line prompt: Reverse nodes in groups of size
- Title: Merge K Sorted Lists
- One-line prompt: Merge many sorted linked lists into one sorted result.
- Expected pattern or core idea: Merge strategy plus heap or divide and conquer.
- Title: Copy List with Random Pointer
- One-line prompt: Clone a linked structure that contains both
nextand random references. - Expected pattern or core idea: Pointer modeling and careful node mapping.
- One-line prompt: Clone a linked structure that contains both
7. Short Recap
The core idea of this chapter is that linked lists are about node connections, and most important operations are really careful pointer updates.
The most important optimization insight is that pointer-based reversal, merge, and cycle detection avoid unnecessary extra arrays or sets when the structure permits it.
The most important implementation warning is to save what you still need before changing a link. Most list bugs come from losing reachability.
This chapter prepares the next chapter by giving you the structural intuition needed to implement stacks, queues, and deques cleanly with either arrays or linked nodes.
8. Coverage Check
- 9.1 Singly linked lists
- 9.2 Doubly linked lists
- 9.3 Circular linked lists
- 9.4 Reversal techniques
- 9.5 Cycle detection
- 9.6 Merge and pointer manipulation problems
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 10: Stack, Queue, and Deque
10: Stack, Queue, and Deque
Goal: Teach learners how stack, queue, and deque behavior works, how to implement these structures with arrays or linked nodes, and how to recognize the simulation and expression problems they solve.
Outcome: By the end of this chapter, you can explain and implement core stack and queue operations, build a circular queue, use a deque for efficient front-and-back maintenance, and solve common parentheses, expression, and simulation problems in Java.
1. Intuition First
Stacks, queues, and deques are not just containers. They are rules about where insertion and removal are allowed.
A simple real-world analogy is a cafeteria. A stack is a pile of trays: last in, first out. A queue is a line of people: first in, first out. A deque is a loading dock where work can happen from both ends.
The core mental model is this: once you know which end you are allowed to touch, a surprising number of problems become simple. Parentheses checking, process scheduling, breadth-like simulations, undo behavior, and monotonic-window maintenance all depend more on operation order than on raw storage.
The most common beginner confusion point is mixing the abstract behavior with one specific implementation. A stack can use an array or linked nodes. A queue can use a linked list or a circular array. The behavior is the contract. The implementation is how you realize it efficiently.
In the roadmap, this chapter closes Part II by turning linear traversal ideas into reusable building blocks that appear throughout recursion, trees, graphs, and advanced interview problems.
2. Core Concepts and Techniques
Concept Cluster: Array-Based and Linked Stacks, Queue, and Circular Queue
Key concepts in this block:
- 10.1 Array-based and linked stacks
- 10.2 Queue and circular queue
Intuition
A stack touches one end only. A queue adds at the back and removes from the front. A circular queue reuses array slots by wrapping around instead of shifting elements.
Why It Matters
These are some of the most reused linear structures in DSA. Their performance depends heavily on choosing the right underlying implementation.
How It Works
Stack:
pushadds to the toppopremoves from the toppeekreads the top without removing it
Queue:
enqueueadds to the reardequeueremoves from the frontfrontreads the next removable value
Circular queue:
- stores
headandsizeorheadandtail - uses modular arithmetic to wrap around the array
- avoids
O(n)shifts on every dequeue
Java Implementation Notes
- For everyday Java use, prefer
ArrayDequeover the legacyStackclass. - Manual array and linked implementations still matter for interviews and invariant understanding.
- Circular queues are best learned with fixed-capacity arrays.
Common Mistakes
- using the wrong end for insertion or removal
- forgetting wrap-around logic in a circular queue
- thinking queue dequeue should shift every element in a well-designed implementation
- underflowing or overflowing a fixed-capacity structure
Quick Example
class ArrayStackQuickExample {
static final class IntStack {
private final int[] data;
private int size;
IntStack(int capacity) {
data = new int[capacity];
}
boolean push(int value) {
if (size == data.length) {
return false;
}
data[size++] = value;
return true;
}
int pop() {
if (size == 0) {
return -1;
}
return data[--size];
}
}
}
Debugging Tip
Print the logical front, rear, or top indices after each operation. Index bugs are easier to see than final wrong answers.
Advanced Note
The abstract operation contract should stay identical even when the implementation changes from array to linked nodes.
Concept Cluster: Deque Operations and Adapter Structures
Key concepts in this block:
- 10.3 Deque operations and use cases
- 10.4 Queue using stacks
- 10.5 Stack using queues
Intuition
A deque supports insertion and removal at both ends. Adapter structures simulate one contract using another contract.
Why It Matters
Deque is the practical workhorse for many advanced linear problems. Queue-using-stacks and stack-using-queues teach you to reason about behavior separately from implementation.
How It Works
Deque use cases:
- monotonic windows
- task scheduling with both ends active
- palindrome-style or bidirectional processing
Queue using stacks:
- either make enqueue easy and dequeue expensive, or the reverse
- the standard practical design uses two stacks for amortized
O(1)queue operations
Stack using queues:
- either rotate after every push or do the expensive work on pop
- the usual interview version rotates the queue after push so the newest item reaches the front
Java Implementation Notes
ArrayDequesupports stack and deque operations efficiently.- Queue-using-stacks is an early example of amortized analysis from Chapter 2.
- When teaching the concept, keep operation contracts explicit in comments or method names.
Common Mistakes
- forgetting which end of the deque represents the current best candidate in monotonic problems
- assuming amortized
O(1)means every operation is individually constant time - rotating a queue incorrectly when simulating a stack
- not transferring elements between stacks at the right moment
Quick Example
import java.util.ArrayDeque;
import java.util.Deque;
class QueueUsingStacksQuickExample {
static final class MyQueue {
private final Deque<Integer> inStack = new ArrayDeque<>();
private final Deque<Integer> outStack = new ArrayDeque<>();
void enqueue(int value) {
inStack.push(value);
}
int dequeue() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.isEmpty() ? -1 : outStack.pop();
}
}
}
Debugging Tip
List the operations in order on paper and compare them with the data-structure state after each step. Adapter bugs usually show up as contract violations, not syntax mistakes.
Advanced Note
Deque often solves problems that look unrelated to stacks or queues at first glance, especially when you need a best candidate from one side and expiry from the other.
Concept Cluster: Parentheses, Expression, and Simulation Problems
Key concepts in this block:
- 10.6 Parentheses, expression, and simulation problems
Intuition
These problems are really about reversible order, pending work, or first-ready processing.
Why It Matters
Once you see the operational rule, the right structure often becomes obvious. Nested expressions are stack-shaped. Line processing is queue-shaped. Window maxima often need deque behavior.
How It Works
Stack-shaped problems:
- matching nested symbols
- evaluating postfix expressions
- undo or backtracking-like simulations
Queue-shaped problems:
- turn-based processing
- round-robin simulation
- breadth-style scheduling
Deque-shaped problems:
- keep candidates in order while dropping expired ones
- sliding maxima or minima
Java Implementation Notes
- For stacks and deques,
ArrayDequeis usually the best standard-library default. - For queue behavior,
ArrayDequealso works well unless the problem requires specialized semantics. - Manual implementations are still worth writing once so the library is not a black box.
Common Mistakes
- pushing opening symbols but checking closings against the wrong order
- confusing postfix and infix evaluation rules
- storing values in a deque when indexes are needed for expiration logic
- picking a queue when the task really needs last-in, first-out behavior
Quick Example
import java.util.ArrayDeque;
import java.util.Deque;
class ParenthesesQuickExample {
static boolean isValid(String text) {
Deque<Character> stack = new ArrayDeque<>();
for (int index = 0; index < text.length(); index++) {
char current = text.charAt(index);
if (current == '(' || current == '[' || current == '{') {
stack.push(current);
} else {
if (stack.isEmpty()) {
return false;
}
char open = stack.pop();
if ((current == ')' && open != '(')
|| (current == ']' && open != '[')
|| (current == '}' && open != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
}
Debugging Tip
If a simulation problem feels confusing, ask: which item should leave first from the currently pending work? That question often identifies the right structure immediately.
Advanced Note
Many so-called simulation problems are secretly data-structure selection problems.
3. Worked Examples and Full Solutions
Worked Example 1: Valid Parentheses
Problem Statement
Given a string containing only the characters ()[]{}, return true if the brackets are correctly matched and nested.
Why This Example Matters
It is the canonical stack problem. The last unmatched opening bracket must be matched first.
Constraints or Assumptions
- input contains only bracket characters
- every closing bracket must match the most recent unmatched opening bracket
- the full string must be consumed with no leftovers
Brute-Force Approach
Repeatedly remove every occurrence of (), [], and {} until the string stops changing. Return true if nothing remains.
This works, but it repeatedly rebuilds strings and hides the real structural rule.
Better Approach
Use a stack of opening brackets. On each closing bracket, check whether it matches the current stack top.
Why the Better Approach Works
Nested delimiters obey last-in, first-out order. The most recent still-open bracket is the only one allowed to close next.
Pragmatic Java Choice
Use ArrayDeque<Character> as a stack in Java. It is the practical standard choice.
Java Solution
import java.util.ArrayDeque;
import java.util.Deque;
class ValidParenthesesExample {
static boolean isValidBruteForce(String text) {
String previous;
String current = text;
do {
previous = current;
current = current.replace("()", "")
.replace("[]", "")
.replace("{}", "");
} while (!current.equals(previous));
return current.isEmpty();
}
static boolean isValidOptimized(String text) {
Deque<Character> stack = new ArrayDeque<>();
for (int index = 0; index < text.length(); index++) {
char current = text.charAt(index);
if (current == '(' || current == '[' || current == '{') {
stack.push(current);
} else {
if (stack.isEmpty()) {
return false;
}
char open = stack.pop();
if ((current == ')' && open != '(')
|| (current == ']' && open != '[')
|| (current == '}' && open != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
}
Dry Run
Use text = "{[()]}".
Optimized approach:
- read
{, push - read
[, push - read
(, push - read
), pop(, match - read
], pop[, match - read
}, pop{, match - stack ends empty -> return
true
Time and Space Complexity
- Brute force: often
O(n^2)time because repeated replacements rebuild strings - Better approach:
O(n)time,O(n)extra space in the worst case
Edge Cases
- empty string ->
true - starts with a closing bracket ->
false - unmatched opening brackets left at the end ->
false
Common Mistakes
- using queue behavior instead of stack behavior
- not checking whether the stack is empty before popping
- only checking counts of brackets instead of nesting order
Worked Example 2: Design a Circular Queue
Problem Statement
Design a fixed-capacity queue supporting enqueue, dequeue, front, rear, isEmpty, and isFull.
Why This Example Matters
It teaches the difference between naive queue behavior on an array and an efficient circular-array implementation.
Constraints or Assumptions
- capacity is fixed
- operations should not shift all elements on each dequeue
- return
-1forfrontorrearwhen the queue is empty
Brute-Force Approach
Store the queue in an array and shift every element left on each dequeue.
This matches the behavior contract but wastes time.
Better Approach
Use a circular array with head and size so both enqueue and dequeue are O(1).
Why the Better Approach Works
The logical front moves through the array without requiring physical shifts. The tail position is computed from head + size modulo the capacity.
Pragmatic Java Choice
Manual implementation is worth doing here. It teaches the invariant clearly and explains why circular queues exist.
Java Solution
class CircularQueueExample {
static final class NaiveQueue {
private final int[] data;
private int size;
NaiveQueue(int capacity) {
data = new int[capacity];
}
boolean enqueue(int value) {
if (isFull()) {
return false;
}
data[size++] = value;
return true;
}
boolean dequeue() {
if (isEmpty()) {
return false;
}
for (int index = 1; index < size; index++) {
data[index - 1] = data[index];
}
size--;
return true;
}
int front() {
return isEmpty() ? -1 : data[0];
}
int rear() {
return isEmpty() ? -1 : data[size - 1];
}
boolean isEmpty() {
return size == 0;
}
boolean isFull() {
return size == data.length;
}
}
static final class CircularQueue {
private final int[] data;
private int head;
private int size;
CircularQueue(int capacity) {
data = new int[capacity];
}
boolean enqueue(int value) {
if (isFull()) {
return false;
}
int tail = (head + size) % data.length;
data[tail] = value;
size++;
return true;
}
boolean dequeue() {
if (isEmpty()) {
return false;
}
head = (head + 1) % data.length;
size--;
return true;
}
int front() {
return isEmpty() ? -1 : data[head];
}
int rear() {
if (isEmpty()) {
return -1;
}
int tailIndex = (head + size - 1) % data.length;
return data[tailIndex];
}
boolean isEmpty() {
return size == 0;
}
boolean isFull() {
return size == data.length;
}
}
}
Dry Run
Use capacity 3.
Optimized approach:
- enqueue
10->head = 0,size = 1 - enqueue
20-> tail index1,size = 2 - enqueue
30-> tail index2,size = 3 - dequeue -> move
headto1,size = 2 - enqueue
40-> tail index(1 + 2) % 3 = 0, reuse freed slot
Queue order is now 20, 30, 40 without any shifting.
Time and Space Complexity
- Brute force:
enqueueO(1),dequeueO(n),O(n)space - Better approach:
O(1)time for each main operation,O(n)space
Edge Cases
- dequeue from empty queue ->
false - enqueue into full queue ->
false - wrapping from the last array index back to
0
Common Mistakes
- confusing capacity with current size
- not using modular arithmetic for wrap-around
- losing track of whether
headpoints to the current front or the next insertion slot
Worked Example 3: Sliding Window Maximum
Problem Statement
Given an integer array and a window size k, return the maximum value in every contiguous window of length k.
Why This Example Matters
It is the most important deque use case in early DSA. It combines window expiry on one end with dominance removal on the other.
Constraints or Assumptions
kis positive- if
kis invalid, return an empty array - windows are contiguous and fixed-size
Brute-Force Approach
For each window, scan all k elements and compute the maximum directly.
This works, but it costs O(nk) time.
Better Approach
Maintain a deque of indexes whose values are in decreasing order. Remove expired indexes from the front and dominated indexes from the back.
Why the Better Approach Works
The front of the deque always stores the best candidate for the current window. Any smaller value behind a newly added larger value can never become the maximum while that larger value remains in the window.
Pragmatic Java Choice
Store indexes, not values, so you can tell when an element has left the window.
Java Solution
import java.util.ArrayDeque;
import java.util.Deque;
class SlidingWindowMaximumExample {
static int[] maxWindowBruteForce(int[] values, int k) {
if (k <= 0 || k > values.length) {
return new int[0];
}
int[] result = new int[values.length - k + 1];
for (int start = 0; start + k <= values.length; start++) {
int maximum = values[start];
for (int index = start + 1; index < start + k; index++) {
maximum = Math.max(maximum, values[index]);
}
result[start] = maximum;
}
return result;
}
static int[] maxWindowOptimized(int[] values, int k) {
if (k <= 0 || k > values.length) {
return new int[0];
}
int[] result = new int[values.length - k + 1];
Deque<Integer> deque = new ArrayDeque<>();
for (int right = 0; right < values.length; right++) {
while (!deque.isEmpty() && deque.peekFirst() <= right - k) {
deque.pollFirst();
}
while (!deque.isEmpty() && values[deque.peekLast()] <= values[right]) {
deque.pollLast();
}
deque.offerLast(right);
if (right >= k - 1) {
result[right - k + 1] = values[deque.peekFirst()];
}
}
return result;
}
}
Dry Run
Use values = [1, 3, -1, -3, 5, 3, 6, 7] and k = 3.
Optimized approach:
- process
1, deque[0] - process
3, remove index0because3dominates1, deque[1] - process
-1, deque[1, 2], first full window max is3 - process
-3, deque[1, 2, 3], next max still3 - process
5, remove expired1, then remove dominated3and2, deque[4], max becomes5 - continue similarly to produce
[3, 3, 5, 5, 6, 7]
Time and Space Complexity
- Brute force:
O(nk)time,O(1)extra space beyond the output - Better approach:
O(n)time,O(k)extra space
Edge Cases
k = 1-> every element is its own window maximumkequal to array length -> one answer- repeated equal values still work correctly with the dominance rule used consistently
Common Mistakes
- storing values instead of indexes in the deque
- forgetting to remove expired indexes before reading the maximum
- removing from the wrong end when enforcing monotonic order
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- array-based or linked manual implementations usually keep core operations at
O(1)when designed correctly - naive array queues can degrade dequeue to
O(n)due to shifting - deque-based optimizations can reduce fixed-window brute force from
O(nk)toO(n) - adapter structures such as queue using stacks rely on amortized, not worst-case-per-operation, reasoning
Choose manual implementations when:
- you need to learn or prove the invariant
- the interview asks you to design the structure
- understanding index or pointer behavior is part of the goal
Choose library support when:
- the problem is about the algorithm using the structure, not designing it
ArrayDequematches the required semantics cleanly- you want reliable
O(1)-style end operations without re-implementing container details
Recognition signals for these structures:
- last-opened item must close first -> stack
- earliest pending item must process first -> queue
- both ends need efficient access -> deque
- the problem is described as parentheses, expression evaluation, undo, scheduling, or monotonic candidate maintenance
Signals not to force these techniques:
- the problem is really about random access by index
- ordering alone is not the core issue
- a simpler array scan solves the task just as well
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- using the wrong end of the structure
- forgetting empty or full checks
- mismanaging wrap-around in circular queues
- using values instead of indexes in deque window problems
Boundary and mutation risks:
- empty input for parentheses or simulation tasks
- fixed-capacity overflow and underflow
- stale elements remaining in a deque after they expire from a window
- incorrect amortized reasoning for queue using stacks
Short debugging checklist:
- What operation contract does this problem need: LIFO, FIFO, or both ends?
- Which end am I adding to and removing from?
- If the structure is circular, how do I detect full versus empty?
- If I am using a deque for a window, how do expired elements leave?
- Am I solving the structure-design problem or the algorithm-that-uses-the-structure problem?
6. Practice Problems
Easy
- Title: Valid Parentheses
- One-line prompt: Decide whether a bracket string is correctly nested.
- Expected pattern or core idea: Stack for last unmatched opener.
- Title: Implement Queue using Stacks
- One-line prompt: Build FIFO behavior using only stack operations.
- Expected pattern or core idea: Two-stack transfer with amortized analysis.
- Title: Baseball Game
- One-line prompt: Evaluate a sequence of score operations with undo-like behavior.
- Expected pattern or core idea: Stack simulation.
Medium
- Title: Evaluate Reverse Polish Notation
- One-line prompt: Evaluate a postfix expression.
- Expected pattern or core idea: Stack-based operand management.
- Title: Daily Temperatures
- One-line prompt: For each day, find how long until a warmer temperature appears.
- Expected pattern or core idea: Monotonic stack of indexes.
- Title: Design Circular Queue
- One-line prompt: Support queue operations efficiently on fixed capacity.
- Expected pattern or core idea: Circular array with front and size.
Hard
- Title: Sliding Window Maximum
- One-line prompt: Return the maximum value in every fixed-size window.
- Expected pattern or core idea: Monotonic deque of indexes.
- Title: Largest Rectangle in Histogram
- One-line prompt: Find the maximum rectangle area in a histogram.
- Expected pattern or core idea: Monotonic stack with boundary reasoning.
- Title: Basic Calculator
- One-line prompt: Evaluate an arithmetic expression with parentheses.
- Expected pattern or core idea: Stack-based expression state management.
7. Short Recap
The core idea of this chapter is that stack, queue, and deque problems become much easier once you identify which end should process work next.
The most important optimization insight is that the right linear structure often turns repeated shifting or repeated rescanning into clean O(1) end operations or one-pass simulations.
The most important implementation warning is to separate behavior from implementation. The contract decides the structure. The array or linked representation only realizes it efficiently.
This chapter prepares the next chapter by making stack behavior intuitive before recursion formalizes the call stack and backtracking ideas.
8. Coverage Check
- 10.1 Array-based and linked stacks
- 10.2 Queue and circular queue
- 10.3 Deque operations and use cases
- 10.4 Queue using stacks
- 10.5 Stack using queues
- 10.6 Parentheses, expression, and simulation problems
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 11: Recursion
11: Recursion
Goal: Teach learners how recursive thinking works, how to design safe base cases, and how to use recursion for search, memoization, and backtracking without treating it as magic.
Outcome: By the end of this chapter, you can trace recursive calls, explain the call stack, write base and recursive cases deliberately, recognize when memoization or backtracking is needed, and convert simple recursive logic into iteration when Java stack depth becomes a risk.
1. Intuition First
Recursion matters because many problems are easier to describe in terms of a smaller version of themselves. Instead of handling the whole problem at once, you define how to solve one step and trust the same logic on a reduced input.
A simple real-world analogy is opening a stack of nested gift boxes. To reach the smallest box, you repeat the same action: open the current box and move to the next smaller one. When you reach the smallest box, you stop. That stopping rule is the base case.
The core mental model is this: recursion is a function calling itself on a smaller state until a stopping condition is reached, then the answers return in reverse order through the call stack. The call stack is the runtime structure that remembers where each unfinished call should continue.
The most common beginner confusion point is thinking recursion is a different kind of logic from loops. It is not. It is another way to express repetition, but each step stores its own local state on the call stack.
In the roadmap, this chapter starts Part III. It turns pattern familiarity from Part II into reasoning about correctness, state, and control flow. That foundation is required for binary search invariants, divide and conquer, tree traversals, and dynamic programming later.
2. Core Concepts and Techniques
Concept Cluster: Base Cases, Recursive Cases, and the Call Stack
Key concepts in this block:
- 11.1 Base case and recursive case design
- 11.2 Understanding the call stack
Intuition
Every recursive function needs two parts: the rule for when to stop and the rule for how to shrink the problem. The call stack keeps track of all unfinished work.
Why It Matters
Most recursion bugs come from one of three causes: no valid stopping rule, no real progress toward the stop, or returning the wrong value while calls unwind.
How It Works
- the base case handles the smallest input directly
- the recursive case moves toward that smallest input
- each function call gets its own local variables and return address
- when the deepest call finishes, earlier calls resume one by one
For factorial(4), the stack grows like this:
factorial(4)waits forfactorial(3)factorial(3)waits forfactorial(2)factorial(2)waits forfactorial(1)factorial(1)returns immediately- the answers unwind upward
Java Implementation Notes
- Keep the base case near the top of the method so it is obvious.
- Prefer descriptive parameter names because each call represents a different state.
- Java does not expose the call stack as a normal collection, so you must reason about it mentally or with a debugger.
Common Mistakes
- forgetting the base case entirely
- making a recursive call that does not shrink the problem
- assuming one call can see another call's local variables
- returning before combining the recursive result correctly
Quick Example
class CountdownQuickExample {
static void printCountdown(int value) {
if (value == 0) {
System.out.println("done");
return;
}
System.out.println(value);
printCountdown(value - 1);
}
}
Debugging Tip
Write the parameter value beside each call on paper. If the values do not move toward the base case, the recursion is wrong.
Advanced Note
A recursive definition is only useful if the subproblem is structurally simpler and the combining step is correct. That same idea reappears in divide and conquer and dynamic programming.
Concept Cluster: Tail Recursion and Converting Recursion to Iteration
Key concepts in this block:
- 11.3 Tail recursion
- 11.6 Converting recursion to iteration
Intuition
Tail recursion means the recursive call is the last operation in the function. That usually means the function's entire state can be carried forward explicitly.
Why It Matters
Tail-recursive logic is easier to convert into an iterative loop. That matters in Java because the language does not guarantee tail-call optimization.
How It Works
- non-tail recursion does work after the recursive call returns
- tail recursion passes all needed state into the next call
- when that state is explicit, a loop can usually replace the call stack
Example idea:
- non-tail factorial:
return n * factorial(n - 1) - tail-recursive shape: keep an accumulator and call the next state directly
Java Implementation Notes
- Prefer iteration over deep tail recursion in Java for production-style safety.
- If you convert recursion to iteration, identify what each stack frame was storing and make those values explicit variables or a manual stack.
- Tail recursion improves clarity of state transitions even when you still implement the final version iteratively.
Common Mistakes
- calling a method tail-recursive when extra work still happens after the call
- converting recursion to iteration but losing one piece of per-call state
- forgetting that Java recursion depth is limited by the call stack size
Quick Example
class SumQuickExample {
static int recursiveSum(int value) {
if (value == 0) {
return 0;
}
return value + recursiveSum(value - 1);
}
static int iterativeSum(int value) {
int total = 0;
while (value > 0) {
total += value;
value--;
}
return total;
}
}
Debugging Tip
Ask what information one call frame must remember before the next call starts. That list tells you what an iterative rewrite must preserve.
Advanced Note
For tree or graph traversals, conversion to iteration usually needs an explicit stack because one variable is not enough to remember branching state.
Concept Cluster: Backtracking and Memoization Basics
Key concepts in this block:
- 11.4 Backtracking basics
- 11.5 Memoization basics
Intuition
Backtracking explores choices, commits to one, and then undoes that choice to try the next path. Memoization stores answers for repeated subproblems so you do not solve the same state again.
Why It Matters
These are the first two big upgrades to plain recursion. Backtracking makes recursion useful for search spaces. Memoization makes recursion efficient on overlapping subproblems.
How It Works
Backtracking:
- choose
- recurse
- undo the choice
Memoization:
- identify the state by parameters
- before computing, check whether that state was already solved
- store the answer the first time it is computed
These two patterns solve different bottlenecks:
- backtracking handles branching decision trees
- memoization handles repeated work across branches
Java Implementation Notes
- For backtracking, copy the current path only when storing a finished answer.
- For memoization, arrays are faster when the state is a simple index range; maps are better when the state is sparse or composite.
- Be precise about whether cached values can be zero or negative so you do not confuse an uninitialized state with a real answer.
Common Mistakes
- forgetting to undo a choice in backtracking
- reusing the same mutable list object in the final answer
- memoizing with the wrong state key
- storing partial results before they are actually complete
Quick Example
import java.util.ArrayList;
import java.util.List;
class BacktrackingQuickExample {
static List<List<Integer>> buildSubsets(int[] values) {
List<List<Integer>> result = new ArrayList<>();
backtrack(values, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] values, int index, List<Integer> current, List<List<Integer>> result) {
if (index == values.length) {
result.add(new ArrayList<>(current));
return;
}
backtrack(values, index + 1, current, result);
current.add(values[index]);
backtrack(values, index + 1, current, result);
current.remove(current.size() - 1);
}
}
Debugging Tip
In backtracking, print the path both before and after the undo step. If the path does not return to the previous state, later branches will be corrupted.
Advanced Note
Memoization is the bridge from recursive intuition to dynamic programming. Once the state and recurrence are stable, tabulation becomes possible.
3. Worked Examples and Full Solutions
Worked Example 1: Fibonacci Number
Problem Statement
Given n, return the nth Fibonacci number where F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2).
Why This Example Matters
It is the classic example of recursion that is easy to write but inefficient without memoization. It makes the cost of repeated subproblems visible.
Constraints or Assumptions
nis non-negative- assume the answer fits in
intfor the chosen test cases - the goal is to compare plain recursion and memoized recursion
Brute-Force Approach
Use the direct recursive definition. For each n, recursively compute n - 1 and n - 2.
This is simple, but it recomputes the same Fibonacci values many times.
Better Approach
Use memoization. Store the answer for each n the first time it is computed, then reuse it.
Why the Better Approach Works
The recursive relation is still correct, but overlapping subproblems disappear because each state is solved once.
Pragmatic Java Choice
Use an int[] cache initialized with -1 because the state is just one integer index from 0 to n.
Java Solution
import java.util.Arrays;
class FibonacciExample {
static int fibonacciBruteForce(int n) {
if (n <= 1) {
return n;
}
return fibonacciBruteForce(n - 1) + fibonacciBruteForce(n - 2);
}
static int fibonacciMemoized(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return fibonacciMemoized(n, memo);
}
private static int fibonacciMemoized(int n, int[] memo) {
if (n <= 1) {
return n;
}
if (memo[n] != -1) {
return memo[n];
}
memo[n] = fibonacciMemoized(n - 1, memo) + fibonacciMemoized(n - 2, memo);
return memo[n];
}
}
Dry Run
Use n = 6.
Brute-force recursion starts with:
F(6)needsF(5)andF(4)F(5)needsF(4)andF(3)F(4)is already appearing again before the firstF(4)is even finished
Memoized version:
- compute
F(6) - solve
F(5)andF(4)as needed - once
F(4)becomes3, store it - later requests for
F(4)return immediately from the cache - final result is
8
Time and Space Complexity
- Brute force:
O(2^n)time,O(n)call stack space - Better approach:
O(n)time,O(n)extra space for memo plusO(n)call stack space
Edge Cases
n = 0returns0n = 1returns1- very large
ncan still risk stack depth and integer overflow
Common Mistakes
- using
0as both a valid answer and an uninitialized cache marker - forgetting the
n <= 1base case - assuming memoization removes call stack usage when it only removes repeated work
Worked Example 2: Generate All Subsets
Problem Statement
Given an array of distinct integers, return all possible subsets.
Why This Example Matters
It is the cleanest first backtracking problem. You make a binary choice at each index: include the element or skip it.
Constraints or Assumptions
- input values are distinct
- output order does not matter
- all subsets should be included, including the empty subset
Brute-Force Approach
Use bitmasking. For each number from 0 to (1 << n) - 1, use the bits to decide which elements belong to the current subset.
This works well, but it does not teach the recursive decision-tree structure.
Better Approach
Use backtracking with an index and a current path. At each index, first skip the element, then include it, and undo the inclusion afterward.
Why the Better Approach Works
Each recursive level represents one decision point. The two branches cover all possibilities exactly once, and the undo step restores the previous state before exploring the next branch.
Pragmatic Java Choice
Use ArrayList for the current path and copy it only when a full subset is complete.
Java Solution
import java.util.ArrayList;
import java.util.List;
class SubsetsExample {
static List<List<Integer>> subsetsBitmask(int[] values) {
List<List<Integer>> result = new ArrayList<>();
int totalMasks = 1 << values.length;
for (int mask = 0; mask < totalMasks; mask++) {
List<Integer> subset = new ArrayList<>();
for (int bit = 0; bit < values.length; bit++) {
if ((mask & (1 << bit)) != 0) {
subset.add(values[bit]);
}
}
result.add(subset);
}
return result;
}
static List<List<Integer>> subsetsBacktracking(int[] values) {
List<List<Integer>> result = new ArrayList<>();
backtrack(values, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] values, int index, List<Integer> current, List<List<Integer>> result) {
if (index == values.length) {
result.add(new ArrayList<>(current));
return;
}
backtrack(values, index + 1, current, result);
current.add(values[index]);
backtrack(values, index + 1, current, result);
current.remove(current.size() - 1);
}
}
Dry Run
Use values = [1, 2].
Backtracking path:
- start at index
0with[] - skip
1, go to index1 - skip
2, store[] - include
2, store[2], undo to[] - return and include
1, current is[1] - skip
2, store[1] - include
2, store[1, 2], undo twice
Final subsets are [], [2], [1], [1, 2].
Time and Space Complexity
- Brute force:
O(n * 2^n)time,O(n)extra space per constructed subset - Better approach:
O(n * 2^n)time,O(n)recursion depth plus output space
Edge Cases
- empty array returns
[[]] - one element returns two subsets
- duplicate input values would create repeated subsets unless handled differently
Common Mistakes
- not removing the last choice after the recursive call
- adding
currentdirectly to the result without copying it - using the wrong stopping condition
Worked Example 3: Factorial, Tail Recursion, and Iteration
Problem Statement
Given a non-negative integer n, return n!.
Why This Example Matters
It is the simplest way to compare basic recursion, tail-recursive state passing, and an iterative rewrite that avoids stack growth in Java.
Constraints or Assumptions
0 <= n <= 20so the answer fits inlong- negative input is invalid
- the focus is control flow, not big-number arithmetic
Brute-Force Approach
Use direct recursion: n! = n * (n - 1)!.
This is readable, but every call must wait for the deeper call to return before multiplying.
Better Approach
Reshape the logic into tail-recursive form with an accumulator, then implement the final production version as a loop.
Why the Better Approach Works
Once the unfinished multiplication is moved into the accumulator, each step only needs the next n and the current accumulated product. That state maps directly to iterative variables.
Pragmatic Java Choice
In Java, prefer the iterative version for large input ranges because the language does not guarantee tail-call optimization.
Java Solution
class FactorialExample {
static long factorialRecursive(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
if (n <= 1) {
return 1L;
}
return n * factorialRecursive(n - 1);
}
static long factorialTailRecursive(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
return factorialTailRecursive(n, 1L);
}
private static long factorialTailRecursive(int n, long accumulator) {
if (n <= 1) {
return accumulator;
}
return factorialTailRecursive(n - 1, accumulator * n);
}
static long factorialIterative(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
long result = 1L;
for (int value = 2; value <= n; value++) {
result *= value;
}
return result;
}
}
Dry Run
Use n = 4.
Direct recursion:
factorialRecursive(4)waits for4 * factorialRecursive(3)factorialRecursive(3)waits for3 * factorialRecursive(2)factorialRecursive(2)waits for2 * factorialRecursive(1)factorialRecursive(1)returns1- unwind to get
2, then6, then24
Tail-recursive state:
(4, 1)becomes(3, 4)(3, 4)becomes(2, 12)(2, 12)becomes(1, 24)- return
24
Iterative version follows the same state updates with loop variables.
Time and Space Complexity
- Brute force:
O(n)time,O(n)call stack space - Better approach: tail-recursive form is still
O(n)time andO(n)stack space in Java; iterative conversion isO(n)time andO(1)extra space
Edge Cases
n = 0returns1n = 1returns1- negative input should be rejected
n > 20overflowslong
Common Mistakes
- forgetting that
0! = 1 - claiming tail recursion is automatically stack-safe in Java
- converting to iteration but starting the loop with the wrong initial product
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- plain recursion can be clean but may repeat work or consume deep call stack space
- memoization often reduces repeated recursive work from exponential time to linear or polynomial time, depending on the state space
- backtracking explores all valid branches, so it is often exponential by nature, but recursion keeps the search logic clear
- tail-recursive state design can make iterative conversion straightforward, even though Java still keeps recursive calls on the stack
Choose plain recursion when:
- the problem naturally reduces to a smaller version of itself
- the depth is modest
- the logic is clearer recursively than iteratively
Choose memoization when:
- the same parameter state appears repeatedly
- the brute-force recursive tree has visible overlap
- correctness is easier to derive recursively than bottom-up at first
Choose backtracking when:
- you are enumerating combinations, subsets, paths, or assignments
- each step branches into choices
- you need to explore a decision tree and possibly undo state
Choose iteration instead of recursion when:
- the depth could be large enough to risk stack overflow
- the recursive state is simple enough to carry with variables or a manual stack
- Java runtime safety matters more than matching the mathematical definition directly
Recognition signals for recursion:
- the problem statement says solve the same task on a smaller input
- the structure is nested or hierarchical
- you can describe a base case and a reducing step cleanly
Signals not to force recursion:
- a simple loop is more direct
- the depth could approach input size in a large dataset
- the state is easier to maintain iteratively than through many call frames
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- missing or incorrect base cases
- recursive calls that do not move toward the base case
- mutating shared lists in backtracking without undoing the change
- memo caches that treat a legitimate answer as if it means uninitialized
- stack overflow from deep recursion on large input
Boundary and state risks:
- empty arrays or strings in recursive traversal problems
- index values that move past array bounds
- negative input in math-style recursive functions
- exponential branching when you forget pruning or memoization
Short debugging checklist:
- What is the smallest valid input, and does my base case handle it?
- Which parameter strictly moves toward the base case on every path?
- What state does each call need to remember before the next call?
- If I am using backtracking, where exactly do I undo the last choice?
- If I am using memoization, is my cache key the full state?
- Would an iterative rewrite be safer for this depth in Java?
6. Practice Problems
Easy
- Title: Fibonacci Number
- One-line prompt: Return the
nth Fibonacci number. - Expected pattern or core idea: Base case design plus memoization.
- One-line prompt: Return the
- Title: Power of Three
- One-line prompt: Decide whether a number can be repeatedly divided to reach the base case.
- Expected pattern or core idea: Recursive reduction with a clear stop condition.
- Title: Reverse String
- One-line prompt: Reverse a character array in place.
- Expected pattern or core idea: Recursive shrinking from both ends or iterative conversion.
Medium
- Title: Generate Parentheses
- One-line prompt: Generate all well-formed parentheses strings of length
2n. - Expected pattern or core idea: Backtracking with validity constraints.
- One-line prompt: Generate all well-formed parentheses strings of length
- Title: Subsets
- One-line prompt: Return every subset of a distinct integer array.
- Expected pattern or core idea: Backtracking decision tree.
- Title: Climbing Stairs
- One-line prompt: Count how many ways there are to climb to the top.
- Expected pattern or core idea: Memoized recursion over overlapping subproblems.
Hard
- Title: N-Queens
- One-line prompt: Place queens so none attack each other.
- Expected pattern or core idea: Backtracking with state pruning.
- Title: Word Search
- One-line prompt: Determine whether a word can be traced through a grid.
- Expected pattern or core idea: Recursive DFS-style backtracking with visited-state control.
- Title: Different Ways to Add Parentheses
- One-line prompt: Return all possible results from computing an expression with different parenthesizations.
- Expected pattern or core idea: Divide-and-conquer recursion with memoization.
7. Short Recap
The core idea of this chapter is that recursion solves a problem by reducing it to smaller versions of the same problem until a safe base case is reached.
The most important optimization insight is that memoization fixes repeated subproblem work, while backtracking manages branching search by choosing and undoing state carefully.
The most important implementation warning is to be explicit about progress toward the base case and to remember that Java recursion depth is limited.
This chapter prepares the next chapter by making recursive reasoning and invariants more natural before binary search asks you to prove why a shrinking search space stays correct.
8. Coverage Check
- 11.1 Base case and recursive case design
- 11.2 Understanding the call stack
- 11.3 Tail recursion
- 11.4 Backtracking basics
- 11.5 Memoization basics
- 11.6 Converting recursion to iteration
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 12: Binary Search
12: Binary Search
Goal: Teach learners how binary search works as a shrinking search-space technique, how to maintain correct search invariants, and how to extend the idea beyond exact lookup.
Outcome: By the end of this chapter, you can implement iterative and recursive binary search, compute lower and upper bounds, apply binary search to monotonic answer spaces, and reason about off-by-one behavior using explicit invariants.
1. Intuition First
Binary search matters because it replaces repeated scanning with repeated elimination. If the data or answer space has order, you can often throw away half of the remaining possibilities at each step.
A simple real-world analogy is looking up a name in a printed dictionary. You do not read page by page from the start. You open near the middle, decide whether the target is before or after that point, and keep narrowing the range.
The core mental model is this: binary search works on an ordered space and maintains a range where the answer must still exist. Every comparison must preserve that guarantee.
The most common beginner confusion point is thinking binary search is only about finding an exact value in a sorted array. That is only the first form. The deeper idea is searching any monotonic space where one side is impossible and the other side is possible.
In the roadmap, this chapter builds directly on recursion and correctness reasoning. It also prepares you for divide and conquer, answer-space search, and ordered structures later.
2. Core Concepts and Techniques
Concept Cluster: Exact Lookup with Iterative and Recursive Binary Search
Key concepts in this block:
- 12.1 Iterative binary search
- 12.2 Recursive binary search
Intuition
If the array is sorted, comparing the middle element with the target tells you which half cannot contain the answer.
Why It Matters
This is one of the most common interview techniques because it transforms O(n) search into O(log n) search when ordering is available.
How It Works
- keep two boundaries, usually
leftandright - compute the middle index safely
- if the middle is the target, return it
- if the middle is too small, discard the left half including
mid - if the middle is too large, discard the right half including
mid
Iterative and recursive versions apply the same logic. The only difference is whether the shrinking range is stored in loop variables or in call frames.
Java Implementation Notes
- Use
left + (right - left) / 2to computemidsafely. - The iterative version is usually the practical default in Java.
- Recursive binary search is useful for learning and for divide-and-conquer symmetry, but it adds call stack usage.
Common Mistakes
- using
while (left < right)when the intended invariant needsleft <= right - forgetting to move past
mid, which causes infinite loops - searching unsorted data
- returning too early without checking the full invariant
Quick Example
class BinarySearchQuickExample {
static int search(int[] values, int target) {
int left = 0;
int right = values.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (values[mid] == target) {
return mid;
}
if (values[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
Debugging Tip
Print left, mid, and right on every iteration. If they stop changing, your update rule is wrong.
Advanced Note
The important part is not the loop shape. It is the invariant: what property is guaranteed about the remaining range after every step?
Concept Cluster: Lower Bound and Upper Bound
Key concepts in this block:
- 12.3 Lower bound and upper bound
Intuition
Sometimes you do not need an exact match. You need the first position where a value could appear, or the first position strictly greater than a value.
Why It Matters
Lower and upper bound solve insert-position problems, range-counting problems, duplicate handling, and many frequency queries.
How It Works
- lower bound: first index
iwherevalues[i] >= target - upper bound: first index
iwherevalues[i] > target - use a half-open search range like
[left, right)to keep the invariant clean - when the predicate at
midis true, keep the left half includingmid - otherwise move
lefttomid + 1
Java Implementation Notes
- Lower and upper bound become much easier when you think in terms of a boolean predicate over indices.
- Half-open intervals often reduce off-by-one errors.
- These forms are more reusable than exact-match code for interview problems.
Common Mistakes
- returning
middirectly instead of the converged boundary - mixing up
>=and>between lower and upper bound - failing to handle the case where the answer is
values.length
Quick Example
class BoundsQuickExample {
static int lowerBound(int[] values, int target) {
int left = 0;
int right = values.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (values[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
Debugging Tip
State the predicate in plain language before coding. For lower bound, ask: is this position already large enough?
Advanced Note
Many range-count problems reduce to upperBound(target) - lowerBound(target).
Concept Cluster: Binary Search on Answer, Templates, Invariants, and Edge Cases
Key concepts in this block:
- 12.4 Binary search on answer
- 12.5 Templates, invariants, and edge cases
Intuition
You can binary-search an answer even when the answer is not stored in an array, as long as you can test whether a candidate answer is feasible and the feasibility changes only once.
Why It Matters
This is one of the most important transitions from mechanical coding to problem recognition. Many interview questions hide binary search behind words like minimum feasible or maximum possible.
How It Works
- define a search range of candidate answers
- define a monotonic predicate such as canFinish(mid)
- if
midis feasible, keep the half that still contains the optimal answer - otherwise discard it
- make the invariant explicit: for example, all values below
leftare impossible, all values at or aboverightare feasible
Java Implementation Notes
- Write the predicate first. If the predicate is not monotonic, binary search does not apply.
- Prefer a reusable template with named invariants over memorizing many small code variations.
- Watch for overflow in arithmetic problems by using division-based checks when possible.
Common Mistakes
- applying binary search when feasibility is not monotonic
- choosing a search range that does not contain the answer
- mixing exact-match logic with answer-space logic
- not proving which side remains feasible or infeasible after each update
Quick Example
class SquareRootQuickExample {
static int floorSqrt(int target) {
int left = 0;
int right = target;
int answer = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= target / Math.max(1, mid)) {
answer = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return answer;
}
}
Debugging Tip
Write one sentence for the invariant before coding. If you cannot explain what is guaranteed on each side of the boundary, the template is not ready.
Advanced Note
Binary search templates become dramatically easier when you think in terms of finding the first true or last true position of a monotonic predicate.
3. Worked Examples and Full Solutions
Worked Example 1: Search for a Target in a Sorted Array
Problem Statement
Given a sorted array of integers and a target value, return the index of the target or -1 if it does not exist.
Why This Example Matters
It is the canonical exact-match binary search problem and the foundation for every later variant.
Constraints or Assumptions
- the array is sorted in non-decreasing order
- duplicates may exist, but any matching index is acceptable
- return
-1when the target is absent
Brute-Force Approach
Scan the array from left to right and stop when you find the target.
Better Approach
Use iterative binary search, and include the recursive version as a secondary implementation of the same invariant.
Why the Better Approach Works
Because the array is sorted, one comparison with the middle element eliminates half the remaining search range.
Pragmatic Java Choice
Prefer the iterative version in Java for day-to-day use because it is explicit and avoids call stack overhead.
Java Solution
class ExactBinarySearchExample {
static int linearSearch(int[] values, int target) {
for (int index = 0; index < values.length; index++) {
if (values[index] == target) {
return index;
}
}
return -1;
}
static int binarySearchIterative(int[] values, int target) {
int left = 0;
int right = values.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (values[mid] == target) {
return mid;
}
if (values[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
static int binarySearchRecursive(int[] values, int target) {
return binarySearchRecursive(values, target, 0, values.length - 1);
}
private static int binarySearchRecursive(int[] values, int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (values[mid] == target) {
return mid;
}
if (values[mid] < target) {
return binarySearchRecursive(values, target, mid + 1, right);
}
return binarySearchRecursive(values, target, left, mid - 1);
}
}
Dry Run
Use values = [2, 4, 7, 9, 11, 15] and target = 9.
Iterative search:
left = 0,right = 5,mid = 2, value7is too small- move
leftto3 mid = 4, value11is too large- move
rightto3 mid = 3, value9matches
Time and Space Complexity
- Brute force:
O(n)time,O(1)extra space - Better approach:
O(log n)time, iterativeO(1)extra space, recursiveO(log n)call stack space
Edge Cases
- empty array returns
-1 - target smaller than the first element returns
-1 - target larger than the last element returns
-1
Common Mistakes
- updating
left = midorright = midinstead of moving pastmid - forgetting the array must already be sorted
- mixing iterative and recursive boundary conventions
Worked Example 2: Search Insert Position with Lower Bound
Problem Statement
Given a sorted array and a target, return the first index where the target can be inserted while preserving sorted order.
Why This Example Matters
It turns binary search from exact lookup into boundary finding, which is the more reusable form in interviews.
Constraints or Assumptions
- the array is sorted in non-decreasing order
- if the target already exists, return its first valid insertion position
- if the target is greater than all elements, return
values.length
Brute-Force Approach
Scan from left to right until you find the first element greater than or equal to the target.
Better Approach
Use a lower-bound binary search on a half-open interval.
Why the Better Approach Works
The predicate values[index] >= target is monotonic across a sorted array. Once it becomes true, it stays true.
Pragmatic Java Choice
Use a reusable lowerBound helper because it generalizes cleanly to duplicate counting and interval queries.
Java Solution
class LowerBoundExample {
static int searchInsertLinear(int[] values, int target) {
for (int index = 0; index < values.length; index++) {
if (values[index] >= target) {
return index;
}
}
return values.length;
}
static int lowerBound(int[] values, int target) {
int left = 0;
int right = values.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (values[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
static int upperBound(int[] values, int target) {
int left = 0;
int right = values.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (values[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
Dry Run
Use values = [1, 3, 3, 5, 8] and target = 3.
Lower bound:
left = 0,right = 5,mid = 2, value3is large enough, moverightto2mid = 1, value3is large enough, moverightto1mid = 0, value1is too small, moveleftto1left == right == 1, answer is1
Upper bound for 3 would return 3, so the count of 3 is 3 - 1 = 2.
Time and Space Complexity
- Brute force:
O(n)time,O(1)extra space - Better approach:
O(log n)time,O(1)extra space
Edge Cases
- empty array returns
0 - target smaller than all elements returns
0 - target larger than all elements returns
values.length
Common Mistakes
- using the exact-match template instead of a boundary template
- mixing up lower bound with upper bound
- forgetting that returning
values.lengthcan be correct
Worked Example 3: Floor Square Root with Binary Search on Answer
Problem Statement
Given a non-negative integer target, return the largest integer x such that x * x <= target.
Why This Example Matters
It is the cleanest beginner example of binary search on answer. The answer is not in an array, but the feasibility test is monotonic.
Constraints or Assumptions
targetis non-negative- return the floor of the square root
- avoid multiplication overflow where possible
Brute-Force Approach
Try every integer from 0 upward until the square exceeds target.
Better Approach
Binary-search the answer range from 0 to target and test whether mid is feasible.
Why the Better Approach Works
The predicate mid * mid <= target is monotonic. If a candidate mid works, every smaller candidate works too. If it fails, every larger candidate fails too.
Pragmatic Java Choice
Use division-based comparison mid <= target / mid to avoid integer overflow.
Java Solution
class IntegerSquareRootExample {
static int sqrtLinear(int target) {
int answer = 0;
while ((long) (answer + 1) * (answer + 1) <= target) {
answer++;
}
return answer;
}
static int sqrtBinarySearch(int target) {
if (target < 2) {
return target;
}
int left = 1;
int right = target;
int answer = 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= target / mid) {
answer = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return answer;
}
}
Dry Run
Use target = 20.
Binary search:
left = 1,right = 20,mid = 10,10 <= 20 / 10is false- move
rightto9 mid = 5,5 <= 20 / 5is false- move
rightto4 mid = 2,2 <= 20 / 2is true, record2, moveleftto3mid = 3,3 <= 20 / 3is true, record3, moveleftto4mid = 4,4 <= 20 / 4is true, record4, moveleftto5- stop, answer is
4
Time and Space Complexity
- Brute force:
O(sqrt(target))time,O(1)extra space - Better approach:
O(log target)time,O(1)extra space
Edge Cases
target = 0returns0target = 1returns1- large values require overflow-safe checks
Common Mistakes
- using
mid * midwithintand overflowing - searching the wrong answer range
- not storing the best feasible answer before moving rightward
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- exact-match binary search reduces sorted-array lookup from
O(n)toO(log n) - lower and upper bound keep the same
O(log n)runtime while handling duplicates and insertion positions cleanly - binary search on answer turns many trial-and-error problems from linear scanning into logarithmic search over a numeric range
- recursive forms can be elegant but use call stack space, while iterative forms are usually simpler to ship in Java
Choose binary search when:
- the data is sorted or the answer space is ordered
- one comparison or feasibility test eliminates half the remaining candidates
- the predicate is monotonic
Choose lower or upper bound when:
- duplicates matter
- you need first occurrence, insertion position, or range counts
- exact-match search feels too rigid for the question
Choose binary search on answer when:
- the problem asks for minimum feasible or maximum valid
- you can write a yes or no predicate for a candidate answer
- feasibility changes only once across the answer range
Signals not to force binary search:
- the data is unsorted and cannot be ordered cheaply enough
- the predicate is not monotonic
- the range is tiny and a direct scan is simpler
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- infinite loops from not moving beyond
mid - off-by-one errors from mixing closed and half-open intervals
- incorrect lower-bound or upper-bound comparison operators
- binary-searching a space that is not monotonic
Boundary and arithmetic risks:
- empty arrays
- single-element arrays
- targets outside the array range
- overflow in arithmetic comparisons for answer-space problems
Short debugging checklist:
- What exact invariant am I maintaining about the search range?
- Is the interval closed
[left, right]or half-open[left, right)? - When I reject
mid, do I move past it correctly? - For answer search, is my predicate truly monotonic?
- If the answer does not exist as an exact value, what boundary should I return?
6. Practice Problems
Easy
- Title: Binary Search
- One-line prompt: Return the index of a target in a sorted array.
- Expected pattern or core idea: Exact iterative binary search.
- Title: Search Insert Position
- One-line prompt: Return the first position where a target fits in sorted order.
- Expected pattern or core idea: Lower bound.
- Title: Sqrt(x)
- One-line prompt: Return the floor square root of a non-negative integer.
- Expected pattern or core idea: Binary search on answer.
Medium
- Title: Find First and Last Position of Element in Sorted Array
- One-line prompt: Return the inclusive range of a target value.
- Expected pattern or core idea: Lower bound and upper bound.
- Title: Peak Index in a Mountain Array
- One-line prompt: Find the peak in a unimodal array.
- Expected pattern or core idea: Binary search on ordered slope information.
- Title: Koko Eating Bananas
- One-line prompt: Find the minimum eating speed to finish within a time limit.
- Expected pattern or core idea: Binary search on answer with feasibility predicate.
Hard
- Title: Median of Two Sorted Arrays
- One-line prompt: Compute the median without fully merging two sorted arrays.
- Expected pattern or core idea: Partition-based binary search.
- Title: Split Array Largest Sum
- One-line prompt: Minimize the largest subarray sum under a partition limit.
- Expected pattern or core idea: Binary search on answer.
- Title: Search in Rotated Sorted Array II
- One-line prompt: Search a rotated sorted array with duplicates.
- Expected pattern or core idea: Binary search with ambiguous boundaries.
7. Short Recap
The core idea of this chapter is that binary search is not about memorizing one loop. It is about maintaining a correct ordered search range and shrinking it safely.
The most important optimization insight is that once you can express the problem as a monotonic boundary or feasibility predicate, many linear scans become logarithmic.
The most important implementation warning is to define the invariant and interval style before you write comparisons.
This chapter prepares the next chapter by strengthening divide-and-conquer reasoning before sorting algorithms compare multiple ways to reduce disorder efficiently.
8. Coverage Check
- 12.1 Iterative binary search
- 12.2 Recursive binary search
- 12.3 Lower bound and upper bound
- 12.4 Binary search on answer
- 12.5 Templates, invariants, and edge cases
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 13: Sorting Algorithms
13: Sorting Algorithms
Goal: Teach learners how major sorting algorithms work, what trade-offs they make, and how to choose a sorting strategy based on data shape, stability needs, memory limits, and constraints.
Outcome: By the end of this chapter, you can explain and implement elementary quadratic sorts, merge sort, quick sort, heap sort, and counting-style sorts in Java, and you can justify when one sorting approach is more appropriate than another.
1. Intuition First
Sorting matters because many harder problems become easier after order is imposed. Searching, duplicate handling, interval merging, greedy scheduling, and many graph or tree preprocessing tasks often become simpler once data is sorted.
A simple real-world analogy is organizing books on a shelf. You can sort by repeatedly swapping neighbors, by selecting the next correct book, by splitting books into smaller piles and merging them, or by placing them into bins by label range. Different methods reach the same final order with different costs.
The core mental model is this: a sorting algorithm spends work resolving disorder. The right algorithm depends on how much disorder there is, whether extra memory is allowed, whether equal elements must keep their original order, and whether the key range is small.
The most common beginner confusion point is assuming there is one universally best sort. There is not. Some are stable, some are in-place, some are fast on average, and some depend on value range rather than pairwise comparison.
In the roadmap, this chapter turns comparison-based reasoning from binary search into broader algorithm trade-offs. It also prepares later chapters where sorted order becomes an assumption rather than the main topic.
2. Core Concepts and Techniques
Concept Cluster: Bubble Sort, Selection Sort, and Insertion Sort
Key concepts in this block:
- 13.1 Bubble sort, selection sort, and insertion sort
Intuition
These algorithms are the first clear models of how local operations gradually create global order.
Why It Matters
They are not usually the best choice for large arrays, but they teach invariants, swapping, shifting, and how sorted prefixes or suffixes grow.
How It Works
- bubble sort repeatedly swaps adjacent out-of-order pairs so large values drift right
- selection sort repeatedly selects the smallest remaining value and places it next
- insertion sort grows a sorted prefix by inserting each new value into its correct position
Java Implementation Notes
- Insertion sort is often the best of the three for small arrays or nearly sorted data.
- Selection sort minimizes writes, which can matter in special cases.
- Bubble sort is mainly educational unless a problem explicitly asks for it.
Common Mistakes
- forgetting the inner-loop bounds
- swapping too eagerly in insertion sort instead of shifting efficiently
- assuming bubble sort is stable only if swaps occur on equal values
- ignoring the early-exit optimization in bubble sort
Quick Example
class InsertionSortQuickExample {
static void insertionSort(int[] values) {
for (int index = 1; index < values.length; index++) {
int current = values[index];
int position = index - 1;
while (position >= 0 && values[position] > current) {
values[position + 1] = values[position];
position--;
}
values[position + 1] = current;
}
}
}
Debugging Tip
After each outer-loop step, verify what portion of the array is guaranteed to be sorted.
Advanced Note
Many production sorting implementations switch to insertion sort for tiny partitions because its constant factors are low.
Concept Cluster: Merge Sort and Quick Sort
Key concepts in this block:
- 13.2 Merge sort
- 13.3 Quick sort
Intuition
Both algorithms use divide and conquer, but they make opposite trade-offs. Merge sort is predictable and stable but uses extra memory. Quick sort is usually faster in practice and in-place, but its worst case is poor without careful pivot strategy.
Why It Matters
These two algorithms dominate interview discussions of general-purpose comparison sorting.
How It Works
Merge sort:
- split the array into halves
- sort each half recursively
- merge the two sorted halves
Quick sort:
- choose a pivot
- partition smaller values left and larger values right
- recurse on the partitions
Java Implementation Notes
- Merge sort is stable and easier to reason about.
- Quick sort needs careful partitioning and a decent pivot choice.
- Randomized pivoting helps avoid consistently bad partitions.
Common Mistakes
- forgetting to copy leftovers during merge
- partition loops that skip or double-count elements
- using quick sort without understanding what the pivot position guarantees
- assuming quick sort is stable
Quick Example
class MergeSortQuickExample {
static void mergeSort(int[] values) {
int[] buffer = new int[values.length];
mergeSort(values, 0, values.length - 1, buffer);
}
private static void mergeSort(int[] values, int left, int right, int[] buffer) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
mergeSort(values, left, mid, buffer);
mergeSort(values, mid + 1, right, buffer);
merge(values, left, mid, right, buffer);
}
private static void merge(int[] values, int left, int mid, int right, int[] buffer) {
int first = left;
int second = mid + 1;
int index = left;
while (first <= mid && second <= right) {
if (values[first] <= values[second]) {
buffer[index++] = values[first++];
} else {
buffer[index++] = values[second++];
}
}
while (first <= mid) {
buffer[index++] = values[first++];
}
while (second <= right) {
buffer[index++] = values[second++];
}
for (int position = left; position <= right; position++) {
values[position] = buffer[position];
}
}
}
Debugging Tip
For merge sort, print the two halves before merging. For quick sort, print the pivot and final partition boundary after each partition step.
Advanced Note
The difference between a stable and unstable sort matters whenever equal keys carry attached meaning, such as timestamps or IDs.
Concept Cluster: Heap Sort, Counting Sort, Radix Sort, and Choosing the Right Sort
Key concepts in this block:
- 13.4 Heap sort
- 13.5 Counting sort and radix sort
- 13.6 When to use which sorting algorithm
Intuition
Heap sort repeatedly extracts the next extreme value from a heap. Counting and radix sort avoid pairwise comparisons when keys have helpful structure.
Why It Matters
This is where sorting becomes a constraint-driven choice rather than a single technique.
How It Works
Heap sort:
- build a max heap
- swap the root with the last unsorted position
- restore the heap property and repeat
Counting sort:
- count how many times each value appears
- rebuild the array from counts
Radix sort:
- sort by one digit or character position at a time
- usually relies on a stable inner sort such as counting sort
Choosing rules:
- stable general-purpose sort with extra memory: merge sort
- fast average in-place comparison sort: quick sort
- guaranteed
O(n log n)in-place comparison sort: heap sort - bounded integer key range: counting sort
- fixed-width digit-based keys: radix sort
Java Implementation Notes
- Heap sort is valuable when you need worst-case guarantees without extra array-sized memory.
- Counting sort only makes sense when the value range is not too large.
- Radix sort is excellent for fixed-format numeric keys but requires careful stable passes.
Common Mistakes
- assuming counting sort works efficiently for arbitrary large ranges
- forgetting that radix sort depends on stable intermediate passes
- mismanaging heap size during heap sort extraction
Quick Example
class CountingSortQuickExample {
static int[] countingSortNonNegative(int[] values, int maximum) {
int[] counts = new int[maximum + 1];
for (int value : values) {
counts[value]++;
}
int[] result = new int[values.length];
int index = 0;
for (int value = 0; value <= maximum; value++) {
for (int count = 0; count < counts[value]; count++) {
result[index++] = value;
}
}
return result;
}
}
Debugging Tip
Before choosing a sort, state the constraints in one line: stable or not, extra memory allowed or not, value range small or not, nearly sorted or not.
Advanced Note
Sorting choice is often about constants, memory, and data distribution, not just asymptotic runtime.
3. Worked Examples and Full Solutions
Worked Example 1: General Array Sorting with Merge Sort
Problem Statement
Given an integer array, sort it in ascending order.
Why This Example Matters
It introduces the first efficient general-purpose sorting upgrade over the quadratic beginner algorithms.
Constraints or Assumptions
- the array may contain duplicates and negative values
- stable behavior is desirable
- extra array-sized memory is acceptable
Brute-Force Approach
Use bubble sort and repeatedly swap adjacent out-of-order pairs until the array is sorted.
Better Approach
Use merge sort.
Why the Better Approach Works
Merge sort splits the problem into two smaller sorting problems, then combines already sorted halves in linear time per merge level.
Pragmatic Java Choice
Use one reusable buffer array to avoid allocating a new temporary array at every merge call.
Java Solution
class MergeSortExample {
static void bubbleSort(int[] values) {
for (int end = values.length - 1; end > 0; end--) {
boolean swapped = false;
for (int index = 0; index < end; index++) {
if (values[index] > values[index + 1]) {
int temp = values[index];
values[index] = values[index + 1];
values[index + 1] = temp;
swapped = true;
}
}
if (!swapped) {
return;
}
}
}
static void mergeSort(int[] values) {
int[] buffer = new int[values.length];
mergeSort(values, 0, values.length - 1, buffer);
}
private static void mergeSort(int[] values, int left, int right, int[] buffer) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
mergeSort(values, left, mid, buffer);
mergeSort(values, mid + 1, right, buffer);
merge(values, left, mid, right, buffer);
}
private static void merge(int[] values, int left, int mid, int right, int[] buffer) {
int first = left;
int second = mid + 1;
int write = left;
while (first <= mid && second <= right) {
if (values[first] <= values[second]) {
buffer[write++] = values[first++];
} else {
buffer[write++] = values[second++];
}
}
while (first <= mid) {
buffer[write++] = values[first++];
}
while (second <= right) {
buffer[write++] = values[second++];
}
for (int index = left; index <= right; index++) {
values[index] = buffer[index];
}
}
}
Dry Run
Use values = [5, 2, 4, 1].
Merge sort:
- split into
[5, 2]and[4, 1] - split again into single elements
- merge
[5]and[2]into[2, 5] - merge
[4]and[1]into[1, 4] - merge
[2, 5]and[1, 4]into[1, 2, 4, 5]
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach:
O(n log n)time,O(n)extra space
Edge Cases
- empty array remains empty
- single-element array is already sorted
- duplicates keep their original relative order under merge sort
Common Mistakes
- forgetting to copy remaining elements after one half finishes
- allocating too many temporary arrays unnecessarily
- assuming merge sort is in-place
Worked Example 2: In-Place Sorting with Quick Sort
Problem Statement
Given an integer array, sort it in ascending order using an in-place strategy.
Why This Example Matters
It highlights the trade-off between memory efficiency and worst-case predictability.
Constraints or Assumptions
- average-case performance matters
- extra array-sized memory is undesirable
- the input can contain duplicates
Brute-Force Approach
Use selection sort and repeatedly choose the smallest remaining value for the next position.
Better Approach
Use quick sort with a randomized pivot.
Why the Better Approach Works
Partitioning places the pivot into its final sorted position and ensures all smaller values are on one side and all larger values are on the other. The same logic then applies recursively to both sides.
Pragmatic Java Choice
Randomize the pivot selection to reduce the chance of worst-case partitions on already patterned input.
Java Solution
import java.util.concurrent.ThreadLocalRandom;
class QuickSortExample {
static void selectionSort(int[] values) {
for (int start = 0; start < values.length; start++) {
int minimumIndex = start;
for (int index = start + 1; index < values.length; index++) {
if (values[index] < values[minimumIndex]) {
minimumIndex = index;
}
}
int temp = values[start];
values[start] = values[minimumIndex];
values[minimumIndex] = temp;
}
}
static void quickSort(int[] values) {
quickSort(values, 0, values.length - 1);
}
private static void quickSort(int[] values, int left, int right) {
if (left >= right) {
return;
}
int pivotIndex = ThreadLocalRandom.current().nextInt(left, right + 1);
swap(values, pivotIndex, right);
int partitionIndex = partition(values, left, right);
quickSort(values, left, partitionIndex - 1);
quickSort(values, partitionIndex + 1, right);
}
private static int partition(int[] values, int left, int right) {
int pivot = values[right];
int smallerEnd = left;
for (int index = left; index < right; index++) {
if (values[index] <= pivot) {
swap(values, smallerEnd, index);
smallerEnd++;
}
}
swap(values, smallerEnd, right);
return smallerEnd;
}
private static void swap(int[] values, int first, int second) {
int temp = values[first];
values[first] = values[second];
values[second] = temp;
}
}
Dry Run
Use values = [7, 3, 5, 2] and assume pivot 5.
- move pivot to the end if needed
- scan the array and keep a boundary for values
<= 5 - after partition, array becomes
[3, 2, 5, 7] - pivot
5is fixed in its final position - recursively sort
[3, 2]and[7] - final answer is
[2, 3, 5, 7]
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach: average
O(n log n)time, worst-caseO(n^2)time, averageO(log n)call stack space
Edge Cases
- already sorted input can be bad for poor pivot choices
- all equal values still need correct partition behavior
- empty and single-element arrays should return immediately
Common Mistakes
- misunderstanding what the partition index guarantees
- forgetting to exclude the pivot's final position from recursive calls
- not randomizing or otherwise choosing pivots carefully
Worked Example 3: Sorting Bounded Integers with Counting Sort
Problem Statement
Given an array of non-negative integers where every value lies between 0 and maximum, sort the array.
Why This Example Matters
It shows that sometimes you should stop comparing elements entirely and exploit the key range directly.
Constraints or Assumptions
- all values are non-negative
maximumis not extremely large relative ton- stability is not required for this basic version
Brute-Force Approach
Use a comparison sort such as merge sort.
Better Approach
Use counting sort.
Why the Better Approach Works
If the key range is small, counting each value is cheaper than repeatedly comparing values to each other.
Pragmatic Java Choice
Use counting sort only when the range size is manageable. If the range is too large, the memory cost becomes the new bottleneck.
Java Solution
class CountingSortExample {
static void mergeSort(int[] values) {
int[] buffer = new int[values.length];
mergeSort(values, 0, values.length - 1, buffer);
}
private static void mergeSort(int[] values, int left, int right, int[] buffer) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
mergeSort(values, left, mid, buffer);
mergeSort(values, mid + 1, right, buffer);
merge(values, left, mid, right, buffer);
}
private static void merge(int[] values, int left, int mid, int right, int[] buffer) {
int first = left;
int second = mid + 1;
int write = left;
while (first <= mid && second <= right) {
if (values[first] <= values[second]) {
buffer[write++] = values[first++];
} else {
buffer[write++] = values[second++];
}
}
while (first <= mid) {
buffer[write++] = values[first++];
}
while (second <= right) {
buffer[write++] = values[second++];
}
for (int index = left; index <= right; index++) {
values[index] = buffer[index];
}
}
static int[] countingSort(int[] values, int maximum) {
int[] counts = new int[maximum + 1];
for (int value : values) {
counts[value]++;
}
int[] result = new int[values.length];
int write = 0;
for (int value = 0; value <= maximum; value++) {
while (counts[value] > 0) {
result[write++] = value;
counts[value]--;
}
}
return result;
}
}
Dry Run
Use values = [4, 2, 2, 1, 3] and maximum = 4.
Counting sort:
- counts become
[0, 1, 2, 1, 1] - rebuild output by writing one
1, two2s, one3, and one4 - result is
[1, 2, 2, 3, 4]
Radix sort extends this idea by applying stable counting-style passes one digit at a time.
Time and Space Complexity
- Brute force:
O(n log n)time,O(n)extra space for merge sort - Better approach:
O(n + k)time andO(k)extra space, wherek = maximum + 1
Edge Cases
- empty array returns empty output
- many repeated values are handled efficiently
- a very large
maximumcan make counting sort impractical
Common Mistakes
- using counting sort when the key range is far larger than the array length
- forgetting that this simple version only handles non-negative bounded integers
- assuming radix sort works without stable per-digit sorting
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- bubble, selection, and insertion sorts are
O(n^2)and mainly useful for learning or very small inputs - merge sort gives
O(n log n)time with stability but needsO(n)extra memory - quick sort is often fastest in practice on average and sorts in place, but its worst case is
O(n^2) - heap sort guarantees
O(n log n)and uses onlyO(1)extra array space, but it is not stable and often has larger constants - counting sort and radix sort can beat comparison sorts when the keys have a constrained structure
Choose insertion sort when:
- the array is small or nearly sorted
- simplicity matters
- stability is useful
Choose merge sort when:
- stable ordering matters
- predictable
O(n log n)time matters - extra memory is acceptable
Choose quick sort when:
- you want fast average performance and in-place partitioning
- randomized or good pivot selection is available
Choose heap sort when:
- worst-case
O(n log n)is required without array-sized extra memory
Choose counting or radix sort when:
- the key domain is constrained enough to exploit
- comparison sorting is leaving performance on the table
Signals not to force a specific sort:
- using counting sort on huge sparse ranges
- using quick sort when stability is required
- using merge sort when memory is too constrained
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- incorrect loop bounds in quadratic sorts
- broken merge leftover copying
- faulty partition logic in quick sort
- heapify index mistakes in heap sort
- range misuse in counting sort
Boundary and data-shape risks:
- empty arrays
- single-element arrays
- already sorted or reverse-sorted input
- many duplicates
- negative values in counting-sort problems unless explicitly handled
Short debugging checklist:
- After each outer loop, what subrange is guaranteed to be sorted?
- If I am merging, did I copy all leftover elements?
- If I am partitioning, what does the pivot boundary mean exactly?
- Does the chosen sort match the data constraints and stability needs?
- Am I paying memory for a benefit I actually need?
6. Practice Problems
Easy
- Title: Sort Colors
- One-line prompt: Rearrange an array containing only
0,1, and2. - Expected pattern or core idea: Counting insight or three-way partitioning.
- One-line prompt: Rearrange an array containing only
- Title: Relative Sort Array
- One-line prompt: Sort one array according to the order defined by another.
- Expected pattern or core idea: Counting or custom ordering.
- Title: Merge Sorted Array
- One-line prompt: Merge two sorted arrays into one sorted result.
- Expected pattern or core idea: Merge procedure.
Medium
- Title: Sort an Array
- One-line prompt: Implement a full sorting algorithm rather than calling the library.
- Expected pattern or core idea: Merge sort or quick sort.
- Title: K Closest Points to Origin
- One-line prompt: Return the
kclosest points. - Expected pattern or core idea: Heap or quickselect-style partition reasoning.
- One-line prompt: Return the
- Title: Largest Number
- One-line prompt: Arrange numbers so their concatenation is maximal.
- Expected pattern or core idea: Comparator design after understanding sorting behavior.
Hard
- Title: Reverse Pairs
- One-line prompt: Count pairs where one value is more than twice another later value.
- Expected pattern or core idea: Merge-sort-based counting.
- Title: Count of Smaller Numbers After Self
- One-line prompt: For each index, count how many smaller values appear later.
- Expected pattern or core idea: Merge-sort counting or Fenwick tree later.
- Title: Maximum Gap
- One-line prompt: Find the maximum difference between adjacent sorted values.
- Expected pattern or core idea: Bucket or radix-style thinking beyond comparison sort.
7. Short Recap
The core idea of this chapter is that sorting is a family of trade-offs, not a single algorithm.
The most important optimization insight is that O(n log n) comparison sorting is the default upgrade, but bounded-key problems can do even better with counting-style methods.
The most important implementation warning is to choose a sort that matches the actual constraints instead of copying one algorithm everywhere.
This chapter prepares the next chapter by making ordered, bit-level, and structural thinking more natural before bit manipulation starts optimizing representation itself.
8. Coverage Check
- 13.1 Bubble sort, selection sort, and insertion sort
- 13.2 Merge sort
- 13.3 Quick sort
- 13.4 Heap sort
- 13.5 Counting sort and radix sort
- 13.6 When to use which sorting algorithm
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 14: Bit Manipulation
14: Bit Manipulation
Goal: Teach learners how binary representation controls low-level operations, how to use bitwise operators safely in Java, and how to recognize when bitmasks simplify state or improve performance.
Outcome: By the end of this chapter, you can read and write basic bit operations, set and clear specific bits, count set bits efficiently, use XOR for common interview tricks, and represent subsets or compact state with bitmasks.
1. Intuition First
Bit manipulation matters because every integer in Java is already stored in binary. Bitwise operations let you work directly with that representation instead of paying for higher-level bookkeeping when the problem only needs on or off state.
A simple real-world analogy is a row of light switches. Each switch is either off or on. A bitmask is just a compact panel of switches where one integer stores many yes or no decisions.
The core mental model is this: a bit position encodes a power of two, and bitwise operators transform those positions directly. Once you can see a number as a set of bits instead of as a decimal value, many operations become mechanical.
The most common beginner confusion point is mixing arithmetic with bitwise reasoning. +, -, and * operate on full numeric values. &, |, ^, ~, <<, and >> operate on individual bits.
In the roadmap, this chapter sits after sorting because it shifts attention from ordering whole values to representing information more compactly. It also prepares later DP state compression, subset work, and advanced string or graph optimizations.
2. Core Concepts and Techniques
Concept Cluster: Bitwise Operators, Single-Bit Updates, and Counting Bits
Key concepts in this block:
- 14.1 Bitwise operators
- 14.2 Set, clear, and toggle bit operations
- 14.3 Counting bits
Intuition
The basic operators let you inspect, combine, or change binary flags one position at a time.
Why It Matters
Many interview tasks boil down to testing membership, flipping a flag, or counting how many features are active.
How It Works
&keeps a bit on only if both sides have it on|turns a bit on if either side has it on^turns a bit on if exactly one side has it on<<shifts bits left, usually multiplying by a power of two>>shifts bits right, usually dividing by a power of two for non-negative values
Single-bit operations:
- set bit
k:value | (1 << k) - clear bit
k:value & ~(1 << k) - toggle bit
k:value ^ (1 << k) - test bit
k:(value & (1 << k)) != 0
Counting bits:
- inspect all bit positions one by one
- or remove the lowest set bit repeatedly with
value &= value - 1
Java Implementation Notes
- Remember that Java
intuses 32 bits andlonguses 64 bits. - Parentheses matter because bitwise operators have lower precedence than arithmetic shifts and comparisons in some expressions.
- For counting bits in production code,
Integer.bitCountexists, but manual logic is still important for interviews.
Common Mistakes
- using one-based bit positions when the code expects zero-based positions
- forgetting parentheses around
1 << k - misunderstanding right shift on negative numbers
- counting all 32 bits when a lower-set-bit loop would be simpler
Quick Example
class BitQuickExample {
static int toggleThirdBit(int value) {
return value ^ (1 << 2);
}
static int countBits(int value) {
int count = 0;
while (value != 0) {
value &= value - 1;
count++;
}
return count;
}
}
Debugging Tip
Write the binary form for a small example. Most bit bugs become obvious once you stop thinking only in decimal.
Advanced Note
Brian Kernighan's trick value &= value - 1 removes one set bit per iteration, so its runtime depends on how many bits are on, not on the word size.
Concept Cluster: XOR Tricks
Key concepts in this block:
- 14.4 XOR tricks
Intuition
XOR is useful because matching values cancel each other out.
Why It Matters
Several popular interview problems use XOR to remove paired values, swap parity-like state, or track uniqueness with constant extra space.
How It Works
a ^ a = 0a ^ 0 = a- XOR is commutative and associative
- if every value appears twice except one, XOR of all values leaves only the unique one
Java Implementation Notes
- XOR-based solutions are usually concise, but only when the problem's count pattern fits exactly.
- Use them when the mathematical rule is clean, not because bit tricks look clever.
Common Mistakes
- applying XOR when duplicates appear three times or follow a different count pattern
- forgetting that XOR solves parity-style uniqueness, not arbitrary frequency counting
Quick Example
class XorQuickExample {
static int singleNumber(int[] values) {
int answer = 0;
for (int value : values) {
answer ^= value;
}
return answer;
}
}
Debugging Tip
If you are tempted to use XOR, write down the appearance count of each value first. The cancellation rule must match that pattern exactly.
Advanced Note
XOR also helps compare prefix parity states, which later appears in some string and prefix problems.
Concept Cluster: Bitmasking, Subsets, and State-Encoding Patterns
Key concepts in this block:
- 14.5 Bitmasking basics
- 14.6 Subset and state-encoding patterns
Intuition
Bitmasking stores a whole set of yes or no decisions inside one integer.
Why It Matters
It is one of the most compact ways to represent subsets, visited choices, permissions, or small-state DP transitions.
How It Works
- bit
krepresents whether itemkis present - iterating from
0to(1 << n) - 1enumerates all subsets ofnitems - one integer can also encode small state combinations, such as which letters have appeared or which tasks are finished
Java Implementation Notes
- Use
intmasks up to 31 useful positions andlongif you need more. - Keep the meaning of each bit explicit in variable names or helper methods.
- Bitmasking is efficient only when the state dimension is small enough.
Common Mistakes
- forgetting that
1 << noverflows ifnis too large for the type - losing track of which bit maps to which item
- using bitmasking when a
HashSetwould be clearer and the state is not small
Quick Example
import java.util.ArrayList;
import java.util.List;
class BitmaskSubsetsQuickExample {
static List<List<Integer>> subsets(int[] values) {
List<List<Integer>> result = new ArrayList<>();
int totalMasks = 1 << values.length;
for (int mask = 0; mask < totalMasks; mask++) {
List<Integer> subset = new ArrayList<>();
for (int bit = 0; bit < values.length; bit++) {
if ((mask & (1 << bit)) != 0) {
subset.add(values[bit]);
}
}
result.add(subset);
}
return result;
}
}
Debugging Tip
When a mask represents a set, print both the decimal mask and the chosen elements while testing. This prevents silent bit-position confusion.
Advanced Note
Bitmask state encoding becomes especially powerful in advanced DP when the state space is small but the transition logic depends on many yes or no flags.
3. Worked Examples and Full Solutions
Worked Example 1: Single Number
Problem Statement
Given an array where every element appears exactly twice except for one element that appears once, return the unique element.
Why This Example Matters
It is the cleanest XOR interview problem and shows how bit reasoning can replace extra storage entirely.
Constraints or Assumptions
- exactly one value appears once
- every other value appears exactly twice
- order does not matter
Brute-Force Approach
Use a HashMap<Integer, Integer> to count frequencies and then find the value with count 1.
Better Approach
Use XOR across the whole array.
Why the Better Approach Works
Every paired value cancels itself because a ^ a = 0, leaving only the unpaired value.
Pragmatic Java Choice
Choose XOR here because the frequency pattern is exact and matches the cancellation rule perfectly.
Java Solution
import java.util.HashMap;
import java.util.Map;
class SingleNumberExample {
static int singleNumberWithMap(int[] values) {
Map<Integer, Integer> frequency = new HashMap<>();
for (int value : values) {
frequency.put(value, frequency.getOrDefault(value, 0) + 1);
}
for (int value : values) {
if (frequency.get(value) == 1) {
return value;
}
}
throw new IllegalArgumentException("Input does not satisfy the problem constraints");
}
static int singleNumberWithXor(int[] values) {
int answer = 0;
for (int value : values) {
answer ^= value;
}
return answer;
}
}
Dry Run
Use values = [4, 1, 2, 1, 2].
XOR flow:
- start
0 0 ^ 4 = 44 ^ 1 = 55 ^ 2 = 77 ^ 1 = 66 ^ 2 = 4
The paired 1 and 2 values cancel out, leaving 4.
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- one-element array returns that element
- negative numbers still work with XOR
- invalid frequency patterns break the XOR assumption
Common Mistakes
- using XOR when some elements appear more than twice
- not checking that the problem statement actually fits the trick
Worked Example 2: Count Set Bits in an Integer
Problem Statement
Given a non-negative integer, return how many bits in its binary representation are 1.
Why This Example Matters
It teaches both direct bit inspection and the lower-set-bit removal trick.
Constraints or Assumptions
- input is non-negative for simpler reasoning
- treat the value as a standard Java
int
Brute-Force Approach
Inspect each bit position from 0 to 31 and count how many tested bits are on.
Better Approach
Use Brian Kernighan's method and repeatedly remove the lowest set bit.
Why the Better Approach Works
value - 1 flips the lowest set bit and all lower bits. Applying value & (value - 1) removes exactly one set bit. Repeating that step counts only the set bits that actually exist.
Pragmatic Java Choice
Use the loop-based Kernighan version in interviews to show understanding, and use Integer.bitCount in production when appropriate.
Java Solution
class CountBitsExample {
static int countBitsByScanning(int value) {
int count = 0;
for (int bit = 0; bit < 32; bit++) {
if ((value & (1 << bit)) != 0) {
count++;
}
}
return count;
}
static int countBitsByRemovingLowestSetBit(int value) {
int count = 0;
while (value != 0) {
value &= value - 1;
count++;
}
return count;
}
}
Dry Run
Use value = 13, which is binary 1101.
Kernighan loop:
1101becomes1100, count11100becomes1000, count21000becomes0000, count3
The answer is 3.
Time and Space Complexity
- Brute force:
O(32)time,O(1)extra space - Better approach:
O(number of set bits)time,O(1)extra space
Edge Cases
0has zero set bits- powers of two have exactly one set bit
- negative numbers need extra care if the problem expects unsigned interpretation
Common Mistakes
- confusing bit positions with decimal digits
- forgetting that left shift on large bit positions can overflow the sign bit in
int - not clarifying whether the task treats input as signed or unsigned
Worked Example 3: Generate All Subsets with Bitmasking
Problem Statement
Given an array of distinct integers, return all possible subsets.
Why This Example Matters
It shows how one integer can encode a whole choice set and how subset enumeration maps directly to binary counting.
Constraints or Assumptions
- all values are distinct
- output order does not matter
- include the empty subset
Brute-Force Approach
Use recursive backtracking to decide include or skip at each position.
Better Approach
Use bitmask enumeration from 0 to (1 << n) - 1.
Why the Better Approach Works
Each binary mask is a unique on or off choice for every element. Every subset corresponds to exactly one mask.
Pragmatic Java Choice
Use bitmasking when n is small enough that 2^n subsets are acceptable and the state only needs membership, not complex recursion control.
Java Solution
import java.util.ArrayList;
import java.util.List;
class BitmaskSubsetsExample {
static List<List<Integer>> subsetsBacktracking(int[] values) {
List<List<Integer>> result = new ArrayList<>();
backtrack(values, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] values, int index, List<Integer> current, List<List<Integer>> result) {
if (index == values.length) {
result.add(new ArrayList<>(current));
return;
}
backtrack(values, index + 1, current, result);
current.add(values[index]);
backtrack(values, index + 1, current, result);
current.remove(current.size() - 1);
}
static List<List<Integer>> subsetsBitmask(int[] values) {
List<List<Integer>> result = new ArrayList<>();
int totalMasks = 1 << values.length;
for (int mask = 0; mask < totalMasks; mask++) {
List<Integer> subset = new ArrayList<>();
for (int bit = 0; bit < values.length; bit++) {
if ((mask & (1 << bit)) != 0) {
subset.add(values[bit]);
}
}
result.add(subset);
}
return result;
}
}
Dry Run
Use values = [10, 20, 30].
Masks:
000gives[]001gives[10]010gives[20]011gives[10, 20]- continue until
111gives[10, 20, 30]
Time and Space Complexity
- Brute force:
O(n * 2^n)time,O(n)recursion depth plus output space - Better approach:
O(n * 2^n)time,O(1)extra control space beyond the output and current subset construction
Edge Cases
- empty array returns
[[]] - large
nmakes subset enumeration infeasible regardless of implementation style - duplicate input values would produce repeated subsets semantically
Common Mistakes
- mixing bit positions with element values
- using
1 << nwhennis too large for the integer type - forcing bitmasking when recursion is clearer and the state is not compact
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- direct bit operations are usually
O(1)and extremely cheap - counting bits can be
O(word size)orO(number of set bits)depending on the method - XOR tricks often turn map-based frequency work into constant-space scans, but only under exact counting assumptions
- bitmasking is compact and fast for small-state problems, but it does not defeat exponential growth when the number of subsets itself is exponential
Choose bit manipulation when:
- the state is naturally yes or no
- the problem mentions powers of two, parity-like uniqueness, or subset membership
- compact representation simplifies the logic
Choose XOR when:
- the cancellation rule matches the frequency pattern exactly
Choose bitmasking when:
- the universe size is small enough to fit comfortably in a primitive type
- you need fast subset or visited-state checks
Signals not to force bit tricks:
- the code becomes less clear without a real performance benefit
- the state is not naturally binary
- the mask would require too many bits to be practical
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- wrong bit index
- missing parentheses around shifts
- misusing signed right shift on negative values
- forgetting that a bitmask still needs a clear mapping between bits and items
Boundary and representation risks:
- zero values
- negative numbers in shift problems
- masks that exceed
intcapacity - exponential subset growth for large
n
Short debugging checklist:
- What does each bit position mean?
- Am I treating positions as zero-based consistently?
- Does the XOR trick match the exact frequency rule?
- Would a set or map be clearer than a bitmask here?
- Is the bit width of the chosen type large enough?
6. Practice Problems
Easy
- Title: Single Number
- One-line prompt: Find the value that appears once while all others appear twice.
- Expected pattern or core idea: XOR cancellation.
- Title: Number of 1 Bits
- One-line prompt: Count how many set bits appear in an integer.
- Expected pattern or core idea: Bit scanning or lowest-set-bit removal.
- Title: Power of Two
- One-line prompt: Determine whether a number is a power of two.
- Expected pattern or core idea: Single-set-bit check.
Medium
- Title: Subsets
- One-line prompt: Return all subsets of a distinct integer array.
- Expected pattern or core idea: Bitmask enumeration or backtracking comparison.
- Title: Counting Bits
- One-line prompt: Return the number of set bits for every number from
0ton. - Expected pattern or core idea: DP over bit relations.
- One-line prompt: Return the number of set bits for every number from
- Title: Sum of Two Integers
- One-line prompt: Add two integers without using
+or-. - Expected pattern or core idea: Bitwise addition with carry.
- One-line prompt: Add two integers without using
Hard
- Title: Single Number III
- One-line prompt: Find two values that appear once while all others appear twice.
- Expected pattern or core idea: XOR partition by a distinguishing bit.
- Title: Maximum Product of Word Lengths
- One-line prompt: Find two words with no shared letters and maximum length product.
- Expected pattern or core idea: Bitmask state encoding.
- Title: Shortest Path Visiting All Nodes
- One-line prompt: Visit every node in a graph with minimum steps.
- Expected pattern or core idea: Bitmask state plus BFS.
7. Short Recap
The core idea of this chapter is that bitwise operations let you manipulate binary state directly instead of carrying extra structures for simple on or off information.
The most important optimization insight is that XOR and bitmasks can collapse some map-heavy or subset-heavy logic into compact constant-space state.
The most important implementation warning is to keep bit positions explicit and to use bit tricks only when the problem's structure genuinely matches them.
This chapter prepares the next chapter by making mathematical shortcuts and representation-aware thinking natural before the math toolkit formalizes common algorithmic number operations.
8. Coverage Check
- 14.1 Bitwise operators
- 14.2 Set, clear, and toggle bit operations
- 14.3 Counting bits
- 14.4 XOR tricks
- 14.5 Bitmasking basics
- 14.6 Subset and state-encoding patterns
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 15: Mathematics for DSA
15: Mathematics for DSA
Goal: Teach learners the mathematical tools that repeatedly appear in algorithms, including divisibility, fast exponentiation, modular arithmetic, and the logarithmic reasoning behind efficient runtime.
Outcome: By the end of this chapter, you can compute GCD and LCM efficiently, factor numbers using square-root reasoning, explain logarithms in algorithm analysis, apply fast exponentiation, work safely with modular arithmetic, and recognize common interview shortcuts built from these ideas.
1. Intuition First
Mathematics matters in DSA because many efficient algorithms are really number-pattern shortcuts. Instead of simulating every possibility, math lets you jump directly to structure: divisors come in pairs, repeated squaring beats repeated multiplication, and modulo arithmetic keeps large counts manageable.
A simple real-world analogy is folding paper. If you fold a paper once, then again, then again, the number of layers doubles quickly. That is the same kind of growth that logarithms and exponentiation describe in algorithms.
The core mental model is this: good algorithmic math is less about abstract theory and more about identifying reusable patterns in numbers, growth, and divisibility.
The most common beginner confusion point is treating math as separate from algorithm design. In practice, math often explains why an algorithm is fast, safe from overflow, or easier to prove correct.
In the roadmap, this chapter closes the foundational toolkit before trees begin. It gives you arithmetic shortcuts that reappear in hashing, graphs, dynamic programming, and combinatorial counting later.
2. Core Concepts and Techniques
Concept Cluster: GCD, LCM, Factorization, and Divisors
Key concepts in this block:
- 15.1 GCD and LCM
- 15.2 Factorization and divisors
Intuition
GCD captures the largest shared building block of two numbers. LCM captures the smallest shared multiple. Divisors and prime factors reveal number structure.
Why It Matters
These ideas appear in fraction reduction, cycle synchronization, array-step problems, number theory tasks, and interview shortcuts involving repeated patterns.
How It Works
- Euclid's algorithm computes GCD using repeated remainder reduction
lcm(a, b) = a / gcd(a, b) * bwhen overflow is controlled carefully- divisors come in pairs around the square root
- factorization often only needs checking candidates up to
sqrt(n)
Java Implementation Notes
- Use iterative Euclid's algorithm for clarity and speed.
- Divide before multiplying when computing LCM to reduce overflow risk.
- For divisor enumeration, check both
dandn / dwhenddividesn.
Common Mistakes
- scanning all numbers from
1tonwhensqrt(n)is enough - computing
a * b / gcd(a, b)and overflowing before the division happens - adding the square-root divisor twice when
d * d == n
Quick Example
class GcdQuickExample {
static int gcd(int first, int second) {
while (second != 0) {
int remainder = first % second;
first = second;
second = remainder;
}
return Math.abs(first);
}
}
Debugging Tip
If a divisor loop goes to n instead of sqrt(n), ask whether you are missing the paired-divisor insight.
Advanced Note
Prime factorization often converts repeated divisor logic into counting exponent patterns, which becomes useful in advanced counting problems.
Concept Cluster: Logarithms and Fast Exponentiation
Key concepts in this block:
- 15.3 Logarithms in algorithm analysis
- 15.4 Fast exponentiation
Intuition
Logarithms measure how many times you can repeatedly shrink or double a quantity. Fast exponentiation uses that same idea in reverse by squaring to skip many multiplications.
Why It Matters
Binary search, heap operations, balanced trees, and exponentiation by squaring all rely on logarithmic thinking.
How It Works
- if an algorithm halves the problem each step, it often runs in
O(log n)time - repeated squaring computes
base^exponentby using the binary representation of the exponent - when the exponent bit is
1, multiply the current answer by the current base - square the base and shift the exponent right each step
Java Implementation Notes
- Iterative fast exponentiation is usually easier to ship than recursive versions.
- Use modular multiplication inside the loop when the task asks for
base^exponent mod m. - Be explicit about integer overflow when powers grow quickly.
Common Mistakes
- confusing
O(log n)withO(n log n) - squaring the base but forgetting to advance the exponent
- multiplying before taking modulo when the problem expects modular arithmetic
Quick Example
class PowerQuickExample {
static long power(long base, long exponent) {
long answer = 1L;
while (exponent > 0) {
if ((exponent & 1L) == 1L) {
answer *= base;
}
base *= base;
exponent >>= 1;
}
return answer;
}
}
Debugging Tip
Write the exponent in binary for a small example. It makes the multiply or skip decisions obvious.
Advanced Note
Fast exponentiation is one of the clearest examples of how bit manipulation and mathematics reinforce each other.
Concept Cluster: Modular Arithmetic and Interview Math Shortcuts
Key concepts in this block:
- 15.5 Modular arithmetic basics
- 15.6 Math shortcuts for interview problems
Intuition
Modulo arithmetic keeps values within a fixed range while preserving many useful addition and multiplication properties.
Why It Matters
Large counting answers, cyclic patterns, rolling computations, and repeated operations often become manageable only under a modulus.
How It Works
(a + b) mod m = ((a mod m) + (b mod m)) mod m(a * b) mod m = ((a mod m) * (b mod m)) mod m- modulo is not the same as division or fraction arithmetic
- common shortcuts include parity reasoning, divisor pairing, remainder cycling, and reducing repeated work by identifying patterns
Java Implementation Notes
- Normalize negative remainders when needed with
(value % mod + mod) % mod. - Apply modulo during the computation, not only at the end, when numbers can grow very large.
- A common interview modulus is
1_000_000_007, but the reasoning matters more than the specific constant.
Common Mistakes
- delaying modulo until after overflow already happened
- assuming modular division works like normal integer division
- missing simple cycles in repeated-operation problems
Quick Example
class ModQuickExample {
static int addMod(int first, int second, int mod) {
return (int) (((long) first + second) % mod);
}
}
Debugging Tip
If a value is exploding in size, ask whether the problem only cares about the answer modulo some number.
Advanced Note
Modular inverses and deeper number theory come later if needed. At this stage, the important part is safe arithmetic and pattern recognition.
3. Worked Examples and Full Solutions
Worked Example 1: Greatest Common Divisor of Two Numbers
Problem Statement
Given two non-negative integers, return their greatest common divisor.
Why This Example Matters
It is the most important reusable number-theory operation in early DSA.
Constraints or Assumptions
- inputs are non-negative
gcd(0, x) = x- return
0when both inputs are0
Brute-Force Approach
Scan from min(a, b) downward and return the first number dividing both inputs.
Better Approach
Use Euclid's algorithm.
Why the Better Approach Works
gcd(a, b) is equal to gcd(b, a % b). The shared divisibility information is preserved while the numbers shrink quickly.
Pragmatic Java Choice
Use the iterative form because it is short, efficient, and avoids recursion overhead.
Java Solution
class GreatestCommonDivisorExample {
static int gcdBruteForce(int first, int second) {
first = Math.abs(first);
second = Math.abs(second);
int limit = Math.min(first, second);
for (int candidate = limit; candidate >= 1; candidate--) {
if (first % candidate == 0 && second % candidate == 0) {
return candidate;
}
}
return Math.max(first, second);
}
static int gcdEuclid(int first, int second) {
first = Math.abs(first);
second = Math.abs(second);
while (second != 0) {
int remainder = first % second;
first = second;
second = remainder;
}
return first;
}
}
Dry Run
Use first = 48 and second = 18.
Euclid's algorithm:
48 % 18 = 12, now solvegcd(18, 12)18 % 12 = 6, now solvegcd(12, 6)12 % 6 = 0, so the answer is6
Time and Space Complexity
- Brute force:
O(min(a, b))time,O(1)extra space - Better approach:
O(log(min(a, b)))time in practice,O(1)extra space
Edge Cases
gcd(0, x) = xgcd(0, 0) = 0- negative inputs should be normalized with absolute values
Common Mistakes
- forgetting the zero-input behavior
- scanning divisors downward when Euclid is available
- using recursive math without explaining the remainder invariant
Worked Example 2: Fast Modular Exponentiation
Problem Statement
Given base, exponent, and mod, compute (base^exponent) mod mod.
Why This Example Matters
It combines logarithmic reasoning, bit inspection, and modular arithmetic in one core algorithm.
Constraints or Assumptions
mod > 0exponent >= 0- use repeated squaring rather than repeated multiplication
Brute-Force Approach
Multiply base by itself exponent times and take modulo during the loop.
Better Approach
Use fast exponentiation by squaring.
Why the Better Approach Works
The exponent's binary form tells you which powers of two contribute to the final answer. Squaring advances through those powers efficiently.
Pragmatic Java Choice
Use long internally even when the inputs are int so intermediate modular products stay safer.
Java Solution
class ModularExponentiationExample {
static long powerBruteForce(long base, long exponent, long mod) {
long answer = 1 % mod;
base %= mod;
for (long count = 0; count < exponent; count++) {
answer = (answer * base) % mod;
}
return answer;
}
static long powerFast(long base, long exponent, long mod) {
long answer = 1 % mod;
base %= mod;
while (exponent > 0) {
if ((exponent & 1L) == 1L) {
answer = (answer * base) % mod;
}
base = (base * base) % mod;
exponent >>= 1;
}
return answer;
}
}
Dry Run
Use base = 3, exponent = 13, mod = 100.
Binary exponent 13 is 1101.
Fast exponentiation:
- start
answer = 1,base = 3 - low bit is
1,answer = 3 - square base to
9, exponent becomes6 - low bit is
0, skip multiply - square base to
81, exponent becomes3 - low bit is
1,answer = 3 * 81 mod 100 = 43 - square base to
61, exponent becomes1 - low bit is
1,answer = 43 * 61 mod 100 = 23
Final answer is 23.
Time and Space Complexity
- Brute force:
O(exponent)time,O(1)extra space - Better approach:
O(log exponent)time,O(1)extra space
Edge Cases
exponent = 0returns1 mod modbase = 0with positive exponent returns0mod = 1forces the answer to0
Common Mistakes
- forgetting to reduce
basemodulomodfirst - delaying modulo until after overflow risk
- not understanding why exponent bits control the multiply steps
Worked Example 3: Count the Divisors of a Number
Problem Statement
Given a positive integer n, return how many positive divisors it has.
Why This Example Matters
It demonstrates the square-root divisor-pair shortcut that appears constantly in interview math problems.
Constraints or Assumptions
n > 0- count positive divisors only
- a perfect square should not double-count its square root
Brute-Force Approach
Check every number from 1 to n and count how many divide n exactly.
Better Approach
Check only from 1 to sqrt(n) and count divisors in pairs.
Why the Better Approach Works
If d divides n, then n / d is also a divisor. One check finds up to two divisors at once.
Pragmatic Java Choice
Use candidate * candidate <= n with long arithmetic if needed for safety.
Java Solution
class DivisorCountingExample {
static int countDivisorsBruteForce(int n) {
int count = 0;
for (int candidate = 1; candidate <= n; candidate++) {
if (n % candidate == 0) {
count++;
}
}
return count;
}
static int countDivisorsSqrt(int n) {
int count = 0;
for (int candidate = 1; candidate * candidate <= n; candidate++) {
if (n % candidate == 0) {
count++;
if (candidate != n / candidate) {
count++;
}
}
}
return count;
}
}
Dry Run
Use n = 36.
Check candidates up to 6:
1gives pair1and362gives pair2and183gives pair3and124gives pair4and95does not divide6gives only one new divisor because6 * 6 = 36
Total divisors: 9.
Time and Space Complexity
- Brute force:
O(n)time,O(1)extra space - Better approach:
O(sqrt(n))time,O(1)extra space
Edge Cases
n = 1has one divisor- prime numbers have exactly two divisors
- perfect squares need special handling to avoid double count
Common Mistakes
- looping all the way to
n - double-counting the square root for perfect squares
- forgetting that divisor pairing is the reason the optimization works
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- Euclid's algorithm reduces divisor-style scanning to logarithmic repeated remainder reduction
- factor and divisor problems often drop from
O(n)toO(sqrt(n))by using paired divisors - fast exponentiation reduces repeated multiplication from linear time in the exponent to logarithmic time
- modular arithmetic keeps numbers bounded, but it must be applied throughout the computation, not only at the end
Choose GCD or LCM tools when:
- the problem involves repeated cycles, divisibility, or synchronization
Choose square-root factorization when:
- you need divisors or prime checks for a single number or modest input sizes
Choose fast exponentiation when:
- the exponent is large
- the problem asks for powers under a modulus
Recognition signals for mathematical shortcuts:
- repeated doubling, halving, or powers
- divisibility or remainder patterns
- pair symmetry around the square root
- very large answers where only modulo matters
Signals not to force advanced math:
- the constraints are tiny and a direct loop is clearer
- the problem is mostly data-structure management rather than arithmetic structure
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- overflow while computing LCM or powers
- double-counting paired divisors
- applying modulo too late
- confusing logarithmic growth with linear growth
Boundary and arithmetic risks:
- zero values in GCD and LCM problems
- negative inputs when only non-negative math was intended
mod = 1- perfect squares in divisor loops
Short debugging checklist:
- Can I replace a full scan with Euclid or square-root reasoning?
- Am I reducing values before multiplying when overflow is possible?
- Does this problem only care about the answer modulo
m? - Is a repeated multiplication actually a fast-exponentiation problem?
- Have I justified why the runtime is logarithmic or square-root rather than linear?
6. Practice Problems
Easy
- Title: Find Greatest Common Divisor of Array
- One-line prompt: Return the GCD of an integer array.
- Expected pattern or core idea: Repeated Euclid reduction.
- Title: Power of Three
- One-line prompt: Determine whether a number is a power of three.
- Expected pattern or core idea: Repeated division or factor reasoning.
- Title: Count Primes
- One-line prompt: Count primes less than
n. - Expected pattern or core idea: Basic math optimization and sieve awareness.
- One-line prompt: Count primes less than
Medium
- Title: Pow(x, n)
- One-line prompt: Compute
x^nefficiently. - Expected pattern or core idea: Fast exponentiation.
- One-line prompt: Compute
- Title: Product of Array Except Self
- One-line prompt: For each index, multiply all other values.
- Expected pattern or core idea: Multiplicative reasoning with prefix and suffix products.
- Title: Fraction Addition and Subtraction
- One-line prompt: Evaluate a string expression of rational numbers.
- Expected pattern or core idea: LCM and fraction reduction with GCD.
Hard
- Title: Super Pow
- One-line prompt: Compute a large exponent under modular arithmetic constraints.
- Expected pattern or core idea: Modular fast exponentiation.
- Title: Reaching Points
- One-line prompt: Determine whether one coordinate pair can reach another with repeated additions.
- Expected pattern or core idea: Reverse math reasoning using modulo.
- Title: Largest Component Size by Common Factor
- One-line prompt: Connect numbers sharing prime factors and find the largest component.
- Expected pattern or core idea: Factorization plus graph or DSU reasoning.
7. Short Recap
The core idea of this chapter is that many algorithm problems become simpler once you spot the arithmetic structure instead of simulating every step.
The most important optimization insight is that Euclid, square-root divisor pairing, and fast exponentiation remove large amounts of repeated work.
The most important implementation warning is to watch overflow and to apply modulo at the right time, not after the damage is already done.
This chapter prepares the next chapter by giving you arithmetic confidence before trees shift the challenge from number structure to hierarchical structure.
8. Coverage Check
- 15.1 GCD and LCM
- 15.2 Factorization and divisors
- 15.3 Logarithms in algorithm analysis
- 15.4 Fast exponentiation
- 15.5 Modular arithmetic basics
- 15.6 Math shortcuts for interview problems
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 16: Tree Fundamentals
16: Tree Fundamentals
Goal: Teach learners how tree structure differs from linear data structures, how to represent trees cleanly in Java, and how recursive reasoning naturally matches parent-child relationships.
Outcome: By the end of this chapter, you can explain core tree terminology, distinguish height from depth and degree, identify root, internal, and leaf nodes, represent trees in Java, and write basic recursive tree traversals and aggregations.
1. Intuition First
Trees matter because many real systems are hierarchical rather than linear. Filesystems, company org charts, HTML documents, and category menus all branch from parent to child instead of forming one straight sequence.
A simple real-world analogy is a family tree. One ancestor branches into children, then grandchildren, then deeper generations. Each person has one parent connection above and several child connections below.
The core mental model is this: a tree is a connected structure with no cycles, and each subtree is itself a smaller tree. That recursive shape is why recursion becomes the default mental tool here.
The most common beginner confusion point is mixing up height and depth. Depth measures how far a node is from the root. Height measures how far a node is from its deepest descendant.
In the roadmap, this chapter opens Part IV. It gives you the vocabulary and mental model needed before binary trees, BSTs, heaps, tries, and range-query trees start adding stronger rules.
2. Core Concepts and Techniques
Concept Cluster: Tree Terminology, Height, Depth, Degree, and Node Roles
Key concepts in this block:
- 16.1 Tree terminology
- 16.2 Height, depth, and degree
- 16.3 Root, internal, and leaf nodes
Intuition
Tree terminology exists so you can describe structure precisely before writing algorithms on top of it.
Why It Matters
If you cannot distinguish parent, child, ancestor, descendant, depth, or leaf, tree algorithms become much harder to explain and debug.
How It Works
- root: the topmost node with no parent
- parent and child: the direct connection between neighboring levels
- ancestor and descendant: any higher or lower node on the same path
- degree of a node: number of children
- leaf node: node with no children
- internal node: node with at least one child
- depth of a node: number of edges from the root to that node
- height of a node: number of edges on the longest downward path to a leaf
- height of the tree: height of the root
Java Implementation Notes
- In binary trees, each node usually stores
leftandrightreferences. - In general trees, use a list of children.
- Decide early whether height counts edges or nodes, and keep that definition consistent.
Common Mistakes
- using height and depth interchangeably
- calling the root a leaf when it is the only node without clarifying the convention
- forgetting that degree is about children, not depth
Quick Example
import java.util.ArrayList;
import java.util.List;
class GeneralTreeQuickExample {
static final class Node {
int value;
List<Node> children = new ArrayList<>();
Node(int value) {
this.value = value;
}
}
}
Debugging Tip
Draw a small tree and label root, leaf, depth, and height manually before coding. Many tree bugs are really vocabulary bugs.
Advanced Note
Later chapters add special constraints, such as binary branching or BST order, but the parent-child hierarchy from this chapter still stays underneath everything.
Concept Cluster: Tree Representation in Java and Recursion on Trees
Key concepts in this block:
- 16.4 Tree representation in Java
- 16.5 Recursion on trees
Intuition
A tree is easiest to process when each node directly points to its children. Recursion then becomes a natural way to solve the same task for every subtree.
Why It Matters
Representation determines whether algorithms feel simple or painful. Good tree code usually comes from choosing a node structure that matches the operations you need.
How It Works
- binary trees use a node with
leftandright - general trees often use
List<Node> children - some problems start from edges, so you first build adjacency or child lists
- recursive tree functions usually follow this pattern:
- handle the null or leaf case
- solve the problem for each child
- combine those child answers at the current node
Java Implementation Notes
- Use
nullcarefully to represent missing children in binary trees. - If the input is an edge list, convert it into node references or adjacency lists before running recursive logic.
- A recursive helper often returns a summary value such as count, height, or boolean validity for the current subtree.
Common Mistakes
- recursing into
nullwithout a base case - rebuilding child lookup repeatedly instead of representing the tree once
- forgetting whether the recursion should process children before or after combining results
Quick Example
class BinaryTreeQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
Debugging Tip
When a recursive tree method fails, ask three questions: what is the base case, what information comes from each child, and how are those child answers combined?
Advanced Note
Many advanced tree algorithms are still just specialized versions of subtree-return recursion with better summary information.
3. Worked Examples and Full Solutions
Worked Example 1: Count Nodes in a Binary Tree
Problem Statement
Given the root of a binary tree, return how many nodes it contains.
Why This Example Matters
It is the simplest non-trivial tree recursion. It shows how a whole-tree answer is built from left and right subtree answers.
Constraints or Assumptions
- the tree may be empty
- the tree is not necessarily balanced
- every node should be counted exactly once
Brute-Force Approach
Use an explicit queue and perform a level-order traversal, counting nodes one by one.
Better Approach
Use recursion and return 1 + leftCount + rightCount for each node.
Why the Better Approach Works
Every subtree is itself a smaller binary tree. If you know how many nodes are in the left and right subtrees, the current node contributes exactly one more.
Pragmatic Java Choice
Use recursion here because the combine rule is direct and easy to verify.
Java Solution
import java.util.ArrayDeque;
import java.util.Queue;
class CountNodesExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static int countWithQueue(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int count = 0;
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
count++;
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
return count;
}
static int countRecursively(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + countRecursively(root.left) + countRecursively(root.right);
}
}
Dry Run
Use a tree with root 10, left child 5, right child 20, and 20 having left child 15.
Recursive count:
- root
10needs count of left subtree and right subtree - left subtree rooted at
5returns1 - right subtree rooted at
20returns1 + 1 + 0 = 2 - root returns
1 + 1 + 2 = 4
Time and Space Complexity
- Brute force:
O(n)time,O(w)extra space for the queue wherewis max width - Better approach:
O(n)time,O(h)call stack space wherehis tree height
Edge Cases
- empty tree returns
0 - single-node tree returns
1 - skewed trees increase recursion depth
Common Mistakes
- forgetting the
nullbase case - returning only child counts without adding
1for the current node - confusing tree height with node count
Worked Example 2: Compute the Height of a Binary Tree
Problem Statement
Given the root of a binary tree, return its height measured in edges.
Why This Example Matters
It forces you to distinguish depth from height and introduces the max-combine pattern common in tree recursion.
Constraints or Assumptions
- an empty tree has height
-1 - a single-node tree has height
0 - height is measured in edges, not nodes
Brute-Force Approach
Use level-order traversal and count how many levels are processed.
Better Approach
Use recursion: the height of a node is 1 + max(leftHeight, rightHeight).
Why the Better Approach Works
The longest root-to-leaf path must go through either the left child or the right child. Recursion finds both subtree heights and keeps the larger one.
Pragmatic Java Choice
Choose a base case that matches the height definition exactly. Using -1 for null makes a leaf's height become 0 naturally.
Java Solution
import java.util.ArrayDeque;
import java.util.Queue;
class HeightExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static int heightByLevels(TreeNode root) {
if (root == null) {
return -1;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int height = -1;
while (!queue.isEmpty()) {
int levelSize = queue.size();
height++;
for (int count = 0; count < levelSize; count++) {
TreeNode current = queue.poll();
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
}
return height;
}
static int heightRecursively(TreeNode root) {
if (root == null) {
return -1;
}
return 1 + Math.max(heightRecursively(root.left), heightRecursively(root.right));
}
}
Dry Run
Use a tree where root 1 has left child 2, right child 3, and node 2 has left child 4.
Recursive height:
- node
4has height0 - node
2sees left height0and right height-1, so height1 - node
3is a leaf, so height0 - root sees
max(1, 0), so height2
Time and Space Complexity
- Brute force:
O(n)time,O(w)extra space - Better approach:
O(n)time,O(h)call stack space
Edge Cases
- empty tree height is
-1by this convention - single-node tree height is
0 - skewed tree height can be
n - 1
Common Mistakes
- mixing node-based and edge-based height definitions
- returning
0fornullwhen the chosen convention expects-1 - taking
mininstead ofmax
Worked Example 3: Build a Rooted Tree from Edges and Compute Subtree Sizes
Problem Statement
Given n nodes labeled 0 to n - 1, a list of parent-child edges for a rooted tree, and the root node, return the size of every node's subtree.
Why This Example Matters
It shows why representation matters. Tree algorithms become simpler once you convert raw edges into child lists.
Constraints or Assumptions
- the input edges form a valid rooted tree
- subtree size includes the node itself
- the root is given
Brute-Force Approach
For every recursive step, scan the entire edge list to find the current node's children.
Better Approach
Build an adjacency list once, then run one DFS recursion to compute subtree sizes.
Why the Better Approach Works
The adjacency list gives direct access to children, so each edge is processed once instead of being rediscovered repeatedly.
Pragmatic Java Choice
Use List<List<Integer>> when the tree comes from edge data instead of prebuilt node objects.
Java Solution
import java.util.ArrayList;
import java.util.List;
class SubtreeSizeExample {
static int[] subtreeSizesByScanningEdges(int n, int[][] edges, int root) {
int[] sizes = new int[n];
computeByScanning(root, edges, sizes);
return sizes;
}
private static int computeByScanning(int node, int[][] edges, int[] sizes) {
int size = 1;
for (int[] edge : edges) {
if (edge[0] == node) {
size += computeByScanning(edge[1], edges, sizes);
}
}
sizes[node] = size;
return size;
}
static int[] subtreeSizesWithAdjacency(int n, int[][] edges, int root) {
List<List<Integer>> children = new ArrayList<>();
for (int node = 0; node < n; node++) {
children.add(new ArrayList<>());
}
for (int[] edge : edges) {
children.get(edge[0]).add(edge[1]);
}
int[] sizes = new int[n];
computeWithAdjacency(root, children, sizes);
return sizes;
}
private static int computeWithAdjacency(int node, List<List<Integer>> children, int[] sizes) {
int size = 1;
for (int child : children.get(node)) {
size += computeWithAdjacency(child, children, sizes);
}
sizes[node] = size;
return size;
}
}
Dry Run
Use n = 5, edges = [[0, 1], [0, 2], [1, 3], [1, 4]], root = 0.
Adjacency list:
0 -> [1, 2]1 -> [3, 4]2 -> []3 -> []4 -> []
Subtree sizes:
- nodes
3and4return1 - node
1returns1 + 1 + 1 = 3 - node
2returns1 - node
0returns1 + 3 + 1 = 5
Time and Space Complexity
- Brute force:
O(n * e)time in the worst case because edges are rescanned repeatedly,O(h)call stack space - Better approach:
O(n + e)time,O(n + e)adjacency space plusO(h)call stack space
Edge Cases
- single-node tree gives subtree size
1 - leaves always have subtree size
1 - malformed edge input would break the tree assumption
Common Mistakes
- recomputing child lookup repeatedly from the raw edge list
- forgetting to count the current node in its own subtree size
- confusing parent-child direction in the edge list
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- tree traversals usually touch each node once, so the natural baseline is often
O(n)time - recursion on trees typically uses
O(h)call stack space, wherehis tree height - queue-based level traversal uses
O(w)extra space, wherewis the maximum width - a good representation choice, such as child lists instead of rescanning edges, often matters as much as the traversal itself
Choose recursion when:
- the answer for a node depends on answers from its children
- the subtree structure is naturally recursive
- the tree height is manageable
Choose explicit queue or stack traversal when:
- the problem is naturally level-based
- you want to avoid deep recursion
- the traversal order is breadth-first rather than depth-first
Recognition signals for tree problems:
- parent-child hierarchy
- no cycles and exactly one root path in rooted settings
- subtree answers combine into a whole-tree answer
Signals not to force tree logic:
- the input is really a general graph with cycles
- the structure is mostly sequential rather than hierarchical
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- missing
nullbase cases - mixing height and depth definitions
- forgetting whether leaf handling should return
0,1, or-1based on the chosen metric - representing a tree poorly and then fighting the traversal code
Boundary and representation risks:
- empty tree
- single-node tree
- skewed trees with large height
- incorrect parent-child direction when building from edges
Short debugging checklist:
- What does the base case return for
null? - What information do I need from each child?
- Am I computing depth or height?
- Does my representation give direct access to children?
- If the tree came from edges, have I built it only once?
6. Practice Problems
Easy
- Title: Maximum Depth of Binary Tree
- One-line prompt: Return the maximum root-to-leaf depth.
- Expected pattern or core idea: Recursive height computation.
- Title: Count Complete Tree Nodes
- One-line prompt: Return the number of nodes in a binary tree.
- Expected pattern or core idea: Tree counting with recursion.
- Title: Same Tree
- One-line prompt: Decide whether two binary trees are identical.
- Expected pattern or core idea: Recursive structural comparison.
Medium
- Title: Balanced Binary Tree
- One-line prompt: Determine whether every node's subtree heights differ by at most one.
- Expected pattern or core idea: Recursive height summary.
- Title: Diameter of Binary Tree
- One-line prompt: Return the longest path length in the tree.
- Expected pattern or core idea: Bottom-up recursion combining subtree heights.
- Title: Subtree of Another Tree
- One-line prompt: Check whether one tree appears inside another.
- Expected pattern or core idea: Recursive comparison plus traversal.
Hard
- Title: Binary Tree Maximum Path Sum
- One-line prompt: Find the highest-value path through a binary tree.
- Expected pattern or core idea: Recursive subtree contribution summary.
- Title: Serialize and Deserialize Binary Tree
- One-line prompt: Convert a tree to text and back.
- Expected pattern or core idea: Representation plus traversal order.
- Title: Sum of Distances in Tree
- One-line prompt: Compute distance sums for every node in a tree.
- Expected pattern or core idea: Tree DP with rerooting insight.
7. Short Recap
The core idea of this chapter is that trees are hierarchical structures where each subtree can usually be solved the same way as the whole tree.
The most important optimization insight is that a good representation and a clean subtree-return recursion often eliminate repeated work immediately.
The most important implementation warning is to define height, depth, and base cases precisely before coding.
This chapter prepares the next chapter by making binary-tree shape and recursive traversal natural before specific traversal orders and binary-tree properties matter more.
8. Coverage Check
- 16.1 Tree terminology
- 16.2 Height, depth, and degree
- 16.3 Root, internal, and leaf nodes
- 16.4 Tree representation in Java
- 16.5 Recursion on trees
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 17: Binary Trees and Traversals
17: Binary Trees and Traversals
Goal: Teach learners the major binary-tree shape categories, the meaning of each traversal order, and when to use recursive, iterative, breadth-first, or Morris-style traversal in Java.
Outcome: By the end of this chapter, you can distinguish full, complete, perfect, and balanced binary trees; implement inorder, preorder, postorder, and level-order traversals; and explain how Morris traversal achieves inorder traversal with O(1) extra space.
1. Intuition First
Binary trees matter because many algorithms become easier when each node has at most two children. That restriction creates clean traversal rules and supports later ordered structures like BSTs and heaps.
A simple real-world analogy is a decision tree with yes or no branches. At each point you can move left or right, and the order in which you visit nodes changes what information you see first.
The core mental model is this: a traversal is a visitation rule. In preorder you visit the current node before its children. In inorder you visit the left subtree, then the current node, then the right subtree. In postorder you visit children before the current node. In level order you visit breadth-first.
The most common beginner confusion point is memorizing traversal names without tying them to what the algorithm needs. Traversal order should be chosen because it matches the problem's dependency structure.
In the roadmap, this chapter sharpens the binary-tree model before BST ordering, heaps, and trie branching add more specialized behavior.
2. Core Concepts and Techniques
Concept Cluster: Binary Tree Shapes
Key concepts in this block:
- 17.1 Full, complete, perfect, and balanced binary trees
Intuition
These terms describe shape constraints, not value ordering.
Why It Matters
Many tree guarantees and time bounds depend on shape. A balanced tree behaves very differently from a skewed one.
How It Works
- full binary tree: every node has either
0or2children - complete binary tree: every level is full except possibly the last, and the last level is filled left to right
- perfect binary tree: every internal node has
2children and all leaves are at the same depth - balanced binary tree: subtree heights stay within a limited difference, commonly at most
1in interview problems
Java Implementation Notes
- These shape properties are usually checked by traversal logic, not by special node fields.
- Complete trees are especially important for array-based heaps later.
Common Mistakes
- confusing full with complete
- assuming complete implies perfect
- treating balanced as identical to complete
Quick Example
class BinaryTreeShapeQuickNotes {
static boolean isLeaf(int leftExists, int rightExists) {
return leftExists == 0 && rightExists == 0;
}
}
Debugging Tip
Draw a counterexample for each term. The easiest way to remember the definitions is to see what each one allows that the others do not.
Advanced Note
Balanced structure is often the real reason operations stay logarithmic in later ordered trees.
Concept Cluster: Depth-First Traversals
Key concepts in this block:
- 17.2 Inorder traversal
- 17.3 Preorder traversal
- 17.4 Postorder traversal
Intuition
Depth-first traversals differ only in when the current node is processed relative to its children.
Why It Matters
Traversal order often reveals whether the problem depends on parent-before-child, child-before-parent, or left-root-right ordering.
How It Works
- inorder: left, root, right
- preorder: root, left, right
- postorder: left, right, root
Typical use cases:
- inorder on BSTs produces sorted values
- preorder is useful for copying or serialization with root-first logic
- postorder is useful when the answer for a node depends on both child results first
Java Implementation Notes
- Recursive traversal is the clearest first implementation.
- Iterative traversal uses an explicit stack and is worth learning because it makes control flow visible.
- Postorder iteration is often the trickiest because the current node must wait for both children.
Common Mistakes
- writing the right recursive calls but adding the value in the wrong place
- thinking inorder is special for all binary trees when it is only value-meaningful for BSTs
- pushing children in the wrong order for iterative preorder
Quick Example
import java.util.ArrayList;
import java.util.List;
class TraversalQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static List<Integer> preorder(TreeNode root) {
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
private static void preorder(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
result.add(node.value);
preorder(node.left, result);
preorder(node.right, result);
}
}
Debugging Tip
When a traversal output is wrong, annotate one node and ask exactly when its value should be recorded.
Advanced Note
Many tree DP problems are postorder in disguise because each parent depends on child summaries.
Concept Cluster: Level-Order Traversal and Morris Traversal
Key concepts in this block:
- 17.5 Level-order traversal
- 17.6 Morris traversal
Intuition
Level order visits the tree breadth-first by depth. Morris traversal temporarily threads the tree to avoid using a stack for inorder traversal.
Why It Matters
Level order is the standard tool for per-level processing. Morris traversal is an advanced but important example of trading temporary pointer rewiring for lower space.
How It Works
Level order:
- use a queue
- process nodes level by level
Morris inorder:
- for a node with a left child, find the rightmost node in its left subtree
- temporarily point that predecessor back to the current node
- move left first, then restore the pointer later and visit the current node
Java Implementation Notes
ArrayDequeworks well for level-order traversal queues.- Morris traversal mutates pointers temporarily, so it requires careful restoration.
- Use Morris only when the
O(1)extra-space benefit is meaningful and the tree can be safely rewired during traversal.
Common Mistakes
- forgetting to separate levels in BFS problems
- not restoring threaded pointers in Morris traversal
- using Morris traversal when recursive or stack-based traversal is clearer and sufficient
Quick Example
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
class LevelOrderQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> level = new ArrayList<>();
for (int count = 0; count < levelSize; count++) {
TreeNode current = queue.poll();
level.add(current.value);
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
result.add(level);
}
return result;
}
}
Debugging Tip
For Morris traversal, print when a temporary thread is created and removed. That makes pointer restoration errors obvious.
Advanced Note
Morris traversal is a good reminder that space optimization can require structural mutation, not just a clever loop.
3. Worked Examples and Full Solutions
Worked Example 1: Binary Tree Level-Order Traversal
Problem Statement
Given the root of a binary tree, return the node values level by level from top to bottom.
Why This Example Matters
It is the standard breadth-first tree problem and the easiest way to see why queue-based traversal differs from DFS.
Constraints or Assumptions
- the tree may be empty
- nodes on the same depth should appear together
- left child should be processed before right child at the same level
Brute-Force Approach
First compute the height of the tree, then for each level call a helper that collects nodes exactly at that depth.
Better Approach
Use a queue and process one level at a time.
Why the Better Approach Works
The queue naturally stores the next frontier of nodes. Measuring the queue size at the start of each round gives you one complete level.
Pragmatic Java Choice
Use ArrayDeque<TreeNode> as the queue and group levels using the current queue size.
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
class LevelOrderExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static List<List<Integer>> levelOrderByDepthQueries(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
int height = height(root);
for (int depth = 0; depth <= height; depth++) {
List<Integer> level = new ArrayList<>();
collectLevel(root, depth, level);
result.add(level);
}
return result;
}
private static int height(TreeNode node) {
if (node == null) {
return -1;
}
return 1 + Math.max(height(node.left), height(node.right));
}
private static void collectLevel(TreeNode node, int depth, List<Integer> level) {
if (node == null) {
return;
}
if (depth == 0) {
level.add(node.value);
return;
}
collectLevel(node.left, depth - 1, level);
collectLevel(node.right, depth - 1, level);
}
static List<List<Integer>> levelOrderWithQueue(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> level = new ArrayList<>();
for (int count = 0; count < levelSize; count++) {
TreeNode current = queue.poll();
level.add(current.value);
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
result.add(level);
}
return result;
}
}
Dry Run
Use a tree with root 1, children 2 and 3, and node 2 having children 4 and 5.
Queue method:
- start queue
[1], process level[1] - queue becomes
[2, 3], process level[2, 3] - queue becomes
[4, 5], process level[4, 5] - queue is empty, stop
Time and Space Complexity
- Brute force:
O(nh)time in the worst case,O(h)call stack space - Better approach:
O(n)time,O(w)extra queue space
Edge Cases
- empty tree returns
[] - single-node tree returns one level
- skewed tree gives one node per level
Common Mistakes
- not separating levels correctly
- forgetting to return an empty result for
null - using DFS order by accident when the problem expects BFS
Worked Example 2: Inorder Traversal with Morris Traversal
Problem Statement
Given the root of a binary tree, return its inorder traversal.
Why This Example Matters
It connects the most common DFS traversal with an advanced space-optimization technique.
Constraints or Assumptions
- the tree may be empty
- output should be in left-root-right order
- temporary pointer rewiring is allowed during traversal as long as it is restored
Brute-Force Approach
Use recursive inorder traversal.
Better Approach
Use Morris inorder traversal to achieve O(1) extra space.
Why the Better Approach Works
When a node has a left subtree, its inorder predecessor is the rightmost node in that left subtree. Temporarily linking that predecessor back to the current node lets you return to the current node without an explicit stack.
Pragmatic Java Choice
Use recursive or stack-based inorder in most code. Use Morris when space is the real constraint and you are comfortable with pointer restoration.
Java Solution
import java.util.ArrayList;
import java.util.List;
class InorderMorrisExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static List<Integer> inorderRecursive(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root, result);
return result;
}
private static void inorder(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
inorder(node.left, result);
result.add(node.value);
inorder(node.right, result);
}
static List<Integer> inorderMorris(TreeNode root) {
List<Integer> result = new ArrayList<>();
TreeNode current = root;
while (current != null) {
if (current.left == null) {
result.add(current.value);
current = current.right;
} else {
TreeNode predecessor = current.left;
while (predecessor.right != null && predecessor.right != current) {
predecessor = predecessor.right;
}
if (predecessor.right == null) {
predecessor.right = current;
current = current.left;
} else {
predecessor.right = null;
result.add(current.value);
current = current.right;
}
}
}
return result;
}
}
Dry Run
Use root 2 with left child 1 and right child 3.
Morris traversal:
- current
2has left child, predecessor is1 - thread
1.rightto2, move to1 1has no left child, visit1, move to threaded2- predecessor thread exists, remove it, visit
2, move to3 3has no left child, visit3
Result: [1, 2, 3].
Time and Space Complexity
- Brute force:
O(n)time,O(h)call stack space - Better approach:
O(n)time,O(1)extra space
Edge Cases
- empty tree returns empty list
- single-node tree returns one value
- highly skewed trees still work because threading is restored
Common Mistakes
- forgetting to restore predecessor links
- visiting the current node at the wrong time
- treating Morris traversal as simpler than it is
Worked Example 3: Check Whether a Binary Tree Is Height-Balanced
Problem Statement
Given the root of a binary tree, return true if it is height-balanced.
Why This Example Matters
It makes the balanced-tree concept concrete and shows how postorder-style summaries avoid repeated work.
Constraints or Assumptions
- a tree is balanced if every node's left and right subtree heights differ by at most
1 - an empty tree is balanced
Brute-Force Approach
For every node, recompute the height of the left and right subtrees separately, then recurse into both children.
Better Approach
Use one bottom-up DFS that returns the subtree height or a failure marker.
Why the Better Approach Works
Each node needs child heights to decide whether it is balanced. Returning height information bottom-up lets every subtree be solved once.
Pragmatic Java Choice
Return -2 as a special failure marker because valid heights under the edge-count convention are -1 or greater.
Java Solution
class BalancedTreeExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static boolean isBalancedBruteForce(TreeNode root) {
if (root == null) {
return true;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return Math.abs(leftHeight - rightHeight) <= 1
&& isBalancedBruteForce(root.left)
&& isBalancedBruteForce(root.right);
}
private static int height(TreeNode node) {
if (node == null) {
return -1;
}
return 1 + Math.max(height(node.left), height(node.right));
}
static boolean isBalancedOptimized(TreeNode root) {
return checkHeight(root) != -2;
}
private static int checkHeight(TreeNode node) {
if (node == null) {
return -1;
}
int leftHeight = checkHeight(node.left);
if (leftHeight == -2) {
return -2;
}
int rightHeight = checkHeight(node.right);
if (rightHeight == -2) {
return -2;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -2;
}
return 1 + Math.max(leftHeight, rightHeight);
}
}
Dry Run
Use a skewed tree 1 -> 2 -> 3 down the left side.
Optimized check:
- node
3returns height0 - node
2sees left0, right-1, returns1 - node
1sees left1, right-1, difference2, returns failure marker-2 - final result is
false
Time and Space Complexity
- Brute force:
O(n^2)time in the worst case,O(h)call stack space - Better approach:
O(n)time,O(h)call stack space
Edge Cases
- empty tree is balanced
- single-node tree is balanced
- skewed tree often fails quickly in the optimized version
Common Mistakes
- recomputing heights repeatedly
- not agreeing on the height convention
- forgetting that every node, not just the root, must satisfy the balance condition
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- recursive DFS traversals usually run in
O(n)time withO(h)call stack space - level-order traversal runs in
O(n)time withO(w)queue space - Morris traversal preserves
O(n)time while reducing extra space toO(1), but the implementation is more delicate - bottom-up traversal summaries often avoid repeated subtree work compared with naive top-down checks
Choose preorder when:
- the current node must be processed before its children
- you are building or serializing root-first structure
Choose inorder when:
- left-before-root-before-right order matters
- you later work with BST sorted order
Choose postorder when:
- the parent depends on completed child answers
Choose level order when:
- the problem is explicitly per level or shortest-depth style
Use Morris traversal when:
- extra stack space truly matters
- temporary pointer rewiring is acceptable
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- putting node visitation in the wrong place for DFS
- mixing up tree shape terminology
- failing to separate BFS levels
- not restoring temporary Morris threads
Boundary and shape risks:
- empty tree
- single-node tree
- skewed trees with high recursion depth
- duplicate values that do not affect traversal order but can confuse manual tracing
Short debugging checklist:
- When exactly should the current node be visited?
- Does the problem need DFS or BFS?
- Am I relying on a shape property like balanced or complete correctly?
- If I use Morris traversal, are all temporary links restored?
- Can I state what each traversal order means without looking it up?
6. Practice Problems
Easy
- Title: Binary Tree Inorder Traversal
- One-line prompt: Return the inorder sequence of a binary tree.
- Expected pattern or core idea: Left-root-right DFS.
- Title: Binary Tree Preorder Traversal
- One-line prompt: Return the preorder sequence of a binary tree.
- Expected pattern or core idea: Root-left-right DFS.
- Title: Binary Tree Level Order Traversal
- One-line prompt: Return the values grouped by depth.
- Expected pattern or core idea: Queue-based BFS.
Medium
- Title: Binary Tree Zigzag Level Order Traversal
- One-line prompt: Traverse the tree level by level while alternating direction.
- Expected pattern or core idea: BFS with level-direction handling.
- Title: Balanced Binary Tree
- One-line prompt: Check whether the tree is height-balanced.
- Expected pattern or core idea: Bottom-up height summary.
- Title: Flatten Binary Tree to Linked List
- One-line prompt: Rewrite the tree into preorder-linked form.
- Expected pattern or core idea: Preorder reasoning with pointer updates.
Hard
- Title: Binary Tree Postorder Traversal
- One-line prompt: Return the postorder sequence without recursion if possible.
- Expected pattern or core idea: Iterative postorder control.
- Title: Recover Binary Search Tree
- One-line prompt: Fix two swapped BST nodes.
- Expected pattern or core idea: Inorder ordering, possibly with Morris traversal.
- Title: Vertical Order Traversal of a Binary Tree
- One-line prompt: Group nodes by vertical columns.
- Expected pattern or core idea: BFS or DFS with coordinate tracking.
7. Short Recap
The core idea of this chapter is that traversal order is a deliberate choice based on what information must be available before or after a node is processed.
The most important optimization insight is that bottom-up DFS and Morris traversal show two different ways to avoid unnecessary extra work or space.
The most important implementation warning is to keep traversal order and shape terminology precise, because small wording mistakes become wrong algorithms quickly.
This chapter prepares the next chapter by making inorder meaning and binary-tree structure stable before BSTs attach ordering rules to the node values themselves.
8. Coverage Check
- 17.1 Full, complete, perfect, and balanced binary trees
- 17.2 Inorder traversal
- 17.3 Preorder traversal
- 17.4 Postorder traversal
- 17.5 Level-order traversal
- 17.6 Morris traversal
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 18: Binary Search Trees
18: Binary Search Trees
Goal: Teach learners how value ordering inside a binary tree changes search, insertion, deletion, and query strategies, and how to reason about BST correctness in Java.
Outcome: By the end of this chapter, you can use the BST property for efficient search, implement insert and delete, validate whether a tree is a BST, solve kth-smallest style problems, and recognize common BST interview patterns.
1. Intuition First
Binary search trees matter because they combine the hierarchical shape of trees with the ordered elimination idea of binary search. The structure of the tree tells you where a value can and cannot be.
A simple real-world analogy is a paper filing system where every drawer splits records into smaller and larger values relative to one label. To find a record, you never check every drawer. You follow the only path that can still contain it.
The core mental model is this: for every node, all values in the left subtree are smaller, and all values in the right subtree are larger. That local rule creates a global searchable order.
The most common beginner confusion point is thinking a BST is automatically balanced. It is not. A BST can still degenerate into a chain if insertion order is unlucky.
In the roadmap, this chapter turns traversal knowledge into ordered-tree reasoning. It also prepares heaps, tries, and advanced balanced-tree ideas later.
2. Core Concepts and Techniques
Concept Cluster: BST Property, Search, Insert, and Delete
Key concepts in this block:
- 18.1 BST property and search
- 18.2 Insert and delete operations
Intuition
Searching in a BST is just repeated branch elimination based on the current node's value.
Why It Matters
BSTs are the first major example where tree structure and value ordering work together to reduce search time.
How It Works
- if target equals current value, stop
- if target is smaller, move left
- if target is larger, move right
Insertion:
- follow the same search path until a
nullchild is found - attach the new value there
Deletion cases:
- no children: remove the node directly
- one child: replace the node with its child
- two children: replace the node with its inorder successor or predecessor, then delete that moved value from the subtree
Java Implementation Notes
- Recursive BST code is readable because the subtree replacement logic maps cleanly to return values.
- Iterative search is often the practical default for lookup.
- Be explicit about how duplicates are handled. Many interview BSTs assume all values are distinct.
Common Mistakes
- treating deletion as a simple remove without handling the three structural cases
- assuming search is logarithmic even when the tree is skewed
- placing equal values inconsistently
Quick Example
class BstSearchQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static boolean contains(TreeNode root, int target) {
TreeNode current = root;
while (current != null) {
if (current.value == target) {
return true;
}
current = target < current.value ? current.left : current.right;
}
return false;
}
}
Debugging Tip
During deletion, draw the exact subtree being returned after each case. Most bugs come from returning the wrong replacement root.
Advanced Note
Balanced BST variants exist because the BST ordering rule alone does not prevent pathological shape.
Concept Cluster: Validating a BST
Key concepts in this block:
- 18.3 Validating a BST
Intuition
A BST is not valid just because each node is larger than its left child and smaller than its right child. The whole subtree range matters.
Why It Matters
This is one of the most common correctness traps in tree interviews.
How It Works
- pass an allowable value range down the tree
- every node must lie strictly between the lower and upper bounds it inherits
- alternatively, inorder traversal of a valid BST must be strictly increasing if duplicates are not allowed
Java Implementation Notes
- Use
longbounds if node values areint, so edge values nearInteger.MIN_VALUEandInteger.MAX_VALUEare still handled safely. - Range validation is usually easier to explain than local-child checks.
Common Mistakes
- only comparing a node with its immediate children
- using inclusive bounds when duplicates are not allowed
- forgetting that a right subtree node must be larger than every ancestor on the left path too
Quick Example
class ValidateBstQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static boolean isValid(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private static boolean isValid(TreeNode node, long lower, long upper) {
if (node == null) {
return true;
}
if (node.value <= lower || node.value >= upper) {
return false;
}
return isValid(node.left, lower, node.value)
&& isValid(node.right, node.value, upper);
}
}
Debugging Tip
When a local-child check seems to pass but the tree is still invalid, write the inherited lower and upper bounds beside each node.
Advanced Note
Inorder monotonicity is a compact validation method, but range-based validation often communicates the correctness idea more directly.
Concept Cluster: Kth Smallest and Common BST Interview Questions
Key concepts in this block:
- 18.4 Kth smallest and order-statistics style problems
- 18.5 Common BST interview questions
Intuition
Because inorder traversal of a BST is sorted, many rank and predecessor or successor questions reduce to controlled inorder traversal.
Why It Matters
This is where BSTs stop being just searchable storage and become tools for ordered queries.
How It Works
- kth smallest: perform inorder traversal and stop after visiting
knodes - predecessor: largest value smaller than target
- successor: smallest value larger than target
- lowest common ancestor in BST: move left or right together until the split point
Java Implementation Notes
- Iterative inorder with a stack is often better than storing the full inorder list if you only need the kth element.
- Common BST questions usually reuse the ordering rule, not a completely new trick.
Common Mistakes
- collecting all inorder values when only the first
kare needed - forgetting that predecessor and successor depend on the ordering path, not arbitrary traversal
- assuming all common tree interview questions are BST questions
Quick Example
import java.util.ArrayDeque;
import java.util.Deque;
class KthSmallestQuickExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
k--;
if (k == 0) {
return current.value;
}
current = current.right;
}
throw new IllegalArgumentException("k is larger than the number of nodes");
}
}
Debugging Tip
If a BST query feels difficult, ask what inorder order would reveal. Many answers become obvious after that step.
Advanced Note
Order-statistics trees maintain subtree sizes to answer rank queries faster, but the basic inorder idea is enough for this stage.
3. Worked Examples and Full Solutions
Worked Example 1: Maintain a BST with Search, Insert, and Delete
Problem Statement
Design a BST that supports search, insert, and delete for distinct integer keys.
Why This Example Matters
It forces you to use the BST property for both navigation and structural updates.
Constraints or Assumptions
- keys are distinct
- operations should preserve the BST property
- the tree does not self-balance automatically
Brute-Force Approach
Store all values in a sorted list. Use linear insertion and deletion by shifting values, and scan linearly for search.
Better Approach
Store values in a BST and use ordered branching for search, insert, and delete.
Why the Better Approach Works
The BST property tells you exactly which subtree can still contain the target or insertion position. Deletion preserves that order by reconnecting valid subtrees carefully.
Pragmatic Java Choice
Use iterative search and recursive insert or delete because deletion case handling is cleaner when subtree roots are returned.
Java Solution
class BstOperationsExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static boolean search(TreeNode root, int target) {
TreeNode current = root;
while (current != null) {
if (current.value == target) {
return true;
}
current = target < current.value ? current.left : current.right;
}
return false;
}
static TreeNode insert(TreeNode root, int value) {
if (root == null) {
return new TreeNode(value);
}
if (value < root.value) {
root.left = insert(root.left, value);
} else if (value > root.value) {
root.right = insert(root.right, value);
}
return root;
}
static TreeNode delete(TreeNode root, int value) {
if (root == null) {
return null;
}
if (value < root.value) {
root.left = delete(root.left, value);
} else if (value > root.value) {
root.right = delete(root.right, value);
} else {
if (root.left == null) {
return root.right;
}
if (root.right == null) {
return root.left;
}
TreeNode successor = findMinimum(root.right);
root.value = successor.value;
root.right = delete(root.right, successor.value);
}
return root;
}
private static TreeNode findMinimum(TreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}
Dry Run
Delete 50 from a BST where 50 has left subtree rooted at 30 and right subtree rooted at 70, and 70 has left child 60.
- node
50has two children - find inorder successor, which is the minimum of the right subtree:
60 - replace
50with60 - delete the original
60from the right subtree - BST order is preserved
Time and Space Complexity
- Brute force: search
O(n), insertO(n), deleteO(n)due to shifting or scanning - Better approach: average
O(h)time per operation wherehis tree height,O(h)call stack space for recursive insert or delete
Edge Cases
- insert into empty tree
- delete a leaf node
- delete a node with one child
- delete the root node
Common Mistakes
- not handling the two-child delete case correctly
- forgetting to reconnect returned subtrees
- assuming the tree stays balanced automatically
Worked Example 2: Validate a Binary Search Tree
Problem Statement
Given the root of a binary tree, return true if it is a valid BST.
Why This Example Matters
It is the canonical proof-oriented BST problem and exposes the difference between local checks and full-subtree constraints.
Constraints or Assumptions
- duplicate values are not allowed
- any invalid value anywhere in a subtree makes the whole tree invalid
Brute-Force Approach
At each node, only compare the node with its immediate left and right child.
Better Approach
Carry lower and upper bounds through recursion.
Why the Better Approach Works
Every node must satisfy all ordering constraints from its ancestors, not just from its parent.
Pragmatic Java Choice
Use long bounds even if values are int so extreme values remain valid test cases.
Java Solution
class ValidateBstExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static boolean isValidLocalCheck(TreeNode root) {
if (root == null) {
return true;
}
if (root.left != null && root.left.value >= root.value) {
return false;
}
if (root.right != null && root.right.value <= root.value) {
return false;
}
return isValidLocalCheck(root.left) && isValidLocalCheck(root.right);
}
static boolean isValidRangeCheck(TreeNode root) {
return isValidRangeCheck(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private static boolean isValidRangeCheck(TreeNode node, long lower, long upper) {
if (node == null) {
return true;
}
if (node.value <= lower || node.value >= upper) {
return false;
}
return isValidRangeCheck(node.left, lower, node.value)
&& isValidRangeCheck(node.right, node.value, upper);
}
}
Dry Run
Use a tree with root 10, left child 5, right child 15, and 15 having left child 6.
Local checks appear to pass at 10 and 15, but range checks reveal the issue:
- node
15's left child6must be greater than10because it is in the right subtree of10 6violates the inherited lower bound10- the tree is not a valid BST
Time and Space Complexity
- Brute force:
O(n)time but logically incorrect,O(h)call stack space - Better approach:
O(n)time,O(h)call stack space
Edge Cases
- empty tree is valid
- single-node tree is valid
- extreme integer values require careful bounds
Common Mistakes
- comparing only parent and child
- using inclusive bounds incorrectly
- forgetting that duplicates need a clear rule
Worked Example 3: Kth Smallest Element in a BST
Problem Statement
Given the root of a BST and an integer k, return the kth smallest value.
Why This Example Matters
It turns inorder traversal into an ordered query rather than just a listing procedure.
Constraints or Assumptions
1 <= k <= number of nodes- the tree is a valid BST
- duplicate values are not used in this version
Brute-Force Approach
Collect the full inorder traversal into a list, then return the value at index k - 1.
Better Approach
Perform iterative inorder traversal and stop as soon as the kth value is visited.
Why the Better Approach Works
Inorder traversal visits BST values in sorted order. The kth visited node is the kth smallest.
Pragmatic Java Choice
Use an explicit stack so you can stop early without building an entire list.
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
class KthSmallestExample {
static final class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
static int kthSmallestWithList(TreeNode root, int k) {
List<Integer> inorderValues = new ArrayList<>();
inorder(root, inorderValues);
return inorderValues.get(k - 1);
}
private static void inorder(TreeNode node, List<Integer> values) {
if (node == null) {
return;
}
inorder(node.left, values);
values.add(node.value);
inorder(node.right, values);
}
static int kthSmallestIterative(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
k--;
if (k == 0) {
return current.value;
}
current = current.right;
}
throw new IllegalArgumentException("k exceeds node count");
}
}
Dry Run
Use BST values [2, 3, 4, 5, 7, 8] arranged as a valid BST and k = 4.
Iterative inorder visits values in this order:
2345
The fourth visited value is 5.
Time and Space Complexity
- Brute force:
O(n)time,O(n)extra space - Better approach:
O(h + k)time,O(h)extra space
Edge Cases
k = 1returns the smallest valuek = nreturns the largest value- invalid
kshould be rejected or handled explicitly
Common Mistakes
- using preorder or postorder instead of inorder
- traversing the full tree when early stopping is enough
- assuming the method works on arbitrary binary trees
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- BST search, insert, and delete are
O(h)wherehis tree height, which is good only if the tree is reasonably balanced - validation and inorder-style queries usually run in
O(n)time because every node may need to be checked - iterative traversals use explicit stack space
O(h), while recursive traversals use call stack spaceO(h)
Choose BST search logic when:
- the structure satisfies the BST ordering property
- the question asks for predecessor, successor, search, rank-like, or ordered lookup behavior
Choose range validation when:
- you need to prove the BST property globally
Choose iterative inorder when:
- you need sorted BST values but do not need to store all of them
- early stopping matters
Signals not to force BST reasoning:
- the tree is not ordered by value
- the problem needs breadth-first shape information instead of ordered lookup
- the input can be badly skewed and worst-case performance matters strongly
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- incorrect subtree reconnection during deletion
- local-child validation instead of global-range validation
- forgetting how duplicates are handled
- assuming logarithmic performance without considering tree shape
Boundary and structural risks:
- empty tree
- deleting the root
- nodes with only one child
- extreme integer bounds in validation
Short debugging checklist:
- Does every subtree returned after insert or delete still satisfy BST order?
- Am I validating against ancestor bounds, not just parent comparisons?
- For kth-smallest, am I actually using inorder order?
- Could this BST be skewed enough to hurt runtime?
- Have I defined duplicate handling explicitly?
6. Practice Problems
Easy
- Title: Search in a Binary Search Tree
- One-line prompt: Return whether a target exists in the BST.
- Expected pattern or core idea: Ordered branching by value.
- Title: Insert into a Binary Search Tree
- One-line prompt: Insert a new key while preserving BST order.
- Expected pattern or core idea: Recursive or iterative insertion path.
- Title: Minimum Absolute Difference in BST
- One-line prompt: Find the smallest difference between any two BST values.
- Expected pattern or core idea: Inorder sorted order.
Medium
- Title: Validate Binary Search Tree
- One-line prompt: Determine whether a binary tree satisfies the BST property.
- Expected pattern or core idea: Range-based validation.
- Title: Delete Node in a BST
- One-line prompt: Remove a key while preserving BST structure.
- Expected pattern or core idea: Three delete cases.
- Title: Kth Smallest Element in a BST
- One-line prompt: Return the kth smallest value.
- Expected pattern or core idea: Inorder traversal.
Hard
- Title: Recover Binary Search Tree
- One-line prompt: Fix a BST where two values were swapped.
- Expected pattern or core idea: Inorder anomaly detection.
- Title: Serialize and Deserialize BST
- One-line prompt: Encode and decode a BST efficiently.
- Expected pattern or core idea: BST order plus traversal serialization.
- Title: Binary Search Tree Iterator
- One-line prompt: Build an iterator that returns BST values in sorted order.
- Expected pattern or core idea: Controlled inorder traversal with stack state.
7. Short Recap
The core idea of this chapter is that BSTs use tree structure plus value ordering to narrow work to one relevant path instead of scanning everything.
The most important optimization insight is that inorder traversal turns many ordered BST questions into simple rank or boundary problems.
The most important implementation warning is that deletion and validation are about full-subtree correctness, not local comparisons or pointer changes alone.
This chapter prepares the next chapter by making ordered tree reasoning comfortable before heaps use a different ordering rule that optimizes access to only the extreme value.
8. Coverage Check
- 18.1 BST property and search
- 18.2 Insert and delete operations
- 18.3 Validating a BST
- 18.4 Kth smallest and order-statistics style problems
- 18.5 Common BST interview questions
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 19: Heap and Priority Queue
19: Heap and Priority Queue
Goal: Teach learners how heaps maintain quick access to the smallest or largest element, how heapify and build-heap work, and when Java's PriorityQueue is the right tool.
Outcome: By the end of this chapter, you can explain min heaps and max heaps, implement heap insertion and extraction, use heapify and build-heap, apply PriorityQueue in Java, perform heap sort, and solve top K and streaming problems efficiently.
1. Intuition First
Heaps matter because some problems do not need full sorted order. They only need fast access to the current smallest or largest value while the rest of the data keeps changing.
A simple real-world analogy is a priority line at an airport. You do not need every passenger perfectly sorted in every way. You only need the next highest-priority passenger to be available immediately.
The core mental model is this: a heap is a complete binary tree where each parent obeys a priority rule relative to its children. In a min heap, every parent is less than or equal to its children. In a max heap, every parent is greater than or equal to its children.
The most common beginner confusion point is mixing heap order with full sorted order. A heap only guarantees parent-child priority, not left-to-right sorted traversal.
In the roadmap, this chapter builds on tree structure and ordering ideas from BSTs, but uses a different rule. Instead of searchable full ordering, heaps optimize repeated extreme-value access.
2. Core Concepts and Techniques
Concept Cluster: Min Heap, Max Heap, Heapify, and Build-Heap
Key concepts in this block:
- 19.1 Min heap and max heap
- 19.2 Heapify and build-heap
Intuition
A heap is a nearly compact tree that keeps the best candidate at the root.
Why It Matters
It supports repeated insertions and extractions of the minimum or maximum without full sorting.
How It Works
- min heap: parent value
<=child values - max heap: parent value
>=child values - complete tree shape allows efficient array representation
- insert uses sift-up to restore heap order
- extract-root uses sift-down after swapping with the last element
- heapify means restoring heap order from a node downward
- build-heap runs heapify from the last internal node backward
Array representation:
- left child index:
2 * index + 1 - right child index:
2 * index + 2 - parent index:
(index - 1) / 2
Java Implementation Notes
- Array-backed heaps are preferred because complete-tree shape eliminates pointer overhead.
- Build-heap is faster than inserting all values one by one into an empty heap.
- Max heaps in Java can be simulated with a reversed comparator in
PriorityQueue.
Common Mistakes
- assuming siblings are ordered
- forgetting to restore the heap after removing the root
- building a heap by repeated insertion when linear-time build-heap would be simpler
Quick Example
import java.util.ArrayList;
import java.util.List;
class MinHeapQuickExample {
static final class MinHeap {
private final List<Integer> values = new ArrayList<>();
void add(int value) {
values.add(value);
siftUp(values.size() - 1);
}
private void siftUp(int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (values.get(parent) <= values.get(index)) {
break;
}
swap(parent, index);
index = parent;
}
}
private void swap(int first, int second) {
int temp = values.get(first);
values.set(first, values.get(second));
values.set(second, temp);
}
}
}
Debugging Tip
After every insert or extract, check the parent-child rule for the changed path only. Heap bugs are almost always local repair bugs.
Advanced Note
Build-heap is O(n), not O(n log n), because most nodes are near the bottom and move only a short distance.
Concept Cluster: PriorityQueue in Java and Heap Sort
Key concepts in this block:
- 19.3 PriorityQueue in Java
- 19.4 Heap sort
Intuition
PriorityQueue is Java's ready-made heap. Heap sort uses heap extraction repeatedly to place values into final sorted order.
Why It Matters
Many interview problems want heap behavior, not a custom heap implementation. Heap sort also shows how a heap can become a full sorting algorithm.
How It Works
- Java
PriorityQueueis a min heap by default - use
Comparator.reverseOrder()for max-heap behavior - heap sort builds a max heap, then swaps the root with the last unsorted position and restores the heap
Java Implementation Notes
- Prefer
PriorityQueueunless the problem explicitly asks you to implement the heap yourself. - Heap sort is in-place on the array, but it is not stable.
PriorityQueuegives cleanoffer,poll, andpeekoperations.
Common Mistakes
- expecting
PriorityQueueiteration to be sorted - forgetting that
PriorityQueueis min-heap by default - heap-sorting with a min heap but writing the output logic for a max heap
Quick Example
import java.util.Comparator;
import java.util.PriorityQueue;
class PriorityQueueQuickExample {
static int kthLargest(int[] values, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int value : values) {
minHeap.offer(value);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
static PriorityQueue<Integer> maxHeap() {
return new PriorityQueue<>(Comparator.reverseOrder());
}
}
Debugging Tip
If a PriorityQueue result looks wrong, check whether you actually needed a min heap or a max heap.
Advanced Note
Heap sort is a strong worst-case option, but many real systems prefer different sorts because stability and cache behavior also matter.
Concept Cluster: Top K and Streaming Problems
Key concepts in this block:
- 19.5 Top K and streaming problems
Intuition
If you only need the best k values, storing all values in fully sorted order is often wasteful.
Why It Matters
This is the most common interview use case for heaps and priority queues.
How It Works
- for top
klargest values, keep a min heap of sizek - for top
ksmallest values, keep a max heap of sizek - in streaming problems, update the heap as new values arrive
- the root always tells you the current boundary of the kept set
Java Implementation Notes
- A fixed-size heap is often the cleanest answer for top K tasks.
- Streaming problems usually care about amortized updates, not full re-sorting after every input.
Common Mistakes
- sorting the full stream after every insertion
- choosing the wrong heap direction for the boundary element
- keeping more than
kelements when onlykare needed
Quick Example
import java.util.PriorityQueue;
class StreamingQuickExample {
static final class KthLargestStream {
private final int k;
private final PriorityQueue<Integer> minHeap = new PriorityQueue<>();
KthLargestStream(int k) {
this.k = k;
}
int add(int value) {
minHeap.offer(value);
if (minHeap.size() > k) {
minHeap.poll();
}
return minHeap.peek();
}
}
}
Debugging Tip
State what the heap root means after every operation. In a top-K-largest stream with a min heap, the root is the current kth largest.
Advanced Note
Top K problems are usually about maintaining a boundary, not about sorting everything.
3. Worked Examples and Full Solutions
Worked Example 1: Design a Min Heap with Build-Heap
Problem Statement
Implement a min heap that supports peek, add, and extractMin, and can also build a heap from an existing array.
Why This Example Matters
It makes the heap property concrete and shows the difference between incremental insertion and bottom-up build-heap.
Constraints or Assumptions
- duplicates are allowed
- extraction from an empty heap should fail clearly
- the underlying storage is an array-like structure
Brute-Force Approach
Store values in an unsorted list. add is cheap, but peek and extractMin must scan the entire list to find the minimum.
Better Approach
Use a binary min heap with sift-up, sift-down, and bottom-up build-heap.
Why the Better Approach Works
The heap property keeps the smallest value at the root. Local repairs after insertions or deletions are enough because only one root-to-leaf path can become invalid each time.
Pragmatic Java Choice
Use an ArrayList<Integer> to focus on heap logic instead of manual resizing.
Java Solution
import java.util.ArrayList;
import java.util.List;
class MinHeapExample {
static final class UnsortedMinStore {
private final List<Integer> values = new ArrayList<>();
void add(int value) {
values.add(value);
}
int peek() {
if (values.isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
int minimum = values.get(0);
for (int value : values) {
minimum = Math.min(minimum, value);
}
return minimum;
}
int extractMin() {
if (values.isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
int minimumIndex = 0;
for (int index = 1; index < values.size(); index++) {
if (values.get(index) < values.get(minimumIndex)) {
minimumIndex = index;
}
}
int minimum = values.get(minimumIndex);
values.remove(minimumIndex);
return minimum;
}
}
static final class MinHeap {
private final List<Integer> values = new ArrayList<>();
MinHeap() {
}
MinHeap(int[] initialValues) {
for (int value : initialValues) {
values.add(value);
}
buildHeap();
}
int peek() {
if (values.isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
return values.get(0);
}
void add(int value) {
values.add(value);
siftUp(values.size() - 1);
}
int extractMin() {
if (values.isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
int minimum = values.get(0);
int lastIndex = values.size() - 1;
swap(0, lastIndex);
values.remove(lastIndex);
if (!values.isEmpty()) {
siftDown(0);
}
return minimum;
}
private void buildHeap() {
for (int index = values.size() / 2 - 1; index >= 0; index--) {
siftDown(index);
}
}
private void siftUp(int index) {
while (index > 0) {
int parent = (index - 1) / 2;
if (values.get(parent) <= values.get(index)) {
break;
}
swap(parent, index);
index = parent;
}
}
private void siftDown(int index) {
int size = values.size();
while (true) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int smallest = index;
if (leftChild < size && values.get(leftChild) < values.get(smallest)) {
smallest = leftChild;
}
if (rightChild < size && values.get(rightChild) < values.get(smallest)) {
smallest = rightChild;
}
if (smallest == index) {
break;
}
swap(index, smallest);
index = smallest;
}
}
private void swap(int first, int second) {
int temp = values.get(first);
values.set(first, values.get(second));
values.set(second, temp);
}
}
}
Dry Run
Build a heap from [7, 3, 10, 1, 5].
Bottom-up build:
- start from the last internal node
- heapify the subtree rooted at
3if needed - heapify the root
7, which swaps down until1reaches the root - final min heap root is
1
Extracting the minimum:
- swap root
1with the last element - remove the last element
- sift down the new root until the heap property is restored
Time and Space Complexity
- Brute force:
addO(1),peekO(n),extractMinO(n) - Better approach:
peekO(1),addO(log n),extractMinO(log n), build-heapO(n)
Edge Cases
- extracting from an empty heap
- duplicate values
- building a heap from an empty array
Common Mistakes
- forgetting to sift down after extraction
- computing child indexes incorrectly
- not realizing build-heap is different from repeated insertion
Worked Example 2: Heap Sort
Problem Statement
Given an integer array, sort it in ascending order using heap sort.
Why This Example Matters
It shows how heap structure can produce a full in-place sort with guaranteed O(n log n) time.
Constraints or Assumptions
- in-place sorting is desired
- stability is not required
- the array may contain duplicates
Brute-Force Approach
Use selection sort and repeatedly place the maximum remaining element at the end.
Better Approach
Build a max heap, then repeatedly move the root to the end of the unsorted region and restore the heap.
Why the Better Approach Works
The max heap guarantees that the largest unsorted value is always at the root. Moving it to the array end fixes one final position per step.
Pragmatic Java Choice
Implement heap sort directly on the input array so the relationship between array indexes and heap positions stays visible.
Java Solution
class HeapSortExample {
static void selectionSort(int[] values) {
for (int end = values.length - 1; end >= 0; end--) {
int maximumIndex = 0;
for (int index = 1; index <= end; index++) {
if (values[index] > values[maximumIndex]) {
maximumIndex = index;
}
}
swap(values, maximumIndex, end);
}
}
static void heapSort(int[] values) {
int size = values.length;
for (int index = size / 2 - 1; index >= 0; index--) {
siftDown(values, size, index);
}
for (int end = size - 1; end > 0; end--) {
swap(values, 0, end);
siftDown(values, end, 0);
}
}
private static void siftDown(int[] values, int size, int index) {
while (true) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int largest = index;
if (leftChild < size && values[leftChild] > values[largest]) {
largest = leftChild;
}
if (rightChild < size && values[rightChild] > values[largest]) {
largest = rightChild;
}
if (largest == index) {
break;
}
swap(values, index, largest);
index = largest;
}
}
private static void swap(int[] values, int first, int second) {
int temp = values[first];
values[first] = values[second];
values[second] = temp;
}
}
Dry Run
Use values = [4, 10, 3, 5, 1].
- build max heap so the root becomes
10 - swap
10with the last position - reduce heap size and sift down the new root
- next largest value reaches the root and is moved next
- continue until the array becomes
[1, 3, 4, 5, 10]
Time and Space Complexity
- Brute force:
O(n^2)time,O(1)extra space - Better approach:
O(n log n)time,O(1)extra space
Edge Cases
- empty array remains empty
- one-element array is already sorted
- duplicates are allowed but heap sort is not stable
Common Mistakes
- building a min heap instead of a max heap for ascending order
- forgetting to shrink the heap size after placing the maximum
- assuming heap order means the array is already globally sorted
Worked Example 3: Kth Largest Element in a Stream
Problem Statement
Design a data structure that returns the kth largest element after each new stream insertion.
Why This Example Matters
It is the most common real use of PriorityQueue in interview settings.
Constraints or Assumptions
- values arrive one at a time
- only the kth largest element is needed, not the full sorted stream
kis fixed
Brute-Force Approach
Store every seen value in a list and sort the whole list after each insertion.
Better Approach
Maintain a min heap of size k.
Why the Better Approach Works
The heap stores exactly the current k largest values. The smallest among them is the kth largest overall, so it sits at the root.
Pragmatic Java Choice
Use PriorityQueue<Integer> directly because the problem is about maintaining the boundary, not implementing the heap yourself.
Java Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
class KthLargestStreamExample {
static final class NaiveKthLargest {
private final int k;
private final List<Integer> values = new ArrayList<>();
NaiveKthLargest(int k) {
this.k = k;
}
int add(int value) {
values.add(value);
Collections.sort(values);
return values.get(values.size() - k);
}
}
static final class HeapKthLargest {
private final int k;
private final PriorityQueue<Integer> minHeap = new PriorityQueue<>();
HeapKthLargest(int k) {
this.k = k;
}
int add(int value) {
minHeap.offer(value);
if (minHeap.size() > k) {
minHeap.poll();
}
return minHeap.peek();
}
}
}
Dry Run
Use k = 3 and stream values 4, 5, 8, 2, 10.
Min-heap of size 3:
- add
4-> heap[4] - add
5-> heap[4, 5] - add
8-> heap[4, 5, 8], current 3rd largest is4 - add
2-> heap becomes size4, remove2, root stays4 - add
10-> heap temporarily has four values, remove smallest4, root becomes5
The current 3rd largest is now 5.
Time and Space Complexity
- Brute force:
O(n log n)per insertion after sorting all seen values - Better approach:
O(log k)per insertion,O(k)extra space
Edge Cases
- fewer than
kvalues seen so far requires a clear problem convention - duplicate values still count as separate elements
- negative values work normally
Common Mistakes
- using a max heap when a fixed-size min heap is the correct boundary structure
- sorting the full history after every update
- forgetting what the heap root represents
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- heaps give
O(1)root access andO(log n)insert or extract, which is ideal when only the smallest or largest item matters repeatedly - build-heap in
O(n)is better than repeated insertion when you already have all data up front - heap sort gives in-place
O(n log n)sorting but sacrifices stability - fixed-size heaps reduce top K maintenance from full re-sorting to
O(log k)updates
Choose a min heap when:
- you need repeated access to the smallest value
- you want to maintain the top
klargest values with the smallest kept boundary at the root
Choose a max heap when:
- you need repeated access to the largest value
- you want to maintain the top
ksmallest values with the largest kept boundary at the root
Choose PriorityQueue when:
- the problem is about heap behavior, not heap implementation details
Choose heap sort when:
- you need guaranteed
O(n log n)time and in-place sorting - stability is not required
Signals not to force heaps:
- the problem needs arbitrary search by value
- a full sorted order is needed only once and another sort fits better
- the dataset is tiny and simpler logic is clearer
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- wrong parent or child index formulas
- sifting in the wrong direction after updates
- misunderstanding what the heap root means in top K problems
- expecting
PriorityQueueiteration to return sorted order
Boundary and representation risks:
- empty heap operations
- duplicate values
- incorrect heap size management during heap sort
- using the wrong comparator for min or max behavior
Short debugging checklist:
- Does every parent satisfy the heap rule relative to its children?
- After extraction, did I restore the heap from the root downward?
- For top K, what exact boundary does the root represent?
- Should I use a min heap or a max heap here?
- If I already have all values, would build-heap be simpler than repeated insertion?
6. Practice Problems
Easy
- Title: Last Stone Weight
- One-line prompt: Repeatedly remove the two largest stones and insert the remainder.
- Expected pattern or core idea: Max heap.
- Title: Kth Largest Element in an Array
- One-line prompt: Return the kth largest value from a static array.
- Expected pattern or core idea: Fixed-size min heap.
- Title: Sort Characters by Frequency
- One-line prompt: Return characters ordered by decreasing count.
- Expected pattern or core idea: Priority queue over frequency pairs.
Medium
- Title: Top K Frequent Elements
- One-line prompt: Return the
kmost frequent values. - Expected pattern or core idea: Frequency map plus fixed-size heap.
- One-line prompt: Return the
- Title: K Closest Points to Origin
- One-line prompt: Keep the
kclosest points by distance. - Expected pattern or core idea: Max heap of size
k.
- One-line prompt: Keep the
- Title: Find Median from Data Stream
- One-line prompt: Maintain the median as values stream in.
- Expected pattern or core idea: Two heaps.
Hard
- Title: Merge k Sorted Lists
- One-line prompt: Merge multiple sorted linked lists into one sorted list.
- Expected pattern or core idea: Min heap over current list heads.
- Title: Sliding Window Median
- One-line prompt: Return the median for each moving window.
- Expected pattern or core idea: Two heaps plus lazy deletion.
- Title: IPO
- One-line prompt: Maximize capital after selecting up to
kprojects. - Expected pattern or core idea: Sorted availability plus max heap.
- One-line prompt: Maximize capital after selecting up to
7. Short Recap
The core idea of this chapter is that heaps optimize repeated access to the best current candidate without fully sorting everything.
The most important optimization insight is that build-heap, fixed-size heaps, and PriorityQueue let you avoid repeated global sorting in top K and streaming tasks.
The most important implementation warning is to remember that heap order is local parent-child order, not complete sorted order.
This chapter prepares the next chapter by showing a tree structure optimized for one kind of lookup before tries optimize prefix-based lookup over strings instead of numeric priority.
8. Coverage Check
- 19.1 Min heap and max heap
- 19.2 Heapify and build-heap
- 19.3 PriorityQueue in Java
- 19.4 Heap sort
- 19.5 Top K and streaming problems
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 20: Trie
20: Trie
Goal: Teach learners how tries store strings by shared prefixes, how to implement insert, search, prefix lookup, and deletion in Java, and when a trie is better than scanning a dictionary.
Outcome: By the end of this chapter, you can design trie nodes, implement insert and search operations, support prefix queries, reason about deletion and memory trade-offs, and solve dictionary and autocomplete-style problems using tries.
1. Intuition First
Tries matter because some string problems are not really about whole-word equality. They are about shared prefixes. If many words begin the same way, a trie stores that common path once instead of repeating it in every comparison.
A simple real-world analogy is a folder tree for words. All words starting with app share the same first three folders before branching into apple, apply, or application.
The core mental model is this: each edge represents one character, and walking from the root to a marked node spells a word. Prefixes correspond to paths, so prefix lookup becomes a path-existence question.
The most common beginner confusion point is thinking trie nodes store whole words. Most trie nodes store only the next-character links plus a flag marking whether the path up to that node completes a word.
In the roadmap, this chapter closes the early ordered-structure section by moving from numeric order and heap priority to string prefix structure.
2. Core Concepts and Techniques
Concept Cluster: Trie Structure, Node Design, Insert, Search, and Prefix Search
Key concepts in this block:
- 20.1 Trie structure and node design
- 20.2 Insert and search operations
- 20.3 Prefix search
Intuition
A trie groups words by shared starting characters.
Why It Matters
Exact search and prefix search become proportional to the word length rather than the number of stored words.
How It Works
- start at the root
- for each character, move to the matching child node, creating it if insertion requires
- after the last character, mark the node as a complete word
- exact search succeeds only if the full path exists and the last node is marked as a word
- prefix search succeeds if the full prefix path exists, even if the last node is not a complete word
Java Implementation Notes
- For lowercase English letters,
TrieNode[] children = new TrieNode[26]is simple and fast. - For larger alphabets or sparse branching, a
Map<Character, TrieNode>may save memory at the cost of some overhead. - Keep exact-word and prefix logic separate through an
isWordflag.
Common Mistakes
- treating a prefix path as proof of a full stored word
- forgetting to mark the end of a word
- using whole-word strings at each node and losing the point of the structure
Quick Example
class TrieQuickExample {
static final class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
static final class Trie {
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
current.children[childIndex] = new TrieNode();
}
current = current.children[childIndex];
}
current.isWord = true;
}
}
}
Debugging Tip
When a search unexpectedly fails, trace the path character by character and check whether the issue is a missing child or a missing isWord mark.
Advanced Note
Trie performance depends on word length, not dictionary size, which is why it can outperform repeated full-word scans for heavy prefix workloads.
Concept Cluster: Delete and Memory Considerations
Key concepts in this block:
- 20.4 Delete and memory considerations
Intuition
Deleting from a trie is not just unmarking a word. You may also want to prune nodes that are no longer needed by any other word.
Why It Matters
Tries trade memory for fast prefix operations, so understanding when nodes can be reclaimed matters.
How It Works
- find the word path recursively or iteratively
- unmark the final node's
isWordflag - remove child references only if the child subtree no longer represents any other word
- shared prefix nodes must remain if another word still depends on them
Java Implementation Notes
- Recursive delete is often the clearest because it can decide on pruning while returning upward.
- Arrays are faster but can waste memory on sparse alphabets.
- Maps reduce wasted space when branching is sparse but add object overhead and hashing costs.
Common Mistakes
- deleting shared prefix nodes too aggressively
- unmarking the wrong node
- forgetting that removing a word should not remove a longer word with the same prefix
Quick Example
class TrieDeleteQuickNotes {
static boolean hasChildren(TrieQuickExample.TrieNode node) {
for (TrieQuickExample.TrieNode child : node.children) {
if (child != null) {
return true;
}
}
return false;
}
}
Debugging Tip
When debugging delete, test pairs like app and apple. Those cases expose shared-prefix pruning mistakes immediately.
Advanced Note
Memory optimization becomes more important with large dictionaries or wide alphabets, where compressed trie variants may later become relevant.
Concept Cluster: Dictionary and Autocomplete Problems
Key concepts in this block:
- 20.5 Dictionary and autocomplete problems
Intuition
A trie is a natural dictionary where you can stop at a prefix node and explore all completions below it.
Why It Matters
Autocomplete, spell-prefix matching, and dictionary lookup are the most recognizable trie applications.
How It Works
- insert all dictionary words
- walk the prefix path
- if the prefix exists, DFS from that node to collect completions
- exact-word dictionary checks only need path lookup plus
isWord
Java Implementation Notes
- DFS from the prefix node can build suggestions into a list.
- Add limits when only the first few suggestions are needed.
- Sorting requirements for autocomplete depend on the problem statement, not on the trie itself.
Common Mistakes
- scanning all dictionary words even after building a trie
- forgetting to include the prefix node itself when it marks a full word
- not stopping DFS when a suggestion limit has already been reached
Quick Example
import java.util.ArrayList;
import java.util.List;
class AutocompleteQuickExample {
static void collectWords(TrieQuickExample.TrieNode node, StringBuilder path, List<String> result) {
if (node.isWord) {
result.add(path.toString());
}
for (int childIndex = 0; childIndex < 26; childIndex++) {
TrieQuickExample.TrieNode child = node.children[childIndex];
if (child != null) {
path.append((char) ('a' + childIndex));
collectWords(child, path, result);
path.deleteCharAt(path.length() - 1);
}
}
}
}
Debugging Tip
If autocomplete returns wrong words, separate prefix navigation from suffix collection and test them independently.
Advanced Note
Autocomplete quality in real systems also depends on ranking, not just prefix matching, but trie structure is still a common retrieval backbone.
3. Worked Examples and Full Solutions
Worked Example 1: Implement Trie with Insert, Search, and startsWith
Problem Statement
Design a trie that supports insert, search, and startsWith for lowercase English words.
Why This Example Matters
It covers the core trie contract and establishes the difference between full-word and prefix queries.
Constraints or Assumptions
- words contain only lowercase English letters
- empty string behavior should be defined consistently
- exact search and prefix search are different operations
Brute-Force Approach
Store all words in a list. For search, scan for exact equality. For startsWith, scan all words until one matches the prefix.
Better Approach
Use a trie with one node per prefix state.
Why the Better Approach Works
All words sharing the same prefix reuse the same path. Both exact search and prefix search become path-walk operations proportional to the query length.
Pragmatic Java Choice
Use a fixed array of size 26 in each node because the alphabet is known and small.
Java Solution
import java.util.ArrayList;
import java.util.List;
class TrieBasicsExample {
static final class NaiveDictionary {
private final List<String> words = new ArrayList<>();
void insert(String word) {
words.add(word);
}
boolean search(String target) {
for (String word : words) {
if (word.equals(target)) {
return true;
}
}
return false;
}
boolean startsWith(String prefix) {
for (String word : words) {
if (word.startsWith(prefix)) {
return true;
}
}
return false;
}
}
static final class Trie {
static final class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
current.children[childIndex] = new TrieNode();
}
current = current.children[childIndex];
}
current.isWord = true;
}
boolean search(String word) {
TrieNode node = findNode(word);
return node != null && node.isWord;
}
boolean startsWith(String prefix) {
return findNode(prefix) != null;
}
private TrieNode findNode(String text) {
TrieNode current = root;
for (int index = 0; index < text.length(); index++) {
int childIndex = text.charAt(index) - 'a';
if (current.children[childIndex] == null) {
return null;
}
current = current.children[childIndex];
}
return current;
}
}
}
Dry Run
Insert app and apple.
- root gets child
a agets childp- first
pgets secondp - mark the second
pnode as a full word forapp - continue to create
landeforapple
Now:
search("app")is true because the node is marked as a wordstartsWith("app")is also truesearch("appl")is false because the path exists but the node is not marked as a full word
Time and Space Complexity
- Brute force:
searchandstartsWithcan takeO(number of words * word length)in the worst case - Better approach:
O(length of word or prefix)time per query, space proportional to total created trie nodes
Edge Cases
- searching for a word never inserted
- prefix exists but full word does not
- inserting the same word multiple times under the same rules
Common Mistakes
- forgetting the
isWordflag - returning true for exact search when only the prefix exists
- not defining the allowed alphabet clearly
Worked Example 2: Autocomplete Suggestions for a Prefix
Problem Statement
Given a dictionary of lowercase words and a prefix, return all dictionary words that start with that prefix.
Why This Example Matters
It shows the trie's main real-world strength: once you reach the prefix node, the remaining work is limited to matching completions.
Constraints or Assumptions
- words are lowercase English letters
- suggestion order may be lexicographic if children are explored from
atoz - return an empty list if the prefix is absent
Brute-Force Approach
Scan every word in the dictionary and keep only those that start with the prefix.
Better Approach
Walk the prefix in the trie, then DFS from the prefix node to collect completions.
Why the Better Approach Works
The trie avoids inspecting unrelated words because only the subtree under the prefix node can produce valid suggestions.
Pragmatic Java Choice
Use DFS with a mutable StringBuilder so suffix construction stays efficient.
Java Solution
import java.util.ArrayList;
import java.util.List;
class AutocompleteExample {
static List<String> autocompleteNaive(List<String> dictionary, String prefix) {
List<String> result = new ArrayList<>();
for (String word : dictionary) {
if (word.startsWith(prefix)) {
result.add(word);
}
}
return result;
}
static final class Trie {
static final class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
current.children[childIndex] = new TrieNode();
}
current = current.children[childIndex];
}
current.isWord = true;
}
List<String> autocomplete(String prefix) {
TrieNode start = findNode(prefix);
List<String> result = new ArrayList<>();
if (start == null) {
return result;
}
collect(start, new StringBuilder(prefix), result);
return result;
}
private TrieNode findNode(String text) {
TrieNode current = root;
for (int index = 0; index < text.length(); index++) {
int childIndex = text.charAt(index) - 'a';
if (current.children[childIndex] == null) {
return null;
}
current = current.children[childIndex];
}
return current;
}
private void collect(TrieNode node, StringBuilder path, List<String> result) {
if (node.isWord) {
result.add(path.toString());
}
for (int childIndex = 0; childIndex < 26; childIndex++) {
TrieNode child = node.children[childIndex];
if (child != null) {
path.append((char) ('a' + childIndex));
collect(child, path, result);
path.deleteCharAt(path.length() - 1);
}
}
}
}
}
Dry Run
Dictionary: app, apple, apply, bat, batch. Prefix: app.
- walk
a -> p -> p - reach the prefix node for
app - DFS from that node
- include
appbecause the prefix node is a complete word - continue to
appleandapply - words under
batare never explored
Time and Space Complexity
- Brute force:
O(number of words * prefix length)plus result construction - Better approach:
O(prefix length + total size of returned suffix subtree)time, plus output space
Edge Cases
- missing prefix returns empty list
- prefix itself may already be a full word
- very large suggestion sets may need an output limit in real systems
Common Mistakes
- forgetting to include the prefix when it is also a valid word
- scanning the full dictionary even after building the trie
- mutating the path without undoing the last character after DFS returns
Worked Example 3: Delete a Word from a Trie Safely
Problem Statement
Given a trie and a word, delete the word while preserving all other stored words.
Why This Example Matters
It exposes the main structural risk in tries: shared prefixes must survive deletion of one word.
Constraints or Assumptions
- words are lowercase English letters
- deleting a missing word should leave the trie unchanged
- unused nodes should be pruned when possible
Brute-Force Approach
Store all dictionary words separately, remove the target word from that list, and rebuild the entire trie from scratch.
Better Approach
Use recursive deletion that unmarks the target word and prunes nodes only when they no longer represent any word or shared prefix.
Why the Better Approach Works
The recursive return tells the parent whether a child subtree has become unnecessary. Shared nodes stay alive because they still have children or still mark another word.
Pragmatic Java Choice
Use a recursive helper that returns whether the current node can be deleted from its parent.
Java Solution
class TrieDeleteExample {
static final class Trie {
static final class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
private final TrieNode root = new TrieNode();
void insert(String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
current.children[childIndex] = new TrieNode();
}
current = current.children[childIndex];
}
current.isWord = true;
}
void delete(String word) {
delete(root, word, 0);
}
boolean search(String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
return false;
}
current = current.children[childIndex];
}
return current.isWord;
}
private boolean delete(TrieNode node, String word, int index) {
if (index == word.length()) {
if (!node.isWord) {
return false;
}
node.isWord = false;
return hasNoChildren(node);
}
int childIndex = word.charAt(index) - 'a';
TrieNode child = node.children[childIndex];
if (child == null) {
return false;
}
boolean shouldDeleteChild = delete(child, word, index + 1);
if (shouldDeleteChild) {
node.children[childIndex] = null;
}
return !node.isWord && hasNoChildren(node);
}
private boolean hasNoChildren(TrieNode node) {
for (TrieNode child : node.children) {
if (child != null) {
return false;
}
}
return true;
}
}
}
Dry Run
Insert app and apple, then delete app.
- follow the path
a -> p -> p - unmark the
appnode as a full word - that node still has child
lforapple, so it must not be deleted search("app")becomes falsesearch("apple")stays true
Time and Space Complexity
- Brute force: rebuilding can cost
O(total dictionary characters)after each deletion - Better approach:
O(length of word)time,O(length of word)call stack space
Edge Cases
- deleting a missing word
- deleting a word that is also a prefix of another word
- deleting the only stored word
Common Mistakes
- pruning shared prefix nodes too early
- unmarking the wrong node
- failing to distinguish exact words from prefixes during delete
4. Complexity and Decision Guide
Main runtime and space trade-offs in this chapter:
- trie operations run in time proportional to word or prefix length, which can be much better than scanning many dictionary entries
- tries use more memory than plain lists or sets because every stored character may create nodes and child references
- array-based child storage is fast for fixed alphabets but can waste memory on sparse branching
- delete and autocomplete logic benefit from trie structure but require careful handling of shared prefixes and output size
Choose a trie when:
- prefix queries are frequent
- many words share common prefixes
- query speed by word length matters more than memory cost
Choose a set or list instead when:
- only exact lookup is needed
- the dictionary is small
- memory simplicity matters more than prefix speed
Recognition signals for tries:
- autocomplete
- dictionary prefix matching
- word search with many repeated prefixes
Signals not to force tries:
- no prefix behavior is needed
- the alphabet is huge and sparse while the dataset is small
- a hash-based exact lookup is enough
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- forgetting the
isWordmarker - treating prefixes as full words
- deleting shared nodes too aggressively
- miscomputing child indexes from characters
Boundary and memory risks:
- empty string behavior
- unsupported characters outside the chosen alphabet
- large memory use for sparse tries
- autocomplete returning too many results without a limit
Short debugging checklist:
- Does exact search check both the path and
isWord? - Does prefix search only need the path?
- During delete, which nodes are shared by other words?
- Is the child index calculation correct for the chosen alphabet?
- Would a map-based node design be more appropriate for this input space?
6. Practice Problems
Easy
- Title: Implement Trie (Prefix Tree)
- One-line prompt: Support insert, exact search, and prefix search.
- Expected pattern or core idea: Trie path traversal with
isWordflags.
- Title: Longest Common Prefix
- One-line prompt: Find the longest shared prefix among strings.
- Expected pattern or core idea: Prefix path reasoning or trie construction.
- Title: Design Add and Search Words Data Structure
- One-line prompt: Support adding words and searching with wildcard dots.
- Expected pattern or core idea: Trie plus DFS branching.
Medium
- Title: Search Suggestions System
- One-line prompt: Return product suggestions for each typed prefix.
- Expected pattern or core idea: Trie-guided autocomplete.
- Title: Replace Words
- One-line prompt: Replace sentence words with shortest matching dictionary roots.
- Expected pattern or core idea: Prefix trie lookup.
- Title: Map Sum Pairs
- One-line prompt: Support prefix-sum queries on string keys.
- Expected pattern or core idea: Trie with aggregated values.
Hard
- Title: Word Search II
- One-line prompt: Find all dictionary words present in a character board.
- Expected pattern or core idea: Trie plus DFS backtracking.
- Title: Palindrome Pairs
- One-line prompt: Find index pairs whose concatenation forms a palindrome.
- Expected pattern or core idea: Trie or reverse-string prefix reasoning.
- Title: Stream of Characters
- One-line prompt: Query whether the recent character stream ends with any dictionary word.
- Expected pattern or core idea: Trie over reversed words.
7. Short Recap
The core idea of this chapter is that tries trade memory for fast exact and prefix-based string lookup by storing shared prefixes once.
The most important optimization insight is that after you reach the prefix node, unrelated words disappear from consideration entirely.
The most important implementation warning is to separate full-word logic from prefix logic and to delete only nodes that are truly no longer shared.
This chapter prepares the next chapter by shifting from prefix lookup on strings to range-query structures that organize numeric intervals instead of characters.
8. Coverage Check
- 20.1 Trie structure and node design
- 20.2 Insert and search operations
- 20.3 Prefix search
- 20.4 Delete and memory considerations
- 20.5 Dictionary and autocomplete problems
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 21: Segment Tree and Fenwick Tree
21: Segment Tree and Fenwick Tree
Goal: Teach how to answer range queries efficiently when arrays change over time, and how to choose between segment trees and Fenwick trees in Java.
Outcome: By the end of this chapter, you can explain why range-query data structures matter, build and query a segment tree, handle point and range updates with lazy propagation, implement a Fenwick tree, and choose the right structure for the constraints in front of you.
1. Intuition First
Range-query structures matter because many problems ask the same pattern repeatedly: "What is the sum, minimum, maximum, or frequency over this interval?" If the array never changes, prefix sums often solve the problem. If updates are mixed with queries, recomputing the answer from scratch becomes too slow.
A simple real-world analogy is a spreadsheet with thousands of rows. If one value changes and you still need fast totals for many row ranges, scanning those rows again and again wastes work. A range-query structure stores partial summaries so you reuse previous computation.
The core mental model is this:
- a segment tree stores answers for nested intervals
- a Fenwick tree stores carefully chosen partial prefix sums
- both trade extra memory for much faster repeated queries and updates
The most common beginner confusion point is thinking prefix sums already solve everything. Prefix sums are excellent for static arrays, but once values change often, the old prefix data becomes stale.
In the roadmap, this chapter is the final step in Part IV. You already know trees as hierarchical structures. Here, that tree idea becomes an interval tool. The next chapter shifts from ordered intervals to graph modeling.
2. Core Concepts and Techniques
Concept Cluster: Why Range Structures Exist
Key concepts in this block:
- 21.1 Why range-query structures matter
- 21.2 Segment tree build and query
Intuition
If every query scans part of the array, repeated range queries become expensive. A segment tree avoids that by storing answers for subranges once and reusing them.
Why It Matters
Problems with many queries often have constraints where $O(n)$ per query is too slow. If $n = 10^5$ and there are $10^5$ queries, a full scan per query is not realistic.
How It Works
A segment tree recursively splits the array into halves.
- each leaf stores one array value
- each internal node stores a merged answer for its interval
- for sums, the merge is addition
- for minimum queries, the merge is
min - a query visits only nodes whose intervals overlap the requested range
Build works bottom-up:
- split interval
[left, right]into two halves - build children
- merge child answers into the parent
Query works by overlap cases:
- no overlap: return the neutral value
- full overlap: return the node's stored answer
- partial overlap: query both children and merge
Java Implementation Notes
- A common implementation uses arrays such as
long[] tree = new long[4 * n]. - Store intervals as inclusive bounds.
- Use
longfor sums when values or counts can exceedint. - Keep the merge operation explicit so the structure is easier to adapt.
Common Mistakes
- mixing array indices with tree node indices
- getting the overlap conditions wrong
- forgetting that the query range is inclusive
- using
intsums when overflow is possible
Quick Example
For the array [2, 1, 5, 3]:
- the root stores the answer for
[0, 3], which is11 - the left child stores
[0, 1], which is3 - the right child stores
[2, 3], which is8
A query for [1, 2] does not scan all four positions. It visits only the branches that overlap [1, 2].
Debugging Tip
Log (node, left, right, tree[node]) during build and query. Most bugs become obvious when the interval boundaries are visible.
Advanced Note
A segment tree works when the merge operation is associative. Sum, minimum, maximum, and gcd all fit naturally.
Concept Cluster: Updates and Deferred Work
Key concepts in this block:
- 21.3 Point updates and range updates
- 21.4 Lazy propagation
Intuition
Once the tree stores interval answers, an update must keep those stored answers correct. Point updates affect one leaf and its ancestors. Range updates may affect many leaves, which is where lazy propagation matters.
Why It Matters
If a problem mixes many updates and many queries, a good query structure is not enough. Update speed matters just as much.
How It Works
For a point update:
- go from root to the target leaf
- change the leaf value
- recompute all ancestors on the way back
For a range update without lazy propagation:
- descend into every affected leaf
- recompute many nodes
- this can become too expensive
Lazy propagation stores pending work at a node instead of pushing it immediately to all descendants.
- if a node interval is fully covered by the update, apply the effect to that node
- store a lazy tag saying "children still need this update later"
- push that tag downward only when a future query or update needs to inspect the children
Java Implementation Notes
- Keep separate arrays such as
tree[]andlazy[]. - For range sums, updating a whole interval by
deltachanges the node value bydelta * intervalLength. - Push lazy values before descending into children during partial-overlap operations.
Common Mistakes
- forgetting to multiply by interval length for sum queries
- not pushing lazy values before going deeper
- clearing the lazy value too early or too late
- assuming the same lazy logic works unchanged for every kind of update
Quick Example
Suppose the array is [4, 0, 2, 1] and you add 3 to [1, 3].
- brute force changes three positions directly
- lazy propagation can mark a fully covered segment and postpone child updates until needed
Debugging Tip
After each update, inspect both tree and lazy. If the root answer is correct but later queries fail, the bug is often in pushing tags to children.
Advanced Note
Range assignment, range add, and range minimum updates do not all use the same lazy logic. The tag meaning must match the operation.
Concept Cluster: Fenwick Tree and Choosing the Right Tool
Key concepts in this block:
- 21.5 Fenwick tree basics
- 21.6 Segment tree vs binary indexed tree
Intuition
A Fenwick tree, also called a binary indexed tree, stores partial prefix sums in a compact structure. Each index is responsible for a block whose size comes from its least significant set bit.
Why It Matters
For prefix sums, range sums, and frequency counting with point updates, a Fenwick tree is often simpler and smaller than a segment tree.
How It Works
Fenwick tree rules:
- internal storage is usually 1-indexed
- update adds
deltaat one position and climbs upward withindex += index & -index - prefix sum moves downward with
index -= index & -index - range sum
[left, right]equalsprefix(right) - prefix(left - 1)
Comparison:
- Fenwick tree is compact and fast for sum-like prefix logic
- segment tree is more general and handles more query and update types
Java Implementation Notes
- Keep a 0-indexed public API and translate internally to 1-indexed storage.
- Track current values if the API asks for "set index to newValue" rather than "add delta".
- Fenwick trees are especially natural for frequency arrays and coordinate-compressed counting problems.
Common Mistakes
- mixing 0-indexed external positions with 1-indexed internal positions
- updating with the new value instead of the delta
- expecting a basic Fenwick tree to support arbitrary range updates and arbitrary range queries without extra techniques
Quick Example
In a 1-indexed Fenwick tree:
- index
6has lowbit2 - so
tree[6]stores the sum for a block of length2 - that block ends at
6, so it covers indices5and6
Debugging Tip
Write down the exact indices touched by an update and a prefix query. If the index jumps look wrong, the lowbit logic is wrong.
Advanced Note
Fenwick trees usually win on simplicity and constants for sums. Segment trees win on flexibility.
3. Worked Examples and Full Solutions
Worked Example 1: Range Sum Query with Point Updates
Problem Statement
Design a structure over an integer array that supports:
- updating one index to a new value
- querying the sum of any inclusive range
[left, right]
Why This Example Matters
This is the basic segment tree use case. It covers build, query, and point update in one clean problem.
Constraints or Assumptions
- the array size can be large
- there can be many mixed updates and queries
- sums may exceed
int, solongis safer
Brute-Force Approach
Use a plain array.
- point update is easy: write the new value in $O(1)$
- range sum query scans from
lefttorightin $O(right - left + 1)$
This is acceptable when queries are few or ranges are tiny.
Better Approach
Use a segment tree where each node stores the sum of its interval.
Why the Better Approach Works
A range query visits only the branches that overlap the requested interval. A point update changes one leaf and recomputes only the ancestors on that root-to-leaf path.
Pragmatic Java Choice
Use:
- an array-backed segment tree
- inclusive interval bounds
- a copied
values[]array to compute update deltas safely
Java Solution
import java.util.Arrays;
class SegmentTreeRangeSumExample {
static final class SegmentTree {
private final int size;
private final long[] tree;
private final int[] values;
SegmentTree(int[] numbers) {
this.size = numbers.length;
this.tree = new long[Math.max(1, 4 * size)];
this.values = Arrays.copyOf(numbers, numbers.length);
if (size > 0) {
build(1, 0, size - 1);
}
}
private void build(int node, int left, int right) {
if (left == right) {
tree[node] = values[left];
return;
}
int mid = left + (right - left) / 2;
build(node * 2, left, mid);
build(node * 2 + 1, mid + 1, right);
tree[node] = tree[node * 2] + tree[node * 2 + 1];
}
long sumRange(int queryLeft, int queryRight) {
if (size == 0 || queryLeft > queryRight) {
return 0;
}
return sumRange(1, 0, size - 1, queryLeft, queryRight);
}
private long sumRange(int node, int left, int right, int queryLeft, int queryRight) {
if (queryRight < left || right < queryLeft) {
return 0;
}
if (queryLeft <= left && right <= queryRight) {
return tree[node];
}
int mid = left + (right - left) / 2;
return sumRange(node * 2, left, mid, queryLeft, queryRight)
+ sumRange(node * 2 + 1, mid + 1, right, queryLeft, queryRight);
}
void update(int index, int newValue) {
if (size == 0) {
return;
}
long delta = newValue - values[index];
values[index] = newValue;
update(1, 0, size - 1, index, delta);
}
private void update(int node, int left, int right, int index, long delta) {
if (index < left || index > right) {
return;
}
tree[node] += delta;
if (left == right) {
return;
}
int mid = left + (right - left) / 2;
update(node * 2, left, mid, index, delta);
update(node * 2 + 1, mid + 1, right, index, delta);
}
}
}
Dry Run
Array: [2, 4, 1, 7, 3]
Query sumRange(1, 3):
- total scan would compute
4 + 1 + 7 - the segment tree visits only overlapping nodes
- answer is
12
Update index 2 to 6:
- old value was
1, sodelta = 5 - update the leaf for index
2 - add
5to each ancestor on the path to the root
Now sumRange(1, 3) becomes 4 + 6 + 7 = 17.
Time and Space Complexity
- brute force: update $O(1)$, query $O(n)$ in the worst case
- segment tree: build $O(n)$, update $O(\log n)$, query $O(\log n)$
- extra space: $O(n)$
Edge Cases
- empty array
- single-element range
- updating the same index many times
- large sums that overflow
int
Common Mistakes
- forgetting that the query is inclusive
- returning the wrong neutral value on no-overlap
- recomputing with stale original values during updates
Worked Example 2: Range Add Updates with Range Sum Queries
Problem Statement
Design a structure that supports:
- adding
deltato every element in[left, right] - querying the sum of any inclusive range
[left, right]
Why This Example Matters
This is the point where plain segment trees become insufficiently efficient for repeated range updates. Lazy propagation is the key new idea.
Constraints or Assumptions
- many updates and queries are interleaved
- values may become large, so use
long - intervals are inclusive
Brute-Force Approach
Use a plain array.
- for update
[left, right], loop through every affected index and adddelta - for query
[left, right], loop through the same interval and sum values
This can become $O(n)$ for both update and query.
Better Approach
Use a segment tree with lazy propagation.
Why the Better Approach Works
A fully covered segment can be updated in one step:
- change the node's sum immediately
- store a pending lazy value for children
- delay the child work until a later partial query or update actually needs those children
Pragmatic Java Choice
Use:
tree[]for interval sumslazy[]for pending increments- helper methods
applyandpushDownto keep the logic local and readable
Java Solution
class LazyPropagationRangeSumExample {
static final class LazySegmentTree {
private final int size;
private final long[] tree;
private final long[] lazy;
LazySegmentTree(int[] numbers) {
this.size = numbers.length;
this.tree = new long[Math.max(1, 4 * size)];
this.lazy = new long[Math.max(1, 4 * size)];
if (size > 0) {
build(1, 0, size - 1, numbers);
}
}
private void build(int node, int left, int right, int[] numbers) {
if (left == right) {
tree[node] = numbers[left];
return;
}
int mid = left + (right - left) / 2;
build(node * 2, left, mid, numbers);
build(node * 2 + 1, mid + 1, right, numbers);
tree[node] = tree[node * 2] + tree[node * 2 + 1];
}
void rangeAdd(int updateLeft, int updateRight, long delta) {
if (size == 0 || updateLeft > updateRight) {
return;
}
rangeAdd(1, 0, size - 1, updateLeft, updateRight, delta);
}
private void rangeAdd(int node, int left, int right, int updateLeft, int updateRight, long delta) {
if (updateRight < left || right < updateLeft) {
return;
}
if (updateLeft <= left && right <= updateRight) {
apply(node, left, right, delta);
return;
}
pushDown(node, left, right);
int mid = left + (right - left) / 2;
rangeAdd(node * 2, left, mid, updateLeft, updateRight, delta);
rangeAdd(node * 2 + 1, mid + 1, right, updateLeft, updateRight, delta);
tree[node] = tree[node * 2] + tree[node * 2 + 1];
}
long rangeSum(int queryLeft, int queryRight) {
if (size == 0 || queryLeft > queryRight) {
return 0;
}
return rangeSum(1, 0, size - 1, queryLeft, queryRight);
}
private long rangeSum(int node, int left, int right, int queryLeft, int queryRight) {
if (queryRight < left || right < queryLeft) {
return 0;
}
if (queryLeft <= left && right <= queryRight) {
return tree[node];
}
pushDown(node, left, right);
int mid = left + (right - left) / 2;
return rangeSum(node * 2, left, mid, queryLeft, queryRight)
+ rangeSum(node * 2 + 1, mid + 1, right, queryLeft, queryRight);
}
private void apply(int node, int left, int right, long delta) {
tree[node] += delta * (right - left + 1L);
lazy[node] += delta;
}
private void pushDown(int node, int left, int right) {
if (lazy[node] == 0 || left == right) {
return;
}
int mid = left + (right - left) / 2;
apply(node * 2, left, mid, lazy[node]);
apply(node * 2 + 1, mid + 1, right, lazy[node]);
lazy[node] = 0;
}
}
}
Dry Run
Array: [5, 2, 1, 4, 3]
Update rangeAdd(1, 3, 2):
- brute force would change the array to
[5, 4, 3, 6, 3] - lazy propagation updates covered segments and stores pending tags instead of touching every descendant immediately
Query rangeSum(2, 4):
- the answer should be
3 + 6 + 3 = 12 - if the query reaches a node with a pending tag, that tag is pushed before exploring children
Time and Space Complexity
- brute force: update $O(n)$, query $O(n)$ in the worst case
- lazy segment tree: update $O(\log n)$, query $O(\log n)$
- extra space: $O(n)$
Edge Cases
- update range of length one
- update the full array
- many overlapping updates before a query
- negative
delta
Common Mistakes
- forgetting
segmentLengthin sum updates - not pushing lazy values before partial recursion
- assuming the parent sum stays correct after child recursion without recomputing it
Worked Example 3: Dynamic Prefix and Range Sums with a Fenwick Tree
Problem Statement
Design a structure that supports:
- setting one index to a new value
- returning prefix sums and arbitrary range sums
Why This Example Matters
A Fenwick tree is often the simplest correct answer when the operation is sum-like and the updates are point updates.
Constraints or Assumptions
- range sum can be reduced to prefix sums
- point updates are frequent
- the tree is internally 1-indexed
Brute-Force Approach
Two common baselines exist:
- use a plain array and scan for every prefix or range sum
- use prefix sums and rebuild them after each update
Both are simple, but the second one still makes updates expensive.
Better Approach
Use a Fenwick tree.
Why the Better Approach Works
Each Fenwick tree cell stores the sum of a carefully chosen suffix of a prefix. That lets updates and prefix queries jump across blocks instead of touching every element.
Pragmatic Java Choice
Use:
- a public 0-indexed API
- an internal 1-indexed
tree[] - a
values[]array so "set index to newValue" can be translated into an added delta
Java Solution
class FenwickTreeRangeSumExample {
static final class FenwickTree {
private final long[] tree;
private final long[] values;
FenwickTree(int[] numbers) {
this.tree = new long[numbers.length + 1];
this.values = new long[numbers.length];
for (int index = 0; index < numbers.length; index++) {
set(index, numbers[index]);
}
}
void set(int index, long newValue) {
long delta = newValue - values[index];
values[index] = newValue;
addDelta(index, delta);
}
long prefixSum(int index) {
long sum = 0;
int oneBasedIndex = index + 1;
while (oneBasedIndex > 0) {
sum += tree[oneBasedIndex];
oneBasedIndex -= oneBasedIndex & -oneBasedIndex;
}
return sum;
}
long rangeSum(int left, int right) {
if (left > right) {
return 0;
}
return prefixSum(right) - (left == 0 ? 0 : prefixSum(left - 1));
}
private void addDelta(int index, long delta) {
int oneBasedIndex = index + 1;
while (oneBasedIndex < tree.length) {
tree[oneBasedIndex] += delta;
oneBasedIndex += oneBasedIndex & -oneBasedIndex;
}
}
}
}
Dry Run
Array: [3, 1, 4, 1, 5]
Build:
set(0, 3)touches internal indices1, 2, 4set(2, 4)touches internal indices3, 4- each update adds its delta to the responsible blocks
Query rangeSum(1, 3):
- compute
prefixSum(3) - prefixSum(0) - result is
1 + 4 + 1 = 6
Update set(2, 6):
- old value at index
2is4 - delta is
2 - add
2to the internal blocks that cover index2
Time and Space Complexity
- brute force array scan: update $O(1)$, query $O(n)$
- rebuilt prefix sums: update $O(n)$, query $O(1)$
- Fenwick tree: update $O(\log n)$, prefix sum $O(\log n)$, range sum $O(\log n)$
- extra space: $O(n)$
Edge Cases
- querying a range of length one
- querying from index
0 - setting a value to the same number
- negative values
Common Mistakes
- forgetting the internal 1-index shift
- using
newValuedirectly instead of the delta - expecting a basic Fenwick tree to answer minimum queries or arbitrary lazy range updates
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- plain scan: simplest code, but repeated range queries are expensive
- prefix sums: excellent for static arrays, weak for frequent updates
- segment tree: flexible and supports many aggregates with $O(\log n)$ queries and updates
- lazy segment tree: the right choice when full interval updates must also stay fast
- Fenwick tree: compact and practical for prefix sums, range sums, and frequency counting
Choose brute force when:
- the array is small
- there are very few operations
- implementation time matters more than asymptotic performance
Choose prefix sums when:
- the array is static
- the query is sum-like
- updates do not happen after preprocessing
Choose a Fenwick tree when:
- you need point updates and prefix or range sums
- you want simpler code and lower constants
- the operation naturally reduces to prefix sums
Choose a segment tree when:
- you need min, max, gcd, or another associative aggregate
- you need more flexible query shapes
- range updates are part of the problem
Choose lazy propagation when:
- many updates touch full intervals
- pushing every update to leaves would be too expensive
Recognition signals:
- many queries over subarrays
- many updates mixed with queries
- constraints where $O(n)$ per operation is too slow
Signals not to force this technique:
- only one or two queries exist
- the array never changes and prefix sums are enough
- the real problem is not about intervals at all
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- off-by-one errors in inclusive ranges
- wrong no-overlap or full-overlap conditions
- stale values during point updates
- forgetting to multiply lazy updates by interval length for sums
- mixing 0-indexed public inputs with 1-indexed Fenwick internals
Boundary risks:
- empty arrays
- single-element segments
- negative updates
- integer overflow on large sums
Mutation risks:
- not recomputing parent values after child updates
- pushing lazy tags only in one code path but not another
- setting a Fenwick value without converting to delta first
Short debugging checklist:
- Does every tree node really represent the interval you think it does?
- For a no-overlap query, are you returning the correct neutral value?
- After a point update, are all ancestors updated?
- Before descending in a lazy tree, are pending tags pushed?
- In a Fenwick tree, which internal indices should a given update touch?
- Are you using
longwhere sums can grow large?
6. Practice Problems
Easy
- Title: Range Sum Query - Immutable. One-line prompt: answer many range sum queries on a fixed array. Expected pattern or core idea: prefix sums as the static baseline before dynamic structures.
- Title: Range Sum Query - Mutable. One-line prompt: support point updates and range sum queries. Expected pattern or core idea: segment tree or Fenwick tree.
- Title: Prefix Frequency Tracker. One-line prompt: maintain counts of values and answer prefix-frequency totals after updates. Expected pattern or core idea: Fenwick tree over frequencies.
Medium
- Title: Range Addition. One-line prompt: apply many interval increments and inspect final values or sums. Expected pattern or core idea: difference array baseline, then lazy propagation when updates and queries interleave.
- Title: Count of Smaller Numbers After Self. One-line prompt: for each element, count how many smaller values appear to its right. Expected pattern or core idea: Fenwick tree with coordinate compression.
- Title: Dynamic Booking Load. One-line prompt: support interval additions and query the total load on a range. Expected pattern or core idea: lazy segment tree.
Hard
- Title: Falling Squares. One-line prompt: place interval-based blocks and track the maximum height after each insertion. Expected pattern or core idea: segment tree with coordinate compression.
- Title: Reverse Pairs. One-line prompt: count pairs satisfying an inequality across positions in the array. Expected pattern or core idea: Fenwick tree or segment tree with compressed values.
- Title: Interval Maximum with Massive Coordinates. One-line prompt: process many interval updates and maximum queries over sparse coordinates. Expected pattern or core idea: segment tree plus coordinate compression.
7. Short Recap
The core idea of this chapter is that range-query structures store partial answers so you do not recompute whole intervals from scratch.
The most important optimization insight is that the right structure depends on the update pattern:
- static array: prefix sums
- point updates plus sums: Fenwick tree or segment tree
- range updates plus queries: lazy segment tree
The most important implementation warning is that interval boundaries and update propagation must stay consistent, especially with lazy tags and Fenwick indexing.
This chapter prepares the next chapter by shifting from interval relationships inside arrays to relationship modeling between nodes in graphs.
8. Coverage Check
- 21.1 Why range-query structures matter
- 21.2 Segment tree build and query
- 21.3 Point updates and range updates
- 21.4 Lazy propagation
- 21.5 Fenwick tree basics
- 21.6 Segment tree vs binary indexed tree
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 22: Graph Foundations
22: Graph Foundations
Goal: Teach how to think about graphs as models of relationships, choose a useful graph representation, and translate real problems into nodes and edges before applying algorithms.
Outcome: By the end of this chapter, you can define core graph terminology, build adjacency lists and adjacency matrices in Java, distinguish directed, undirected, and weighted graphs, and model real-world and interview problems as graphs without guessing.
1. Intuition First
Graphs matter because many problems are not about order in an array or shape in a tree. They are about relationships:
- cities connected by roads
- users connected by friendships
- courses connected by prerequisites
- states connected by allowed moves
A simple real-world analogy is a transit map. Stations are nodes. Tracks are edges. Once you see the map that way, later algorithms like BFS, DFS, shortest path, and topological ordering become natural.
The core mental model is this:
- nodes represent entities or states
- edges represent allowed relationships or moves
- graph algorithms answer questions about reachability, structure, cost, and dependency
The most common beginner confusion point is waiting for a problem statement to say the word "graph". Many graph problems never say it directly. You must notice that the problem is really about objects and connections.
In the roadmap, this chapter starts Part V. The goal is not heavy graph algorithms yet. The goal is correct modeling. Traversal comes next.
2. Core Concepts and Techniques
Concept Cluster: Basic Representation
Key concepts in this block:
- 22.1 Graph terminology
- 22.2 Adjacency list
- 22.3 Adjacency matrix
Intuition
A graph is a set of nodes and edges. The first practical decision is how to store those connections.
Why It Matters
Graph algorithms are only as clean as the representation underneath them. The same algorithm can feel easy or awkward depending on how the graph is stored.
How It Works
Important terminology:
- vertex or node: one entity in the graph
- edge: a connection between two nodes
- path: a sequence of connected edges
- cycle: a path that starts and ends at the same node without trivial repetition
- degree: number of incident edges in an undirected graph
- indegree and outdegree: number of incoming and outgoing edges in a directed graph
- connected component: a maximal connected region in an undirected graph
Two common representations:
- adjacency list: for each node, store its neighbors
- adjacency matrix: store whether edge
(u, v)exists in a 2D table
Java Implementation Notes
- Adjacency list is often
List<List<Integer>>. - Weighted adjacency list commonly uses
List<List<Edge>>. - Adjacency matrix can be
boolean[][],int[][], orLong[][]depending on the problem. - Sparse graphs usually prefer adjacency lists.
- Dense graphs or constant-time edge existence checks may prefer adjacency matrices.
Common Mistakes
- forgetting isolated nodes that have no edges
- storing undirected edges in only one direction
- using an adjacency matrix when
Vis large and memory becomes a problem
Quick Example
If the graph has edges (0, 1) and (0, 2):
- adjacency list for node
0is[1, 2] - adjacency matrix has
matrix[0][1] = trueandmatrix[0][2] = true
Debugging Tip
Before writing any algorithm, print the graph representation once. Many later bugs are actually construction bugs.
Advanced Note
Representation choice affects both runtime and how natural the later code feels. Good graph work starts before traversal.
Concept Cluster: Graph Types
Key concepts in this block:
- 22.4 Directed and undirected graphs
- 22.5 Weighted graphs
Intuition
Edges can have direction, weight, both, or neither. Those choices change what the graph means.
Why It Matters
The same pair (u, v) can represent:
- mutual friendship in an undirected graph
- one-way dependency in a directed graph
- travel cost or latency in a weighted graph
How It Works
Undirected graph:
- edge
(u, v)means the connection works both ways - store both
u -> vandv -> uin an adjacency list
Directed graph:
- edge
(u, v)means movement or dependency only fromutov - store one direction only unless the reverse edge also exists
Weighted graph:
- edges carry a number such as distance, cost, time, or probability
- the edge storage must keep both the destination and the weight
Java Implementation Notes
- For undirected adjacency lists, always add both directions in the builder.
- A small
Edgeclass is usually cleaner than parallel lists. - Use
longfor weights if costs may grow large.
Common Mistakes
- accidentally treating a directed problem as undirected
- duplicating weights incorrectly in undirected graphs
- losing the meaning of the weight when naming fields too vaguely
Quick Example
Flights are usually directed and weighted:
Delhi -> Mumbai (120)means a direct route with cost120- it does not automatically imply
Mumbai -> Delhi (120)
Debugging Tip
Ask one question early: "If I can go from u to v, can I always go back?" That single question prevents many direction bugs.
Advanced Note
Some problems are better modeled as layered or state graphs where direction and weight come from transitions, not from a physical map.
Concept Cluster: Problem Modeling
Key concepts in this block:
- 22.6 Modeling real problems as graphs
Intuition
Modeling means deciding what should become a node and what should become an edge.
Why It Matters
Many graph problems are lost before the algorithm starts because the nodes or edges were chosen poorly.
How It Works
A practical modeling checklist:
- what are the entities or states?
- what transition or relationship connects them?
- is the connection one-way or two-way?
- does each edge need a weight?
- should the graph be built explicitly, or can neighbors be generated on the fly?
Examples:
- social network: users are nodes, friendships are edges
- course plan: courses are nodes, prerequisite rules are directed edges
- grid maze: cells are nodes, legal moves are edges
- lock puzzle: lock states are nodes, one dial move is an edge
Java Implementation Notes
- Not every graph must be materialized fully.
- Grid and state-space problems often use implicit graphs where neighbors are generated when needed.
- If identifiers are strings or objects, map them to integer indices when performance matters.
Common Mistakes
- choosing edges that are too vague
- ignoring direction in dependency problems
- materializing a massive graph when neighbors can be generated locally
- using expensive object-heavy structures when integer indexing is enough
Quick Example
In a maze:
- node: one open cell
- edge: one legal move to a neighboring open cell
- graph type: usually unweighted, often implicit, usually directed and undirected are equivalent because moves work both ways
Debugging Tip
State the model in one sentence before coding: "Nodes are ..., edges are ...". If that sentence feels unclear, the implementation will be unclear too.
Advanced Note
A good model often matters more than the first algorithm you try. Traversal becomes straightforward when the model is clean.
3. Worked Examples and Full Solutions
Worked Example 1: Build an Undirected Graph with an Adjacency List
Problem Statement
Given n nodes labeled 0 to n - 1 and a list of undirected edges, build the graph and return the neighbors of any requested node.
Why This Example Matters
Adjacency lists are the default representation for sparse graphs and for most traversal algorithms in the next chapter.
Constraints or Assumptions
- nodes are labeled with integers
- edges are undirected
- neighbor order is not guaranteed unless you sort it
Brute-Force Approach
Store only the edge list. Whenever you need the neighbors of a node, scan every edge and collect matches.
Better Approach
Build an adjacency list once.
Why the Better Approach Works
The edge list repeats the same scan for every neighbor query. The adjacency list spends $O(E)$ once and then answers neighbor lookup directly from the stored list.
Pragmatic Java Choice
Use:
List<List<Integer>>for the graph- one
ArrayListper node - optional sorting if deterministic output helps debugging
Java Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class AdjacencyListExample {
static List<Integer> neighborsFromEdgeList(int node, int[][] edges) {
List<Integer> neighbors = new ArrayList<>();
for (int[] edge : edges) {
if (edge[0] == node) {
neighbors.add(edge[1]);
} else if (edge[1] == node) {
neighbors.add(edge[0]);
}
}
Collections.sort(neighbors);
return neighbors;
}
static List<List<Integer>> buildUndirectedGraph(int nodeCount, int[][] edges) {
List<List<Integer>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
int first = edge[0];
int second = edge[1];
graph.get(first).add(second);
graph.get(second).add(first);
}
for (List<Integer> neighbors : graph) {
Collections.sort(neighbors);
}
return graph;
}
}
Dry Run
Suppose:
n = 5- edges are
(0, 1),(0, 3),(1, 4)
Brute force for neighbors of 0:
- scan all edges
- collect
1and3
Adjacency list after building:
0 -> [1, 3]1 -> [0, 4]2 -> []3 -> [0]4 -> [1]
The isolated node 2 still exists and must have an empty list.
Time and Space Complexity
- brute force neighbor lookup: $O(E)$ per query
- adjacency list build: $O(V + E)$
- adjacency list neighbor lookup: $O(degree(node))$
- adjacency list space: $O(V + E)$
Edge Cases
- isolated nodes
- repeated edges if the input allows them
- self-loops
n = 0
Common Mistakes
- forgetting to add both directions
- skipping isolated nodes entirely
- assuming every node appears in an edge
Worked Example 2: Direct Flight Lookup with a Weighted Directed Adjacency Matrix
Problem Statement
Given a set of cities and directed weighted flights, support direct-route existence checks and direct-route cost lookup.
Why This Example Matters
This example shows when an adjacency matrix is a better fit: many direct edge existence queries on a graph that is small enough for $O(V^2)$ storage.
Constraints or Assumptions
- edges are directed
- weights are nonnegative costs
- if multiple edges exist between the same pair, keep the cheapest one
Brute-Force Approach
Store all flights in an edge list and scan the entire list for every direct-route query.
Better Approach
Use a weighted adjacency matrix.
Why the Better Approach Works
Direct edge lookup becomes one table access instead of scanning all edges.
Pragmatic Java Choice
Use:
Long[][] matrixnullto mean "no direct edge"- a method that keeps the smallest weight for duplicate edges
Java Solution
class AdjacencyMatrixExample {
static final class WeightedDirectedGraph {
private final Long[][] matrix;
WeightedDirectedGraph(int nodeCount) {
this.matrix = new Long[nodeCount][nodeCount];
}
void addEdge(int from, int to, long weight) {
if (matrix[from][to] == null || weight < matrix[from][to]) {
matrix[from][to] = weight;
}
}
boolean hasDirectEdge(int from, int to) {
return matrix[from][to] != null;
}
long directCost(int from, int to) {
if (matrix[from][to] == null) {
throw new IllegalStateException("No direct edge");
}
return matrix[from][to];
}
}
}
Dry Run
Flights:
0 -> 1with cost500 -> 2with cost1202 -> 1with cost40
Matrix idea:
matrix[0][1] = 50matrix[0][2] = 120matrix[2][1] = 40matrix[1][0]staysnullunless that direct flight also exists
Now:
hasDirectEdge(0, 1)istruedirectCost(0, 1)is50hasDirectEdge(1, 0)isfalse
Time and Space Complexity
- brute force direct lookup: $O(E)$ per query
- adjacency matrix direct lookup: $O(1)$
- build from edges: $O(E)$
- space: $O(V^2)$
Edge Cases
- no direct connection
- duplicate edges with different costs
- self-loops
- graphs too large for a practical matrix
Common Mistakes
- accidentally filling both directions for a directed graph
- using a matrix on a huge sparse graph
- not defining how duplicate edges should be handled
Worked Example 3: Model a Grid Maze as a Graph
Problem Statement
Given a grid where '.' means open and '#' means blocked, model the maze so that each open cell can find its reachable neighboring cells in four directions.
Why This Example Matters
Many interview problems use implicit graphs. The graph is real, but building every possible edge explicitly is not always necessary.
Constraints or Assumptions
- moves are allowed up, down, left, and right
- blocked cells are not nodes
- the graph is unweighted for now
Brute-Force Approach
Treat every open cell as a node, compare it with every other open cell, and connect pairs that are one move apart.
Better Approach
Generate neighbors locally by checking only the four valid directions around a cell.
Why the Better Approach Works
A cell only has at most four relevant neighbors. Comparing against every other open cell wastes work.
Pragmatic Java Choice
Use:
- a small
Cellrecord for readability - a helper that checks bounds and blocked cells
- local neighbor generation instead of a full pairwise comparison
Java Solution
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class GridGraphModelExample {
record Cell(int row, int col) {}
static Map<Cell, List<Cell>> buildGraph(char[][] grid) {
Map<Cell, List<Cell>> graph = new HashMap<>();
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
if (isOpen(grid, row, col)) {
Cell cell = new Cell(row, col);
graph.put(cell, localNeighbors(grid, cell));
}
}
}
return graph;
}
static List<Cell> bruteForceNeighbors(char[][] grid, Cell source) {
List<Cell> openCells = new ArrayList<>();
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
if (isOpen(grid, row, col)) {
openCells.add(new Cell(row, col));
}
}
}
List<Cell> neighbors = new ArrayList<>();
for (Cell candidate : openCells) {
int distance = Math.abs(candidate.row() - source.row()) + Math.abs(candidate.col() - source.col());
if (distance == 1) {
neighbors.add(candidate);
}
}
return neighbors;
}
static List<Cell> localNeighbors(char[][] grid, Cell source) {
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
List<Cell> neighbors = new ArrayList<>();
for (int[] direction : directions) {
int nextRow = source.row() + direction[0];
int nextCol = source.col() + direction[1];
if (isOpen(grid, nextRow, nextCol)) {
neighbors.add(new Cell(nextRow, nextCol));
}
}
return neighbors;
}
private static boolean isOpen(char[][] grid, int row, int col) {
return row >= 0
&& row < grid.length
&& col >= 0
&& col < grid[0].length
&& grid[row][col] == '.';
}
}
Dry Run
Grid:
. . #
. # .
. . .
For source cell (1, 0):
- brute force checks every open cell and keeps those at Manhattan distance
1 - local neighbor generation checks only:
(2, 0)valid(0, 0)valid(1, 1)blocked(1, -1)out of bounds
So the neighbors are (2, 0) and (0, 0).
Time and Space Complexity
- brute force neighbor lookup for one cell: $O(k)$ where
kis the number of open cells - local neighbor lookup: $O(1)$ because only four directions are checked
- full explicit graph build with local checks: $O(R \cdot C)$
- space for the explicit graph: $O(V + E)$ if you materialize it
Edge Cases
- blocked starting cell
- single-cell grid
- row or column boundaries
- grids where the graph is disconnected
Common Mistakes
- treating blocked cells as nodes
- forgetting boundary checks
- building every pair of open cells when only local moves matter
- missing that many grid problems are graphs even when the problem never says so
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- edge list is simple, but neighbor lookup is slow
- adjacency list is the standard choice for sparse graphs and traversals
- adjacency matrix gives $O(1)$ direct-edge checks but costs $O(V^2)$ memory
- implicit graphs avoid building edges that can be generated locally when needed
Choose an adjacency list when:
- the graph is sparse
- you need to iterate over neighbors often
- BFS or DFS is likely coming next
Choose an adjacency matrix when:
- the graph is small or dense
- direct edge existence checks happen frequently
- $O(V^2)$ memory is acceptable
Choose implicit modeling when:
- neighbors come from simple rules such as grid moves or state transitions
- explicit construction would be unnecessarily large
- you only need local neighbor generation during traversal
Recognition signals for graph modeling:
- entities with relationships
- dependencies or prerequisites
- routes, roads, flights, or links
- puzzles with legal moves between states
- grids where movement rules define adjacency
Signals not to force a graph:
- the structure is strictly linear and array-based
- the problem is really about intervals, not connections
- a full graph materialization would be much larger than necessary
5. Edge Cases, Pitfalls, and Debugging
Most common modeling bugs:
- nodes are chosen inconsistently
- direction is ignored in dependency problems
- undirected edges are stored only one way
- weights are forgotten or attached to the wrong edge
- isolated nodes disappear from the representation
Boundary and scaling risks:
- node labels that are not contiguous
- one-based vs zero-based indexing
- adjacency matrices that are too large
- self-loops and duplicate edges
- implicit graphs with missing boundary checks
Short debugging checklist:
- What exactly is a node?
- What exactly is an edge?
- Is the connection one-way or two-way?
- Does an edge need a weight?
- Are isolated nodes still represented?
- Is the chosen representation reasonable for the graph size and query pattern?
6. Practice Problems
Easy
- Title: Find Center of Star Graph. One-line prompt: identify the hub node from undirected edges. Expected pattern or core idea: graph terminology and degree reasoning.
- Title: Find the Town Judge. One-line prompt: find the person trusted by everyone who trusts nobody. Expected pattern or core idea: directed graph modeling with indegree and outdegree.
- Title: Destination City. One-line prompt: given one-way city routes, find the terminal city. Expected pattern or core idea: directed graph representation and outgoing-edge reasoning.
Medium
- Title: Keys and Rooms. One-line prompt: treat rooms and keys as a graph before traversing it. Expected pattern or core idea: model rooms as nodes and keys as directed edges.
- Title: Course Schedule. One-line prompt: turn prerequisite pairs into a directed dependency graph. Expected pattern or core idea: adjacency list plus directed modeling.
- Title: Network Delay Time. One-line prompt: represent travel times between nodes for later shortest-path processing. Expected pattern or core idea: weighted directed graph modeling.
Hard
- Title: Word Ladder. One-line prompt: connect words that differ by one character and reason about the resulting graph. Expected pattern or core idea: implicit graph modeling.
- Title: Open the Lock. One-line prompt: model each lock state as a node with legal dial turns as edges. Expected pattern or core idea: state graph modeling.
- Title: Bus Routes. One-line prompt: decide whether bus stops or routes should become nodes before solving. Expected pattern or core idea: graph modeling choice before traversal.
7. Short Recap
The core idea of this chapter is that graph problems begin with modeling, not with algorithms.
The most important optimization insight is that representation choice matters:
- adjacency list for sparse traversal-heavy graphs
- adjacency matrix for frequent direct-edge checks
- implicit graphs when neighbors can be generated locally
The most important implementation warning is to define nodes, edges, direction, and weight clearly before coding.
This chapter prepares the next chapter by turning graph models into actual exploration with BFS and DFS.
8. Coverage Check
- 22.1 Graph terminology
- 22.2 Adjacency list
- 22.3 Adjacency matrix
- 22.4 Directed and undirected graphs
- 22.5 Weighted graphs
- 22.6 Modeling real problems as graphs
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 23: Graph Traversal
23: Graph Traversal
Goal: Teach how to explore graphs systematically using BFS and DFS, and how traversal solves reachability, connected components, cycle detection, and bipartite checking in Java.
Outcome: By the end of this chapter, you can implement BFS and DFS cleanly, count connected components, detect cycles, check bipartite structure, and reuse robust Java traversal templates across graph problems.
1. Intuition First
Once a graph is modeled correctly, the next question is simple: how do you move through it without missing nodes or getting stuck in cycles?
A simple real-world analogy is exploring a building:
- BFS explores room by room, outward in layers from the starting room
- DFS goes down one hallway as far as possible before backing up
The core mental model is this:
- traversal needs a frontier of work
- BFS uses a queue and explores by distance in edges
- DFS uses recursion or an explicit stack and explores deeply first
- a visited structure prevents repeated work and infinite loops
The most common beginner confusion point is marking visited too late. If you do that carelessly, nodes may enter the queue or recursion many times.
In the roadmap, this chapter turns graph representation into graph movement. The next chapter narrows that movement to directed acyclic graphs and ordering constraints.
2. Core Concepts and Techniques
Concept Cluster: Two Fundamental Traversals
Key concepts in this block:
- 23.1 Breadth-first search
- 23.2 Depth-first search
Intuition
BFS explores by layers. DFS explores by depth. They answer different questions naturally.
Why It Matters
BFS is usually the first choice for:
- shortest path in an unweighted graph
- layer-by-layer expansion
- minimum number of moves
DFS is usually the first choice for:
- structural exploration
- recursion-friendly search
- component counting
- many cycle and backtracking patterns
How It Works
BFS:
- start from a source
- mark it visited
- push it into a queue
- repeatedly pop from the queue and push unvisited neighbors
DFS:
- start from a source
- mark it visited
- recursively or iteratively visit each unvisited neighbor before returning
Java Implementation Notes
ArrayDeque<Integer>is a good queue for BFS.- Recursive DFS is simple, but deep graphs may risk stack overflow.
- Adjacency lists are usually the most natural representation for traversal.
- Mark visited as soon as you decide to process a node, not after exploring all neighbors.
Common Mistakes
- marking visited too late in BFS
- forgetting disconnected components
- assuming DFS finds shortest paths in unweighted graphs
- using recursion without considering graph depth
Quick Example
Graph:
0 -> [1, 2]1 -> [3]2 -> [4]
From 0:
- BFS order is
0, 1, 2, 3, 4 - one valid DFS order is
0, 1, 3, 2, 4
Debugging Tip
For BFS, print the queue after each pop. For DFS, print (node, parent) at entry and exit.
Advanced Note
Traversal order can vary if neighbor lists are in different orders. The correctness condition is usually about coverage, not one exact order.
Concept Cluster: Structure from Traversal
Key concepts in this block:
- 23.3 Connected components
- 23.4 Cycle detection
Intuition
Traversal does more than visit nodes. It reveals the shape of the graph.
Why It Matters
Connected components tell you how many disconnected regions exist. Cycle detection tells you whether some path loops back in a problematic way.
How It Works
Connected components in an undirected graph:
- loop through all nodes
- if a node is unvisited, start a traversal
- that one traversal covers exactly one component
Cycle detection:
- undirected graph: track the parent; visiting an already visited neighbor that is not the parent means a cycle
- directed graph: often use a recursion stack or three-state marking
Java Implementation Notes
- Use one outer loop for all nodes, not just one source.
- Keep parent information when checking cycles in undirected graphs.
- For directed cycles, a three-state array is often cleaner than a plain visited array.
Common Mistakes
- assuming one BFS or DFS from node
0covers the full graph - treating the parent edge in an undirected graph as a cycle
- mixing directed and undirected cycle logic
Quick Example
If the graph has edges:
(0, 1),(1, 2),(2, 0),(3, 4)
Then:
{0, 1, 2}is one connected component with a cycle{3, 4}is another connected component without a cycle
Debugging Tip
When cycle detection looks wrong, inspect one component at a time and write down the parent relationship for each edge visit.
Advanced Note
Directed cycle detection becomes especially important in the next chapter, where topological ordering only works on DAGs.
Concept Cluster: Coloring and Reusable Templates
Key concepts in this block:
- 23.5 Bipartite graph check
- 23.6 Java traversal templates
Intuition
A graph is bipartite if you can color its nodes with two colors so that every edge connects different colors.
Why It Matters
Bipartite checking appears in scheduling, conflict modeling, and parity-style constraints. It is also a good test of whether you truly understand traversal state.
How It Works
Use BFS or DFS to color:
- start an unvisited node with color
0 - every neighbor must get the opposite color
- if a neighbor already has the same color, the graph is not bipartite
Because the graph may be disconnected, repeat this for every component.
Java Implementation Notes
- Use
int[] colorwith values like-1,0, and1. - Reusable traversal templates should separate:
- graph representation
- visited or color state
- node-processing logic
Common Mistakes
- checking only one component
- forgetting that a self-loop immediately breaks bipartiteness
- mixing visited state and color state carelessly
Quick Example
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
class GraphTraversalTemplatesQuickExample {
static List<Integer> bfsOrder(List<List<Integer>> graph, int start) {
List<Integer> order = new ArrayList<>();
boolean[] visited = new boolean[graph.size()];
Queue<Integer> queue = new ArrayDeque<>();
visited[start] = true;
queue.offer(start);
while (!queue.isEmpty()) {
int node = queue.poll();
order.add(node);
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
return order;
}
static List<Integer> dfsOrder(List<List<Integer>> graph, int start) {
List<Integer> order = new ArrayList<>();
boolean[] visited = new boolean[graph.size()];
dfs(start, graph, visited, order);
return order;
}
private static void dfs(int node, List<List<Integer>> graph, boolean[] visited, List<Integer> order) {
visited[node] = true;
order.add(node);
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited, order);
}
}
}
}
Debugging Tip
When a template fails, confirm the invariant for each loop or call: every node in the queue or recursion stack should already be marked as scheduled for processing.
Advanced Note
Well-structured templates reduce bugs more than clever traversal tricks do.
3. Worked Examples and Full Solutions
Worked Example 1: Shortest Path in an Unweighted Graph with BFS
Problem Statement
Given an unweighted graph, a source node, and a target node, return one shortest path from source to target.
Why This Example Matters
This is the most important BFS pattern. BFS is not just traversal order here; it guarantees the first time you reach a node is through the minimum number of edges.
Constraints or Assumptions
- the graph is unweighted
- there may be multiple shortest paths
- return an empty path if the target is unreachable
Brute-Force Approach
Enumerate all simple paths from source to target and keep the shortest one.
Better Approach
Use BFS with a parent[] array to reconstruct the shortest path.
Why the Better Approach Works
BFS explores nodes by increasing distance from the source. The first time the target is reached, the path length is minimal in number of edges.
Pragmatic Java Choice
Use:
ArrayDeque<Integer>as the queueboolean[] visitedint[] parentinitialized to-1
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
class BfsShortestPathExample {
static List<Integer> bruteForceShortestPath(List<List<Integer>> graph, int source, int target) {
boolean[] visited = new boolean[graph.size()];
List<Integer> currentPath = new ArrayList<>();
List<Integer> bestPath = new ArrayList<>();
dfsAllPaths(graph, source, target, visited, currentPath, bestPath);
return bestPath;
}
static List<Integer> shortestPathBfs(List<List<Integer>> graph, int source, int target) {
int nodeCount = graph.size();
boolean[] visited = new boolean[nodeCount];
int[] parent = new int[nodeCount];
Arrays.fill(parent, -1);
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(source);
visited[source] = true;
parent[source] = source;
while (!queue.isEmpty()) {
int node = queue.poll();
if (node == target) {
break;
}
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
parent[neighbor] = node;
queue.offer(neighbor);
}
}
}
if (!visited[target]) {
return List.of();
}
return reconstructPath(parent, source, target);
}
private static void dfsAllPaths(
List<List<Integer>> graph,
int node,
int target,
boolean[] visited,
List<Integer> currentPath,
List<Integer> bestPath) {
visited[node] = true;
currentPath.add(node);
if (node == target) {
if (bestPath.isEmpty() || currentPath.size() < bestPath.size()) {
bestPath.clear();
bestPath.addAll(currentPath);
}
} else {
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfsAllPaths(graph, neighbor, target, visited, currentPath, bestPath);
}
}
}
currentPath.remove(currentPath.size() - 1);
visited[node] = false;
}
private static List<Integer> reconstructPath(int[] parent, int source, int target) {
List<Integer> path = new ArrayList<>();
int current = target;
while (current != source) {
path.add(current);
current = parent[current];
}
path.add(source);
Collections.reverse(path);
return path;
}
}
Dry Run
Graph:
0 -> [1, 2]1 -> [3]2 -> [3, 4]3 -> [5]4 -> [5]
Source 0, target 5.
BFS steps:
- start with queue
[0] - visit
0, add1and2 - visit
1, add3 - visit
2, add4because3is already scheduled - visit
3, add5
The reconstructed path can be [0, 1, 3, 5]. It uses three edges, which is shortest.
Time and Space Complexity
- brute force simple-path search: exponential in the worst case
- BFS with adjacency list: $O(V + E)$
- extra space: $O(V)$ for queue, visited, and parent
Edge Cases
- source equals target
- target unreachable
- graph with cycles
- multiple shortest paths
Common Mistakes
- marking visited only when popping instead of when enqueuing
- forgetting to store parents for path reconstruction
- using BFS shortest-path logic on weighted graphs
Worked Example 2: Count Connected Components and Detect a Cycle
Problem Statement
Given an undirected graph, return:
- the number of connected components
- whether the graph contains at least one cycle
Why This Example Matters
This example shows how one DFS framework can answer multiple structural questions at once.
Constraints or Assumptions
- the graph is undirected
- it may be disconnected
- self-loops count as cycles
Brute-Force Approach
For each node, run a full reachability search, compare all reachability sets, and deduce the component groups. For cycle detection, repeatedly test whether alternate routes exist between the endpoints of an edge. This works conceptually, but it repeats a lot of work.
Better Approach
Run one DFS per unvisited component and track the parent edge to detect cycles.
Why the Better Approach Works
Each node is visited once. The outer loop counts how many separate traversals are needed. During a DFS in an undirected graph, finding a visited neighbor that is not the parent means a back edge and therefore a cycle.
Pragmatic Java Choice
Use:
- one outer loop over all nodes
- a recursive DFS for clarity
- a small result record to return both answers together
Java Solution
import java.util.List;
class ConnectedComponentsAndCycleExample {
record Analysis(int componentCount, boolean hasCycle) {}
static int bruteForceComponentCount(List<List<Integer>> graph) {
int nodeCount = graph.size();
boolean[][] reaches = new boolean[nodeCount][nodeCount];
for (int start = 0; start < nodeCount; start++) {
markReachable(graph, start, reaches[start]);
}
boolean[] assigned = new boolean[nodeCount];
int components = 0;
for (int node = 0; node < nodeCount; node++) {
if (assigned[node]) {
continue;
}
components++;
for (int other = 0; other < nodeCount; other++) {
if (reaches[node][other]) {
assigned[other] = true;
}
}
}
return components;
}
static Analysis analyzeUndirectedGraph(List<List<Integer>> graph) {
boolean[] visited = new boolean[graph.size()];
int componentCount = 0;
boolean hasCycle = false;
for (int node = 0; node < graph.size(); node++) {
if (!visited[node]) {
componentCount++;
if (dfs(node, -1, graph, visited)) {
hasCycle = true;
}
}
}
return new Analysis(componentCount, hasCycle);
}
private static boolean dfs(int node, int parent, List<List<Integer>> graph, boolean[] visited) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
if (dfs(neighbor, node, graph, visited)) {
return true;
}
} else if (neighbor != parent) {
return true;
}
}
return false;
}
private static void markReachable(List<List<Integer>> graph, int node, boolean[] seen) {
if (seen[node]) {
return;
}
seen[node] = true;
for (int neighbor : graph.get(node)) {
markReachable(graph, neighbor, seen);
}
}
}
Dry Run
Graph:
- component 1: edges
(0, 1),(1, 2),(2, 0) - component 2: edge
(3, 4) - component 3: node
5isolated
Outer loop:
- start at
0, DFS visits0, 1, 2and detects a cycle - next unvisited node is
3, DFS visits3, 4 - next unvisited node is
5, DFS visits only5
Final answer:
- component count is
3 - cycle exists is
true
Time and Space Complexity
- brute force repeated reachability: up to $O(V \cdot (V + E))$
- optimized DFS: $O(V + E)$
- extra space: $O(V)$ for visited, plus recursion stack up to $O(V)$
Edge Cases
- isolated nodes
- self-loops
- multiple components
- graph with no edges
Common Mistakes
- forgetting the outer loop over all nodes
- reporting the parent edge as a cycle
- using undirected cycle logic on a directed graph
Worked Example 3: Check Whether a Graph Is Bipartite
Problem Statement
Given an undirected graph, determine whether it can be colored using two colors so that every edge connects different colors.
Why This Example Matters
Bipartite checking combines traversal, state assignment, and component handling. It is a clean test of BFS or DFS correctness.
Constraints or Assumptions
- the graph can be disconnected
- a self-loop immediately makes the graph non-bipartite
- any valid two-coloring is acceptable
Brute-Force Approach
Try all possible two-color assignments for all nodes and check whether every edge connects opposite colors.
Better Approach
Use BFS coloring.
Why the Better Approach Works
When BFS visits an edge (u, v), it forces v to have the opposite color of u. If a contradiction appears, the graph is not bipartite. If all components are colored consistently, it is bipartite.
Pragmatic Java Choice
Use:
int[] colorfilled with-1- BFS so layer-style reasoning is explicit
- one outer loop to cover disconnected graphs
Java Solution
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
class BipartiteGraphCheckExample {
static boolean bruteForceTwoColoring(List<List<Integer>> graph) {
int nodeCount = graph.size();
int totalAssignments = 1 << nodeCount;
for (int mask = 0; mask < totalAssignments; mask++) {
boolean valid = true;
for (int node = 0; node < nodeCount && valid; node++) {
int color = (mask >> node) & 1;
for (int neighbor : graph.get(node)) {
int neighborColor = (mask >> neighbor) & 1;
if (color == neighborColor) {
valid = false;
break;
}
}
}
if (valid) {
return true;
}
}
return false;
}
static boolean isBipartite(List<List<Integer>> graph) {
int[] color = new int[graph.size()];
Arrays.fill(color, -1);
for (int start = 0; start < graph.size(); start++) {
if (color[start] != -1) {
continue;
}
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(start);
color[start] = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
for (int neighbor : graph.get(node)) {
if (neighbor == node) {
return false;
}
if (color[neighbor] == -1) {
color[neighbor] = 1 - color[node];
queue.offer(neighbor);
} else if (color[neighbor] == color[node]) {
return false;
}
}
}
}
return true;
}
}
Dry Run
Graph:
0 -> [1, 3]1 -> [0, 2]2 -> [1, 3]3 -> [0, 2]
This is an even cycle.
BFS coloring:
- color
0as0 - neighbors
1and3become1 - neighbor
2of node1becomes0 - all edges connect opposite colors, so the graph is bipartite
If you add edge (0, 2):
- node
0and node2would both need the same color and different colors at once - contradiction appears
- graph is not bipartite
Time and Space Complexity
- brute force coloring: $O(2^V \cdot E)$
- BFS coloring: $O(V + E)$
- extra space: $O(V)$
Edge Cases
- disconnected graph
- isolated nodes
- self-loops
- odd cycles
Common Mistakes
- checking only one connected component
- forgetting that a self-loop breaks bipartiteness immediately
- mixing visited logic and color logic so nodes are recolored incorrectly
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- BFS and DFS both run in $O(V + E)$ on adjacency lists
- BFS naturally gives shortest path in unweighted graphs
- DFS is often simpler for recursive structural checks
- connected components, cycle detection, and bipartite checks are usually just traversal plus the right extra state
Choose BFS when:
- shortest path in an unweighted graph matters
- the problem has layers or minimum moves
- queue-based level reasoning is natural
Choose DFS when:
- you need structural exploration
- recursion makes the logic clearer
- parent or recursion-state reasoning is central
Use component-wise outer loops when:
- the graph may be disconnected
- the question asks about the whole graph, not only one source
Recognition signals:
- "can you reach...?"
- "minimum number of moves" in an unweighted setting
- "how many groups/components...?"
- "does this graph contain a cycle?"
- "can this graph be split into two valid groups?"
Signals not to force this technique:
- weighted shortest path is required
- the graph is a DAG dependency problem better suited for topological order
- the core problem is not about traversal at all
5. Edge Cases, Pitfalls, and Debugging
Most common implementation bugs:
- forgetting to mark visited at the right moment
- starting from one node and assuming the whole graph is covered
- using DFS for shortest path in an unweighted graph
- confusing directed cycle logic with undirected cycle logic
- forgetting parent tracking in undirected cycle detection
- failing to reset or separate traversal state across problems
Boundary and state risks:
- empty graph
- isolated nodes
- self-loops
- repeated edges
- recursion depth on very deep graphs
- disconnected graphs in bipartite checks
Short debugging checklist:
- Is every node that enters the queue or recursion stack marked as scheduled?
- Are you looping over all nodes for whole-graph problems?
- In undirected cycle detection, are you excluding the parent edge?
- In bipartite checking, are colors assigned consistently across components?
- Are you relying on BFS only for unweighted shortest path problems?
6. Practice Problems
Easy
- Title: Find if Path Exists in Graph. One-line prompt: determine whether two nodes are connected at all. Expected pattern or core idea: BFS or DFS reachability.
- Title: Flood Fill. One-line prompt: recolor all connected cells reachable from a starting cell. Expected pattern or core idea: BFS or DFS on an implicit grid graph.
- Title: Keys and Rooms. One-line prompt: decide whether every room becomes reachable from room
0. Expected pattern or core idea: traversal over a directed graph.
Medium
- Title: Number of Provinces. One-line prompt: count connected components from an adjacency matrix. Expected pattern or core idea: component traversal.
- Title: Is Graph Bipartite? One-line prompt: decide whether the graph can be colored with two colors. Expected pattern or core idea: BFS or DFS coloring.
- Title: Redundant Connection. One-line prompt: identify the extra edge that creates a cycle in an undirected graph. Expected pattern or core idea: traversal-based cycle reasoning or DSU comparison.
Hard
- Title: Word Ladder. One-line prompt: find the shortest transformation sequence length between words. Expected pattern or core idea: BFS on an implicit graph.
- Title: Open the Lock. One-line prompt: reach a target lock state while avoiding forbidden states. Expected pattern or core idea: BFS over state space.
- Title: Shortest Path in Binary Matrix. One-line prompt: compute the minimum path length through an implicit grid graph. Expected pattern or core idea: BFS with careful visited management.
7. Short Recap
The core idea of this chapter is that graph traversal is controlled exploration with explicit state.
The most important optimization insight is that BFS and DFS are not interchangeable:
- BFS for unweighted shortest paths and layers
- DFS for structural exploration and many recursive checks
The most important implementation warning is to manage visited, parent, and color state carefully, especially across disconnected graphs.
This chapter prepares the next chapter by turning general traversal into ordered traversal on DAGs with topological sorting.
8. Coverage Check
- 23.1 Breadth-first search
- 23.2 Depth-first search
- 23.3 Connected components
- 23.4 Cycle detection
- 23.5 Bipartite graph check
- 23.6 Java traversal templates
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 24: Topological Sort and DAG Problems
24: Topological Sort and DAG Problems
Goal: Teach how directed acyclic graphs model one-way dependencies, how to compute a valid topological order in Java, and how that order solves dependency and shortest-path problems efficiently.
Outcome: By the end of this chapter, you can recognize a DAG, produce a topological ordering with Kahn's algorithm or DFS, solve dependency ordering problems, and compute shortest paths in DAGs in linear time.
1. Intuition First
This chapter matters because many real problems are not just about reachability. They are about order. If task A must happen before task B, the graph is not just a set of connections. It is a dependency system.
A simple real-world analogy is a university degree plan:
- you cannot take advanced databases before the prerequisite programming course
- you cannot graduate if your prerequisites form a loop
- if the prerequisite graph has no directed cycle, there is at least one legal course order
The core mental model is this:
- a directed edge
u -> vmeansumust come beforev - a directed acyclic graph, or DAG, is a directed graph with no directed cycle
- a topological order is a linear ordering of nodes where every edge points forward in the order
The most common beginner confusion point is mixing up plain traversal with dependency order. BFS and DFS tell you how to visit a graph. Topological sort tells you whether the graph admits a legal ordering and what one such ordering can be.
In the roadmap, Chapter 23 taught general graph traversal. This chapter adds a stricter graph shape and a stronger output: valid dependency order. That same order will become a powerful optimization tool for shortest paths inside DAGs, which then leads naturally into the general shortest-path algorithms in the next chapter.
2. Core Concepts and Techniques
Concept Cluster: DAG Structure and Dependency Modeling
Key concepts in this block:
- 24.1 Directed acyclic graphs
- 24.4 Dependency ordering problems
Intuition
A DAG is the graph version of "do these things in an order that respects prerequisites."
Why It Matters
Build systems, job scheduling, course planning, spreadsheet recalculation, and package installation all have this shape. The graph does not just describe what touches what. It describes what must happen first.
How It Works
A graph is a DAG if it is directed and contains no directed cycle.
A topological order exists if and only if the graph is a DAG.
For every edge u -> v, node u must appear before node v in any valid topological order.
Dependency ordering problems often reduce to three steps:
- choose the correct edge direction
- detect whether a cycle exists
- if no cycle exists, produce one valid order
Java Implementation Notes
- Use an adjacency list for most sparse graphs.
- Be explicit about edge meaning. If a pair says "prerequisite before course", store
prerequisite -> course. - Disconnected DAGs are normal. A topological order may start from any zero-dependency node in any component.
Common Mistakes
- reversing the edge direction
- assuming a topological order is unique
- trying to topologically sort an undirected graph
- forgetting that a directed cycle makes the problem impossible
Quick Example
If the graph has edges:
0 -> 21 -> 22 -> 3
Then valid orders include:
0, 1, 2, 31, 0, 2, 3
Node 2 cannot come before 0 or 1, and node 3 cannot come before 2.
Debugging Tip
If the produced order violates a dependency, inspect one edge at a time and ask whether the graph direction matches the problem statement.
Advanced Note
Topological order is only about relative constraints. It does not say anything about path cost, earliest completion time, or optimality by itself.
Concept Cluster: Kahn's Algorithm
Key concepts in this block:
- 24.2 Kahn's algorithm
Intuition
Kahn's algorithm repeatedly removes nodes that currently have no incoming dependencies.
Why It Matters
It is the most direct algorithm for dependency scheduling. It is also very good at cycle detection because a cycle leaves nodes stuck with indegree greater than zero.
How It Works
Kahn's algorithm uses indegree, which is the number of incoming edges to a node.
Algorithm:
- compute indegree for every node
- push all nodes with indegree
0into a queue - repeatedly pop a node, add it to the answer, and reduce the indegree of its outgoing neighbors
- when a neighbor reaches indegree
0, push it into the queue - if the answer contains fewer than all nodes, the graph has a cycle
Java Implementation Notes
- Use
int[] indegree. - Use
ArrayDeque<Integer>as the queue. - If the problem wants a smallest-numbered valid order, use a
PriorityQueue<Integer>instead of a queue.
Common Mistakes
- forgetting to initialize all zero-indegree nodes
- decrementing the wrong endpoint of an edge
- treating "queue became empty" as success even when some nodes were never processed
Quick Example
Suppose indegrees start as:
- node
0:0 - node
1:0 - node
2:2 - node
3:1
Queue starts with 0, 1. Once both are removed, node 2 reaches indegree 0, and then node 3 becomes available.
Debugging Tip
After building the graph, the sum of all indegrees should equal the number of edges.
Advanced Note
Kahn's algorithm naturally supports level-based scheduling variants, such as "minimum semesters" or "number of rounds."
Concept Cluster: DFS-Based Topological Sort
Key concepts in this block:
- 24.3 DFS-based topological sort
Intuition
DFS-based topological sort uses finishing order. A node is added after all nodes reachable from it have already been processed.
Why It Matters
This version is often convenient when DFS is already the natural reasoning tool, especially when you want explicit cycle detection with recursion-stack state.
How It Works
Use three states:
0: unvisited1: visiting2: fully processed
DFS steps:
- mark the current node as visiting
- recursively process each outgoing neighbor
- if you ever see a neighbor already in state
1, you found a directed cycle - after all neighbors are done, mark the current node as processed and append it to the order
- reverse the final order
Java Implementation Notes
- A plain
visited[]array is not enough for directed cycle detection here. - Use recursion for clarity or an explicit stack if depth may be large.
- Reverse postorder is the key result, not preorder.
Common Mistakes
- using only
visited[]and missing back edges - forgetting to reverse the collected order
- applying undirected cycle logic to a directed graph
Quick Example
For edges 0 -> 2, 1 -> 2, 2 -> 3:
- DFS from
0reaches2, then3 3finishes first- then
2 - then
0 - after also processing
1, reversing the finish order gives a valid topological order
Debugging Tip
Log state transitions as 0 -> 1 -> 2. A node should never move backward.
Advanced Note
Recursive DFS is elegant, but on very deep DAGs an iterative implementation may be safer in production.
Concept Cluster: Shortest Paths in DAGs
Key concepts in this block:
- 24.5 Shortest paths in DAGs
Intuition
In a DAG, once you process nodes in topological order, every edge into the current node has already been considered. That removes the need for repeated revisits.
Why It Matters
This gives a shortest-path algorithm in O(V + E) time, which is faster than general shortest-path algorithms for this special graph shape.
How It Works
Steps:
- compute a topological order
- initialize all distances to infinity except the source
- process nodes in topological order
- for each edge
u -> vwith weightw, relax it by checking whetherdistance[u] + wimprovesdistance[v]
Relaxation means trying to improve a known distance using one more edge.
This works even with negative edge weights, as long as the graph is a DAG.
Java Implementation Notes
- Use
longfor distances. - Keep unreachable nodes at a large sentinel value.
- Guard against adding to infinity by checking reachability before relaxing.
Common Mistakes
- trying this on a graph that may contain cycles
- assuming unreachable nodes should become
0 - forgetting that edge direction still matters
Quick Example
Edges:
0 -> 1with weight20 -> 2with weight41 -> 2with weight-1
If the topological order is 0, 1, 2, then:
- after processing
0, distances are0, 2, 4 - after processing
1, distance to2improves from4to1
Debugging Tip
Print the topological order before relaxing edges. If the order is wrong, all later shortest-path logic will also be wrong.
Advanced Note
The same pattern can solve longest-path-style DAG problems if the recurrence and initialization are adjusted carefully.
3. Worked Examples and Full Solutions
Worked Example 1: Course Schedule Ordering with Kahn's Algorithm
Problem Statement
Given numCourses labeled 0 to numCourses - 1 and prerequisite pairs [course, prerequisite], return one valid order in which all courses can be completed. If no valid order exists, return an empty list.
Why This Example Matters
This is the standard dependency-ordering problem. It maps directly to a DAG and makes indegree reasoning concrete.
Constraints or Assumptions
- the graph is directed
- there may be disconnected components
- multiple valid orders may exist
- an empty result means a cycle exists
Brute-Force Approach
Repeatedly scan all unscheduled courses and ask whether every prerequisite has already been completed.
This works, but it rescans the prerequisite list again and again.
Better Approach
Use Kahn's algorithm with an indegree array and a queue of currently available courses.
Why the Better Approach Works
A course is ready exactly when all incoming dependencies have been removed. Kahn's algorithm tracks that condition incrementally instead of recomputing it from scratch every round.
Pragmatic Java Choice
Use:
- an adjacency list from
prerequisite -> course - an
int[] indegree - an
ArrayDeque<Integer>queue
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
class KahnTopologicalOrderExample {
static List<Integer> naiveOrderByRescanning(int numCourses, int[][] prerequisites) {
Set<Integer> scheduled = new HashSet<>();
List<Integer> order = new ArrayList<>();
boolean madeProgress = true;
while (order.size() < numCourses && madeProgress) {
madeProgress = false;
for (int course = 0; course < numCourses; course++) {
if (scheduled.contains(course)) {
continue;
}
boolean ready = true;
for (int[] prerequisite : prerequisites) {
int nextCourse = prerequisite[0];
int requiredCourse = prerequisite[1];
if (nextCourse == course && !scheduled.contains(requiredCourse)) {
ready = false;
break;
}
}
if (ready) {
scheduled.add(course);
order.add(course);
madeProgress = true;
}
}
}
return order.size() == numCourses ? order : List.of();
}
static List<Integer> topologicalOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int course = 0; course < numCourses; course++) {
graph.add(new ArrayList<>());
}
int[] indegree = new int[numCourses];
for (int[] prerequisite : prerequisites) {
int course = prerequisite[0];
int requiredCourse = prerequisite[1];
graph.get(requiredCourse).add(course);
indegree[course]++;
}
Queue<Integer> queue = new ArrayDeque<>();
for (int course = 0; course < numCourses; course++) {
if (indegree[course] == 0) {
queue.offer(course);
}
}
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int course = queue.poll();
order.add(course);
for (int nextCourse : graph.get(course)) {
indegree[nextCourse]--;
if (indegree[nextCourse] == 0) {
queue.offer(nextCourse);
}
}
}
return order.size() == numCourses ? order : List.of();
}
}
Dry Run
Input:
numCourses = 4- prerequisites:
[1, 0],[2, 0],[3, 1],[3, 2]
Graph:
0 -> 10 -> 21 -> 32 -> 3
Indegrees:
0: 01: 12: 13: 2
Process:
- queue starts with
0 - pop
0, order becomes[0], indegrees of1and2become0 - queue now has
1, 2 - pop
1, order becomes[0, 1], indegree of3becomes1 - pop
2, order becomes[0, 1, 2], indegree of3becomes0 - pop
3, order becomes[0, 1, 2, 3]
Time and Space Complexity
Brute force:
- Time:
O(VE)in the common repeated-rescan form - Space:
O(V)
Kahn's algorithm:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- cycle such as
0 -> 1 -> 0 - isolated courses with no prerequisites
- duplicate prerequisite pairs if input is not sanitized
numCourses = 0
Common Mistakes
- building the edge as
course -> prerequisite - forgetting to compare output size with
numCourses - only seeding the queue with one zero-indegree node instead of all of them
Worked Example 2: Build Order with DFS-Based Topological Sort
Problem Statement
Given moduleCount modules and dependency pairs [prerequisite, dependent], return one valid build order. If the dependencies contain a cycle, return an empty list.
Why This Example Matters
It shows the DFS version of topological sort and makes directed cycle detection explicit.
Constraints or Assumptions
- dependencies are directed
- the build graph may be disconnected
- any valid order is acceptable
Brute-Force Approach
Generate all permutations of the modules and test whether each order respects every dependency.
That is conceptually simple but factorial in the number of modules, so it becomes useless quickly.
Better Approach
Use DFS with a three-state array and reverse finishing order.
Why the Better Approach Works
A node is added only after every node reachable from it has been fully processed. Reversing that finishing order places prerequisites before dependents. A back edge to a currently visiting node proves a cycle.
Pragmatic Java Choice
Use:
- an adjacency list from
prerequisite -> dependent - an
int[] statewith values0,1, and2 - a
List<Integer>to collect finish order
Java Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class DfsTopologicalOrderExample {
static List<Integer> buildOrder(int moduleCount, int[][] dependencies) {
List<List<Integer>> graph = new ArrayList<>();
for (int module = 0; module < moduleCount; module++) {
graph.add(new ArrayList<>());
}
for (int[] dependency : dependencies) {
int prerequisite = dependency[0];
int dependent = dependency[1];
graph.get(prerequisite).add(dependent);
}
int[] state = new int[moduleCount];
List<Integer> order = new ArrayList<>();
for (int module = 0; module < moduleCount; module++) {
if (state[module] == 0 && !dfs(module, graph, state, order)) {
return List.of();
}
}
Collections.reverse(order);
return order;
}
private static boolean dfs(int node, List<List<Integer>> graph, int[] state, List<Integer> order) {
state[node] = 1;
for (int neighbor : graph.get(node)) {
if (state[neighbor] == 1) {
return false;
}
if (state[neighbor] == 0 && !dfs(neighbor, graph, state, order)) {
return false;
}
}
state[node] = 2;
order.add(node);
return true;
}
}
Dry Run
Input:
moduleCount = 5- dependencies:
[0, 2],[1, 2],[2, 3]
Meaning:
0before21before22before34is independent
Possible DFS flow:
- start at
0 - go to
2 - go to
3 - finish
3, then2, then0 - later process
1, then4
Collected finish order could be:
[3, 2, 0, 1, 4]
Reverse it:
[4, 1, 0, 2, 3]
That is valid because 0 and 1 still come before 2, and 2 comes before 3.
Time and Space Complexity
Brute force:
- Time:
O(V! * E) - Space:
O(V)
DFS topological sort:
- Time:
O(V + E) - Space:
O(V + E)plus recursion stack up toO(V)
Edge Cases
- a self-loop such as
[2, 2] - multiple disconnected components
- deep chains that may create recursion-depth concerns
- duplicate dependencies
Common Mistakes
- using only a boolean
visited[] - forgetting to reverse the finish order
- treating a fully processed node as a cycle
Worked Example 3: Shortest Paths in a Weighted DAG
Problem Statement
Given a weighted DAG with nodeCount nodes, an edge list [from, to, weight], and a source node, return the shortest distance from the source to every node. Use a large sentinel for unreachable nodes.
Why This Example Matters
It shows why topological order is not just for dependency output. In DAGs, it directly turns into dynamic programming over paths.
Constraints or Assumptions
- the graph must be a DAG
- edge weights may be positive, zero, or negative
- unreachable nodes should remain at infinity
Brute-Force Approach
Enumerate all directed paths starting from the source and keep the cheapest path to each destination.
That is exponential in the worst case because a DAG can still contain many distinct paths.
Better Approach
Compute a topological order once, then relax edges in that order.
Why the Better Approach Works
When processing a node in topological order, every path into that node has already come from earlier nodes. That means its best distance is already finalized for the purpose of forward relaxations.
Pragmatic Java Choice
Use:
- an adjacency list with edge weights
- Kahn's algorithm to obtain a topological order
- a
long[] distancearray
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
class DagShortestPathExample {
private static final class Edge {
final int to;
final int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
static long[] shortestPaths(int nodeCount, int[][] edges, int source) {
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
int[] indegree = new int[nodeCount];
for (int[] edge : edges) {
int from = edge[0];
int to = edge[1];
int weight = edge[2];
graph.get(from).add(new Edge(to, weight));
indegree[to]++;
}
List<Integer> order = topologicalOrder(graph, indegree);
if (order.size() != nodeCount) {
throw new IllegalArgumentException("Input graph must be a DAG.");
}
long infinity = Long.MAX_VALUE / 4;
long[] distance = new long[nodeCount];
Arrays.fill(distance, infinity);
distance[source] = 0L;
for (int node : order) {
if (distance[node] == infinity) {
continue;
}
for (Edge edge : graph.get(node)) {
long candidate = distance[node] + edge.weight;
if (candidate < distance[edge.to]) {
distance[edge.to] = candidate;
}
}
}
return distance;
}
private static List<Integer> topologicalOrder(List<List<Edge>> graph, int[] indegree) {
Queue<Integer> queue = new ArrayDeque<>();
for (int node = 0; node < indegree.length; node++) {
if (indegree[node] == 0) {
queue.offer(node);
}
}
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int node = queue.poll();
order.add(node);
for (Edge edge : graph.get(node)) {
indegree[edge.to]--;
if (indegree[edge.to] == 0) {
queue.offer(edge.to);
}
}
}
return order;
}
}
Dry Run
Input:
- source
0 - edges:
[0, 1, 2][0, 2, 4][1, 2, -1][1, 3, 2][2, 3, 3]
One valid topological order:
0, 1, 2, 3
Process:
- start distances as
[0, inf, inf, inf] - from
0, relax to[0, 2, 4, inf] - from
1, improve node2to1and node3to4 - from
2, candidate for node3is1 + 3 = 4, so no change - final distances are
[0, 2, 1, 4]
Time and Space Complexity
Brute force:
- Time: exponential in the number of distinct source-to-node paths
- Space: path-recursion dependent
Topological shortest path:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- unreachable nodes
- negative edge weights
- graph accidentally containing a cycle
- source in a disconnected component
Common Mistakes
- forgetting to guard against relaxing from infinity
- assuming this works on arbitrary cyclic graphs
- building the topological order from the wrong edge direction
4. Complexity and Decision Guide
Across this chapter, the main trade-offs are simple:
- Kahn's algorithm:
O(V + E)time,O(V + E)space. Choose it when indegree is natural, when you want explicit cycle detection by output size, or when layer-based scheduling matters. - DFS-based topological sort:
O(V + E)time,O(V + E)space. Choose it when DFS reasoning already fits the problem or when you want direct recursion-stack cycle detection. - Shortest paths in DAGs:
O(V + E)time after topological ordering. Choose it when the graph is guaranteed to be acyclic and path weights matter.
Use this chapter's techniques when you see signals like:
- prerequisites
- dependency graph
- build order
- task order
- schedule with no cycles
- weighted DAG
Do not force topological sort when:
- the graph is undirected
- the graph can contain cycles and the task is still meaningful
- you need shortest paths in a general weighted graph rather than a DAG
A practical rule:
- if you only need a legal dependency order, use Kahn or DFS topo sort
- if the graph is a DAG and you need weighted shortest paths, use topological relaxation
- if the graph is not guaranteed to be a DAG, wait for the algorithms in the next chapter
5. Edge Cases, Pitfalls, and Debugging
Common bugs in this chapter include:
- reversing dependency edges
- forgetting to process disconnected components
- using plain
visited[]for directed cycle detection - assuming an empty queue means success in Kahn's algorithm
- treating DAG shortest-path logic as valid on a cyclic graph
Boundary and correctness checks:
- zero nodes should not crash the implementation
- isolated nodes still belong in the topological order
- self-loops are immediate cycles
- unreachable nodes in DAG shortest paths should stay at infinity
Short debugging checklist:
- verify the edge direction against the problem statement
- verify the sum of indegrees equals the number of edges
- verify Kahn's output length equals
V - verify DFS state transitions only move
0 -> 1 -> 2 - verify the topological order before relaxing shortest-path edges
- verify unreachable nodes are never used as relaxation sources
6. Practice Problems
Easy
- Title: Course Schedule. One-line prompt: decide whether all courses can be finished under prerequisite constraints. Expected pattern or core idea: cycle detection in a directed graph with Kahn or DFS.
- Title: Course Schedule II. One-line prompt: return one valid order of courses if it exists. Expected pattern or core idea: topological sorting.
- Title: Find All Possible Recipes from Given Supplies. One-line prompt: determine which recipes can be made when recipes can depend on other recipes. Expected pattern or core idea: dependency graph and Kahn's algorithm.
Medium
- Title: Parallel Courses. One-line prompt: compute the minimum number of rounds needed when any number of zero-indegree courses can be taken together. Expected pattern or core idea: Kahn's algorithm in layers.
- Title: Alien Dictionary. One-line prompt: infer a valid character order from a sorted dictionary. Expected pattern or core idea: graph construction plus topological sort.
- Title: Eventual Safe States. One-line prompt: find nodes that never lead into a directed cycle. Expected pattern or core idea: reverse graph and topological reasoning.
Hard
- Title: Parallel Courses III. One-line prompt: compute the minimum total time when each course has its own duration. Expected pattern or core idea: topological order plus dynamic programming on a DAG.
- Title: Largest Color Value in a Directed Graph. One-line prompt: maximize repeated color count along a valid path or report a cycle. Expected pattern or core idea: topological DP with cycle detection.
- Title: Longest Weighted Path in a DAG. One-line prompt: find the maximum path value in an acyclic directed graph. Expected pattern or core idea: DAG dynamic programming after topological order.
7. Short Recap
The core idea of this chapter is that DAGs turn graph traversal into valid ordering.
The most important optimization insight is that once a graph is acyclic, topological order lets you solve dependency and path problems in linear time.
The most important implementation warning is to get edge direction and directed cycle detection exactly right.
This chapter prepares the next chapter by moving from DAG-specific path reasoning to shortest-path algorithms for general weighted graphs.
8. Coverage Check
- 24.1 Directed acyclic graphs
- 24.2 Kahn's algorithm
- 24.3 DFS-based topological sort
- 24.4 Dependency ordering problems
- 24.5 Shortest paths in DAGs
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 25: Shortest Path Algorithms
25: Shortest Path Algorithms
Goal: Teach how shortest-path problems differ by edge weights, graph size, and query type, and how to choose and implement the right Java algorithm for each case.
Outcome: By the end of this chapter, you can apply Dijkstra's algorithm, Bellman-Ford, Floyd-Warshall, and 0-1 BFS correctly, and you can choose the right shortest-path algorithm from the graph constraints.
1. Intuition First
This chapter matters because "find the shortest path" is not one problem. It is a family of problems. The right algorithm depends on whether edges can be negative, whether you need one source or all pairs, and whether weights have special structure.
A simple real-world analogy is route planning:
- if all roads have nonnegative travel times, always extending the cheapest current route can be safe
- if some edges can reduce cost, greedy choices can become unsafe
- if every pair of cities matters, solving one source at a time may waste work
- if weights are only
0or1, there is a special shortcut
The core mental model is relaxation. Relaxing an edge means checking whether reaching v through u gives a better distance than the best one known so far.
The most common beginner confusion point is treating shortest-path algorithms as interchangeable. They are not. Dijkstra's algorithm fails on negative edges. Floyd-Warshall is correct for all-pairs shortest paths on small graphs, but it is too expensive on large sparse graphs. 0-1 BFS is extremely fast, but only for weights 0 and 1.
In the roadmap, the previous chapter showed that DAG structure can simplify shortest paths. This chapter removes that restriction and teaches the standard tools for general weighted graphs.
2. Core Concepts and Techniques
Concept Cluster: Dijkstra's Algorithm
Key concepts in this block:
- 25.1 Dijkstra's algorithm
Intuition
Dijkstra's algorithm repeatedly commits to the not-yet-finalized node with the smallest current distance.
Why It Matters
It is the standard tool for single-source shortest paths when all edge weights are nonnegative.
How It Works
Algorithm:
- initialize all distances to infinity except the source
- use a min-priority queue keyed by current best distance
- pop the node with smallest tentative distance
- relax all outgoing edges
- if a shorter distance is found for a neighbor, push the improved state
The key correctness idea is that once the smallest tentative distance is popped, no later path can improve it if all edge weights are nonnegative.
Java Implementation Notes
- Use
PriorityQueue<State>. - Use
long[] distance. - Skip stale queue entries where the stored distance is not the current best one.
Common Mistakes
- using Dijkstra on negative edges
- forgetting stale-entry checks
- treating the graph as undirected when the input is directed
- using
intwhen path sums may overflow
Quick Example
Edges:
0 -> 1with40 -> 2with12 -> 1with2
From source 0:
- first finalize
0 - then finalize
2with distance1 - then improve
1from4to3
Debugging Tip
Whenever Dijkstra gives a wrong result, inspect the edge weights first. A single negative edge invalidates the greedy guarantee.
Advanced Note
A simple O(V^2) version exists with arrays instead of a priority queue. It can be reasonable for dense graphs or very small V.
Concept Cluster: Bellman-Ford Algorithm
Key concepts in this block:
- 25.2 Bellman-Ford algorithm
Intuition
Bellman-Ford improves distances by edge count. After one full pass, it knows the best path using at most one edge more than before.
Why It Matters
It handles negative edge weights and can detect negative cycles reachable from the source.
How It Works
Algorithm:
- initialize distances
- repeat
V - 1times: - try relaxing every edge
- if nothing changes in a pass, stop early
- do one extra pass to detect whether any distance can still improve
If a reachable distance improves on the extra pass, there is a reachable negative cycle.
Java Implementation Notes
- An edge list is often simpler than an adjacency list here.
- Only relax an edge if the source endpoint is already reachable.
- Early stopping is a useful optimization.
Common Mistakes
- doing too few passes
- detecting negative cycles that are not reachable from the chosen source
- forgetting to guard against adding to infinity
Quick Example
Edges:
0 -> 1with41 -> 2with-20 -> 2with5
After the first pass:
- distance to
1becomes4 - distance to
2becomes2through1, not5directly
Debugging Tip
Print the full distance array after each pass. Bellman-Ford bugs are often pass-order or initialization bugs.
Advanced Note
A limited-pass Bellman-Ford pattern also appears in problems with a bound on stops or edges.
Concept Cluster: Floyd-Warshall Algorithm
Key concepts in this block:
- 25.3 Floyd-Warshall algorithm
Intuition
Floyd-Warshall asks whether allowing one more intermediate node improves any shortest path.
Why It Matters
It solves all-pairs shortest paths in a clean dynamic-programming form and works well when V is small enough for O(V^3).
How It Works
Let distance[i][j] mean the current best distance from i to j.
Then for each possible intermediate node k, update:
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
After processing all k, every shortest path that uses any subset of nodes as intermediates has been considered.
Java Implementation Notes
- Use a
long[][]matrix. - Initialize
distance[i][i] = 0. - If multiple edges exist between the same pair, keep the minimum one.
- Guard against adding infinity values.
Common Mistakes
- overflow when adding two "infinity" sentinels
- forgetting that the algorithm is naturally all-pairs, not just one source
- using it on graphs too large for
O(V^3)
Quick Example
If:
0 -> 1 = 51 -> 2 = 30 -> 2 = 20
Then when 1 is allowed as an intermediate node, 0 -> 2 improves from 20 to 8.
Debugging Tip
When one matrix entry looks wrong, inspect the exact via node that should have improved it.
Advanced Note
Negative cycles can be detected if some diagonal entry distance[i][i] becomes negative.
Concept Cluster: 0-1 BFS and Algorithm Selection
Key concepts in this block:
- 25.4 0-1 BFS
- 25.5 Choosing the right shortest-path algorithm
Intuition
If every edge weight is either 0 or 1, a deque can replace the priority queue.
Why It Matters
0-1 BFS runs in linear time and is often much faster and simpler than generic shortest-path logic for binary-weight graphs.
How It Works
0-1 BFS:
- start from the source with distance
0 - use a deque
- when relaxing a
0-weight edge, push the neighbor to the front - when relaxing a
1-weight edge, push the neighbor to the back
Algorithm choice:
- Dijkstra: nonnegative weights, single source
- Bellman-Ford: negative edges or negative-cycle detection
- Floyd-Warshall: all pairs on small or dense graphs
- 0-1 BFS: edge weights only
0and1
Java Implementation Notes
- Use
ArrayDeque<Integer>. - Do not use a normal BFS queue for weighted edges, even if the weights are small.
- Keep the same relaxation mindset as Dijkstra, just with a deque instead of a min-heap.
Common Mistakes
- applying plain BFS to
0/1weighted graphs - using Dijkstra when 0-1 BFS would be simpler and faster
- forgetting whether the problem uses
< limit,<= limit, or exact edge cost conditions
Quick Example
If:
0 -> 1costs00 -> 2costs11 -> 2costs1
Then 1 should be processed before 2, even though both are discovered from 0, because the path to 1 has lower total cost.
Debugging Tip
If 0-1 BFS behaves like ordinary BFS, check whether you always use offerLast. Zero-cost moves must go to the front.
Advanced Note
The broader idea is bucketed shortest-path processing. 0-1 BFS is the simplest and most common special case.
3. Worked Examples and Full Solutions
Worked Example 1: Single-Source Shortest Paths with Dijkstra's Algorithm
Problem Statement
Given a directed weighted graph with nonnegative edge weights and a source node, return the shortest distance from the source to every node.
Why This Example Matters
This is the default shortest-path problem when weights are nonnegative.
Constraints or Assumptions
- all edge weights are nonnegative
- the graph may be disconnected
- unreachable nodes should remain at infinity
Brute-Force Approach
Enumerate all simple paths from the source and keep the shortest one to each destination.
That is exponential and not realistic even on moderate graphs.
Better Approach
Use Dijkstra's algorithm with a min-priority queue.
Why the Better Approach Works
The next node removed from the priority queue has the smallest tentative distance. Because all remaining edges are nonnegative, no later route can beat that distance.
Pragmatic Java Choice
Use:
- an adjacency list
- a
PriorityQueueof(node, distance)states - stale-entry skipping instead of a separate finalized set
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
class DijkstraShortestPathExample {
private static final class Edge {
final int to;
final int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
private static final class State implements Comparable<State> {
final int node;
final long distance;
State(int node, long distance) {
this.node = node;
this.distance = distance;
}
@Override
public int compareTo(State other) {
return Long.compare(this.distance, other.distance);
}
}
static long[] shortestPaths(int nodeCount, int[][] edges, int source) {
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(new Edge(edge[1], edge[2]));
}
long infinity = Long.MAX_VALUE / 4;
long[] distance = new long[nodeCount];
Arrays.fill(distance, infinity);
distance[source] = 0L;
PriorityQueue<State> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(new State(source, 0L));
while (!priorityQueue.isEmpty()) {
State current = priorityQueue.poll();
if (current.distance != distance[current.node]) {
continue;
}
for (Edge edge : graph.get(current.node)) {
long candidate = current.distance + edge.weight;
if (candidate < distance[edge.to]) {
distance[edge.to] = candidate;
priorityQueue.offer(new State(edge.to, candidate));
}
}
}
return distance;
}
}
Dry Run
Input:
- source
0 - edges:
[0, 1, 4][0, 2, 1][2, 1, 2][1, 3, 1][2, 3, 5][3, 4, 3]
Process:
- start with distances
[0, inf, inf, inf, inf] - pop
0, relax to[0, 4, 1, inf, inf] - pop
2, improve1to3, set3to6 - pop
1, improve3to4 - pop
3, set4to7
Final distances:
[0, 3, 1, 4, 7]
Time and Space Complexity
Brute force:
- Time: exponential
- Space: path-recursion dependent
Dijkstra with priority queue:
- Time:
O((V + E) log V) - Space:
O(V + E)
Edge Cases
- unreachable nodes
- multiple edges between the same pair
- zero-weight edges
- source with no outgoing edges
Common Mistakes
- using Dijkstra on a graph with negative edges
- failing to skip stale priority-queue entries
- forgetting whether the graph is directed or undirected
Worked Example 2: Negative Edges and Cycle Detection with Bellman-Ford
Problem Statement
Given a directed weighted graph and a source node, compute shortest distances and report whether a negative cycle is reachable from the source.
Why This Example Matters
This is the standard fallback when negative weights appear.
Constraints or Assumptions
- edge weights may be negative
- the graph may be disconnected
- only negative cycles reachable from the source matter for the returned answer
Brute-Force Approach
Enumerate all simple source-to-destination paths and take the minimum path weight.
That is again exponential and gives no clean way to reason about negative cycles.
Better Approach
Use Bellman-Ford on the edge list.
Why the Better Approach Works
After k passes, Bellman-Ford has considered all shortest paths that use at most k edges. Any simple shortest path uses at most V - 1 edges. If an extra pass still improves a reachable distance, some cycle must be reducing cost.
Pragmatic Java Choice
Use:
- an edge list instead of nested adjacency traversal
long[] distance- early stopping when a pass makes no changes
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class BellmanFordExample {
private static final class Edge {
final int from;
final int to;
final int weight;
Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
static final class Result {
final long[] distance;
final boolean hasReachableNegativeCycle;
Result(long[] distance, boolean hasReachableNegativeCycle) {
this.distance = distance;
this.hasReachableNegativeCycle = hasReachableNegativeCycle;
}
}
static Result shortestPaths(int nodeCount, int[][] edgesArray, int source) {
List<Edge> edges = new ArrayList<>();
for (int[] edge : edgesArray) {
edges.add(new Edge(edge[0], edge[1], edge[2]));
}
long infinity = Long.MAX_VALUE / 4;
long[] distance = new long[nodeCount];
Arrays.fill(distance, infinity);
distance[source] = 0L;
for (int pass = 1; pass <= nodeCount - 1; pass++) {
boolean changed = false;
for (Edge edge : edges) {
if (distance[edge.from] == infinity) {
continue;
}
long candidate = distance[edge.from] + edge.weight;
if (candidate < distance[edge.to]) {
distance[edge.to] = candidate;
changed = true;
}
}
if (!changed) {
break;
}
}
boolean hasReachableNegativeCycle = false;
for (Edge edge : edges) {
if (distance[edge.from] == infinity) {
continue;
}
if (distance[edge.from] + edge.weight < distance[edge.to]) {
hasReachableNegativeCycle = true;
break;
}
}
return new Result(distance, hasReachableNegativeCycle);
}
}
Dry Run
Input:
- source
0 - edges:
[0, 1, 4][0, 2, 5][1, 2, -2][2, 3, 3][1, 3, 6]
Pass 1:
distance[1] = 4distance[2] = 5- then improve
distance[2]to2through1 - set
distance[3] = 5through2
Pass 2:
- no further improvement
Final distances:
[0, 4, 2, 5]
Extra pass:
- no change, so no reachable negative cycle
Time and Space Complexity
Brute force:
- Time: exponential
- Space: path-recursion dependent
Bellman-Ford:
- Time:
O(VE) - Space:
O(V + E)
Edge Cases
- negative edges but no negative cycle
- negative cycle unreachable from the source
- self-loop with negative weight
- disconnected nodes
Common Mistakes
- forgetting the extra pass for negative-cycle detection
- treating every negative edge as a negative cycle
- relaxing from nodes that are still unreachable
Worked Example 3: All-Pairs Shortest Paths with Floyd-Warshall
Problem Statement
Given a directed weighted graph with nodeCount nodes, compute the shortest distance between every ordered pair of nodes.
Why This Example Matters
Some problems ask many shortest-path queries across the same graph. Running a single-source algorithm over and over may be the wrong abstraction.
Constraints or Assumptions
- graph size should be small enough for
O(V^3) - edge weights may be negative if there is no relevant negative cycle
- multiple edges between the same nodes may exist
Brute-Force Approach
Run a single-source shortest-path algorithm separately from every source node.
That can work, but it repeats setup and reasoning for each source. Floyd-Warshall is often cleaner when all pairs matter and V is small.
Better Approach
Use Floyd-Warshall dynamic programming.
Why the Better Approach Works
At step k, the algorithm decides whether paths are better when they are allowed to go through node k as an intermediate. After all k, every possible intermediate set has been considered.
Pragmatic Java Choice
Use:
- a
long[][] distancematrix - a large infinity sentinel
- direct initialization from the edge list
Java Solution
import java.util.Arrays;
class FloydWarshallExample {
static long[][] allPairsShortestPaths(int nodeCount, int[][] edges) {
long infinity = Long.MAX_VALUE / 4;
long[][] distance = new long[nodeCount][nodeCount];
for (int from = 0; from < nodeCount; from++) {
Arrays.fill(distance[from], infinity);
distance[from][from] = 0L;
}
for (int[] edge : edges) {
int from = edge[0];
int to = edge[1];
int weight = edge[2];
distance[from][to] = Math.min(distance[from][to], weight);
}
for (int via = 0; via < nodeCount; via++) {
for (int from = 0; from < nodeCount; from++) {
if (distance[from][via] == infinity) {
continue;
}
for (int to = 0; to < nodeCount; to++) {
if (distance[via][to] == infinity) {
continue;
}
long candidate = distance[from][via] + distance[via][to];
if (candidate < distance[from][to]) {
distance[from][to] = candidate;
}
}
}
}
return distance;
}
static boolean hasNegativeCycle(long[][] distance) {
for (int node = 0; node < distance.length; node++) {
if (distance[node][node] < 0) {
return true;
}
}
return false;
}
}
Dry Run
Input edges:
[0, 1, 5][1, 2, 3][2, 3, 1][0, 3, 10]
Initial key entries:
distance[0][3] = 10distance[0][1] = 5distance[1][2] = 3distance[2][3] = 1
When via = 1:
distance[0][2]improves from infinity to8
When via = 2:
distance[0][3]improves from10to9distance[1][3]becomes4
Time and Space Complexity
Brute-force repeated single-source approach:
- Time: depends on the chosen single-source algorithm
- Space: depends on that algorithm
Floyd-Warshall:
- Time:
O(V^3) - Space:
O(V^2)
Edge Cases
- multiple edges between the same pair
- unreachable pairs
- negative edges
- negative cycles, detectable by a negative diagonal entry
Common Mistakes
- forgetting to keep the minimum direct edge
- overflow from adding two infinity values
- using Floyd-Warshall on graphs too large for cubic time
Worked Example 4: Binary-Weight Shortest Paths with 0-1 BFS
Problem Statement
Given a directed graph where every edge weight is either 0 or 1, compute the shortest distance from a source node to every node.
Why This Example Matters
It teaches a specialized but extremely useful optimization. Many interview problems hide 0/1 weights behind costs like free moves versus paid moves.
Constraints or Assumptions
- every edge weight is exactly
0or1 - the graph may be disconnected
- the graph may be directed or undirected depending on the problem statement
Brute-Force Approach
Use Dijkstra's algorithm with a priority queue.
That is correct, but it does more work than needed because the weights have only two possibilities.
Better Approach
Use 0-1 BFS with a deque.
Why the Better Approach Works
A 0-cost move should be processed before any pending 1-cost move at the same current distance frontier. A deque is enough to maintain that order.
Pragmatic Java Choice
Use:
- an adjacency list
- an
ArrayDeque<Integer> - a
long[] distancearray
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
class ZeroOneBfsExample {
private static final class Edge {
final int to;
final int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
static long[] shortestPaths(int nodeCount, int[][] edges, int source) {
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(new Edge(edge[1], edge[2]));
}
long infinity = Long.MAX_VALUE / 4;
long[] distance = new long[nodeCount];
Arrays.fill(distance, infinity);
distance[source] = 0L;
Deque<Integer> deque = new ArrayDeque<>();
deque.offerFirst(source);
while (!deque.isEmpty()) {
int node = deque.pollFirst();
for (Edge edge : graph.get(node)) {
long candidate = distance[node] + edge.weight;
if (candidate < distance[edge.to]) {
distance[edge.to] = candidate;
if (edge.weight == 0) {
deque.offerFirst(edge.to);
} else {
deque.offerLast(edge.to);
}
}
}
}
return distance;
}
}
Dry Run
Input:
- source
0 - edges:
[0, 1, 0][0, 2, 1][1, 2, 1][1, 3, 0][3, 4, 1]
Process:
- start with deque
[0] - pop
0, set1to0and push front, set2to1and push back - deque is now
[1, 2] - pop
1, set3to0and push front - deque is now
[3, 2] - pop
3, set4to1
Final distances:
[0, 0, 1, 0, 1]
Time and Space Complexity
Dijkstra baseline:
- Time:
O((V + E) log V) - Space:
O(V + E)
0-1 BFS:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- source isolated from the rest of the graph
- multiple
0-cost edges - graph containing an accidental weight other than
0or1 - directed versus undirected interpretation
Common Mistakes
- using a normal queue instead of a deque
- pushing zero-cost neighbors to the back
- assuming a node should be processed only once without checking distance improvements
4. Complexity and Decision Guide
The main trade-offs in this chapter are:
- Dijkstra's algorithm:
O((V + E) log V). Choose it for single-source shortest paths with nonnegative edges. - Bellman-Ford algorithm:
O(VE). Choose it when negative edges exist or when reachable negative-cycle detection matters. - Floyd-Warshall algorithm:
O(V^3). Choose it when all-pairs answers matter andVis small enough. - 0-1 BFS:
O(V + E). Choose it when every edge weight is0or1.
Recognition signals:
- "nonnegative weighted graph" suggests Dijkstra
- "negative edges" suggests Bellman-Ford
- "all pairs" or "many source-target queries on a small graph" suggests Floyd-Warshall
- "free move versus paid move" or "binary weights" suggests 0-1 BFS
Signals not to force a technique:
- do not use Dijkstra with negative edges
- do not use Floyd-Warshall on large sparse graphs
- do not use plain BFS when weights are not all equal
- do not use Bellman-Ford by default when all weights are nonnegative and performance matters
A practical rule:
- first inspect the edge-weight restrictions
- then inspect whether the task is single-source or all-pairs
- then inspect graph size
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- wrong infinity initialization
- overflow when adding to infinity
- mixing directed and undirected interpretations
- forgetting stale-entry handling in Dijkstra
- forgetting the extra Bellman-Ford pass
- using the wrong push side in 0-1 BFS
Boundary handling:
- unreachable nodes should remain at infinity
- zero-weight edges are legal for Dijkstra and important for 0-1 BFS
- negative self-loops are immediate reachable negative cycles if the source can reach them
- Floyd-Warshall should start with
distance[i][i] = 0
Short debugging checklist:
- verify edge-weight assumptions before choosing the algorithm
- verify the source starts with distance
0 - verify relaxations only come from reachable states
- verify Dijkstra never sees a negative edge
- verify Bellman-Ford runs at most
V - 1full passes before cycle check - verify Floyd-Warshall guards infinity before addition
- verify 0-1 BFS pushes weight
0edges to the front
6. Practice Problems
Easy
- Title: Cheapest Path in a Nonnegative Directed Graph. One-line prompt: compute shortest distances from one source when every edge cost is nonnegative. Expected pattern or core idea: Dijkstra's algorithm.
- Title: Minimum Edge Reversals to Reach Destination. One-line prompt: follow existing directed edges for cost
0and reverse an edge for cost1. Expected pattern or core idea: 0-1 BFS. - Title: Dense City Map Queries. One-line prompt: answer many shortest-path queries between all city pairs in a small graph. Expected pattern or core idea: Floyd-Warshall.
Medium
- Title: Network Delay Time. One-line prompt: compute how long it takes a signal to reach all nodes from one source. Expected pattern or core idea: Dijkstra's algorithm.
- Title: Cheapest Flights Within K Stops. One-line prompt: find the minimum flight cost with a bound on the number of edges used. Expected pattern or core idea: limited-pass Bellman-Ford style relaxation.
- Title: Path With Minimum Effort. One-line prompt: minimize the maximum step cost across a grid path. Expected pattern or core idea: Dijkstra on an implicit weighted graph.
Hard
- Title: Detect Arbitrage or Negative Cycle in an Exchange Graph. One-line prompt: determine whether repeated exchanges can reduce cost without bound. Expected pattern or core idea: Bellman-Ford negative-cycle detection.
- Title: Minimum Cost to Make at Least One Valid Path in a Grid. One-line prompt: move freely along suggested directions and pay to deviate. Expected pattern or core idea: 0-1 BFS.
- Title: All-Pairs Routing Table for a Small Dense Network. One-line prompt: precompute shortest distances for every ordered pair. Expected pattern or core idea: Floyd-Warshall.
7. Short Recap
The core idea of this chapter is that shortest-path problems must be classified before they are solved.
The most important optimization insight is to match the algorithm to edge-weight structure:
- nonnegative weights: Dijkstra
- negative edges: Bellman-Ford
- all pairs: Floyd-Warshall
- weights
0/1: 0-1 BFS
The most important implementation warning is that Dijkstra's algorithm is not safe with negative edges.
This chapter prepares the next chapter by moving from shortest routes between nodes to the cheapest way to connect an entire graph.
8. Coverage Check
- 25.1 Dijkstra's algorithm
- 25.2 Bellman-Ford algorithm
- 25.3 Floyd-Warshall algorithm
- 25.4 0-1 BFS
- 25.5 Choosing the right shortest-path algorithm
Coverage Summary: 5/5 official subtopics covered
This must always be 5/5 before final output
Next: 26: Minimum Spanning Tree and Disjoint Set Union
26: Minimum Spanning Tree and Disjoint Set Union
Goal: Teach how to connect an undirected weighted graph as cheaply as possible, and how Disjoint Set Union supports greedy MST construction and fast connectivity reasoning in Java.
Outcome: By the end of this chapter, you can explain the greedy view of minimum spanning trees, implement Kruskal's and Prim's algorithms, build DSU with path compression and union by rank, and solve connectivity and offline query problems efficiently.
1. Intuition First
This chapter matters because many graph problems are not about finding a best path from one source. They are about connecting everything as cheaply as possible.
A simple real-world analogy is laying network cable between offices:
- every cable has a cost
- all offices must become connected
- using extra cables that create cycles wastes money unless they help some other goal
- the cheapest fully connected network is a minimum spanning tree
The core mental model is this:
- a spanning tree connects all nodes with exactly
V - 1edges and no cycle - a minimum spanning tree, or MST, is the spanning tree with minimum total edge weight
- DSU tracks which nodes are already in the same connected component, so greedy algorithms can avoid creating cycles cheaply
The most common beginner confusion point is mixing up shortest paths and MSTs. A shortest-path tree minimizes distance from one source. An MST minimizes total connection cost across the whole graph. These goals are different.
In the roadmap, the previous chapter focused on path cost between nodes. This chapter shifts to graph-wide connectivity and introduces DSU, which will remain useful far beyond MST problems.
2. Core Concepts and Techniques
Concept Cluster: Greedy View of MSTs and Kruskal's Algorithm
Key concepts in this block:
- 26.1 Greedy view of minimum spanning trees
- 26.2 Kruskal's algorithm
Intuition
Kruskal's algorithm grows the MST by taking the cheapest safe edge available.
Why It Matters
It is one of the cleanest greedy algorithms in graph theory and a standard use case for DSU.
How It Works
Greedy view:
- sort edges by weight from smallest to largest
- consider them in that order
- take an edge only if it connects two different components
- skip it if it would create a cycle
- stop after taking
V - 1edges
The correctness idea is that choosing the lightest safe edge cannot hurt the final answer.
Java Implementation Notes
- Kruskal works naturally from an edge list.
- Sorting dominates the running time.
- DSU is the right structure for "same component?" checks.
Common Mistakes
- using Kruskal on a directed graph
- forgetting to stop after
V - 1chosen edges - checking cycle formation with DFS each time instead of DSU
Quick Example
Edges:
(0, 1, 1)(1, 2, 2)(0, 2, 3)(1, 3, 4)
Kruskal takes:
- weight
1 - weight
2 - skips weight
3because it creates a cycle - takes weight
4
Debugging Tip
Track the number of successful unions. In a connected graph, it must end at exactly V - 1.
Advanced Note
The cut-property proof explains why the cheapest crossing edge of a cut is always safe, but for implementation you mostly need to remember "take the cheapest edge that connects different components."
Concept Cluster: Prim's Algorithm
Key concepts in this block:
- 26.3 Prim's algorithm
Intuition
Prim's algorithm grows one connected tree outward from a starting node, always adding the cheapest edge that connects the current tree to a new node.
Why It Matters
Prim's algorithm is often the most natural choice when the graph is already stored as adjacency lists or adjacency matrices.
How It Works
Algorithm:
- start from any node
- keep a priority queue of edges crossing from the built tree to outside nodes
- repeatedly choose the cheapest such edge
- add the new node to the tree
- push its outgoing edges
This is greedy like Dijkstra in structure, but the meaning is different:
- Dijkstra chooses the next cheapest path from a source
- Prim chooses the next cheapest edge that expands the tree
Java Implementation Notes
- Use an adjacency list for sparse graphs.
- Use a
PriorityQueuekeyed by edge weight. - Skip nodes already included in the MST.
Common Mistakes
- confusing shortest distance with cheapest connecting edge
- forgetting to add both directions for an undirected graph
- returning a cost even when the graph is disconnected
Quick Example
If the current tree contains nodes {0, 1} and the crossing edges have weights 3, 5, and 7, Prim must choose the edge of weight 3, even if some other edge elsewhere in the graph is cheaper but does not touch the current tree.
Debugging Tip
Count how many nodes have been added to the tree. A connected graph must finish with all V nodes included.
Advanced Note
A matrix-based O(V^2) Prim implementation can be good for dense graphs.
Concept Cluster: Find, Union, and DSU Optimizations
Key concepts in this block:
- 26.4 Find and union operations
- 26.5 Path compression and union by rank
Intuition
DSU keeps track of which nodes belong to the same component as edges are added over time.
Why It Matters
Without DSU, many graph algorithms keep rechecking connectivity from scratch. DSU turns that repeated work into almost constant-time updates and queries.
How It Works
Core operations:
find(x): return the representative of the component containingxunion(a, b): merge the components ofaandbif they differ
Optimizations:
- path compression shortens parent chains during
find - union by rank attaches the shallower tree under the deeper one
Together these make DSU operations very fast in practice.
Java Implementation Notes
- Store
parent[]andrank[]. - Initialize
parent[i] = i. - A successful
unionis the right place to decrement a component counter if one is being tracked.
Common Mistakes
- forgetting to use
findbefore comparing or merging - updating rank incorrectly
- decrementing the component count even when the nodes were already connected
Quick Example
If:
union(0, 1)union(1, 2)
Then find(0) and find(2) should return the same representative.
Debugging Tip
After a few unions, print parent[] and a few find() results. If equal components still have different representatives, path compression or root attachment is wrong.
Advanced Note
The amortized complexity is often written as O(alpha(V)), where alpha is the inverse Ackermann function. In practice, that is effectively constant.
Concept Cluster: Connectivity and Offline Query Problems
Key concepts in this block:
- 26.6 Connectivity and offline query problems
Intuition
Sometimes queries ask whether two nodes are connected under a condition, such as "only use edges lighter than this limit." If queries are processed in sorted order, DSU can reuse work instead of rebuilding the graph every time.
Why It Matters
This pattern appears in threshold queries, batched connectivity checks, and some dynamic-style graph problems.
How It Works
Offline approach:
- sort edges by the condition that makes them usable
- sort queries by the same threshold
- sweep from small to large threshold
- union edges as soon as they become allowed
- answer each query by checking whether its endpoints now have the same representative
Java Implementation Notes
- Store original query indices so answers can be written back in input order.
Arrays.sorton helper objects keeps the code readable.- Offline means you are allowed to reorder the processing, even though you return answers in the original order.
Common Mistakes
- confusing
< limitwith<= limit - forgetting to restore answer order
- rebuilding DSU for every query and losing the whole optimization
Quick Example
If edges of weight less than 5 are allowed, then you union only edges with weights 1, 2, 3, and 4 before answering that query.
Debugging Tip
Print the edge pointer and current threshold while sweeping. Many offline bugs come from one wrong comparison operator.
Advanced Note
This is one reason DSU appears in many problems that do not even mention MSTs.
3. Worked Examples and Full Solutions
Worked Example 1: Minimum Spanning Tree with Kruskal's Algorithm
Problem Statement
Given an undirected weighted graph with nodeCount nodes and edges [u, v, weight], return the total weight of its minimum spanning tree. If the graph is disconnected, return -1.
Why This Example Matters
This is the standard MST problem and the classic place where DSU becomes necessary.
Constraints or Assumptions
- the graph is undirected
- the graph may be disconnected
- edge weights may repeat
- multiple MSTs may exist
Brute-Force Approach
Check every subset of exactly V - 1 edges, keep only those that form a spanning tree, and take the minimum total weight.
This is combinatorial and immediately too slow.
Better Approach
Sort the edges and run Kruskal's algorithm with DSU.
Why the Better Approach Works
At each step, the cheapest edge connecting two different components is safe to include. DSU makes the "different components?" test fast.
Pragmatic Java Choice
Use:
- a sortable edge list
- DSU with path compression and union by rank
- a running count of how many edges have been chosen
Java Solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class KruskalMstExample {
private static final class Edge {
final int from;
final int to;
final int weight;
Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
private static final class DisjointSetUnion {
private final int[] parent;
private final int[] rank;
DisjointSetUnion(int size) {
this.parent = new int[size];
this.rank = new int[size];
for (int node = 0; node < size; node++) {
parent[node] = node;
}
}
int find(int node) {
if (parent[node] != node) {
parent[node] = find(parent[node]);
}
return parent[node];
}
boolean union(int first, int second) {
int rootFirst = find(first);
int rootSecond = find(second);
if (rootFirst == rootSecond) {
return false;
}
if (rank[rootFirst] < rank[rootSecond]) {
parent[rootFirst] = rootSecond;
} else if (rank[rootFirst] > rank[rootSecond]) {
parent[rootSecond] = rootFirst;
} else {
parent[rootSecond] = rootFirst;
rank[rootFirst]++;
}
return true;
}
}
static long minimumSpanningTreeCost(int nodeCount, int[][] edgesArray) {
if (nodeCount == 0) {
return 0L;
}
List<Edge> edges = new ArrayList<>();
for (int[] edge : edgesArray) {
edges.add(new Edge(edge[0], edge[1], edge[2]));
}
edges.sort(Comparator.comparingInt(edge -> edge.weight));
DisjointSetUnion dsu = new DisjointSetUnion(nodeCount);
long totalCost = 0L;
int chosenEdges = 0;
for (Edge edge : edges) {
if (dsu.union(edge.from, edge.to)) {
totalCost += edge.weight;
chosenEdges++;
if (chosenEdges == nodeCount - 1) {
break;
}
}
}
return chosenEdges == nodeCount - 1 ? totalCost : -1L;
}
}
Dry Run
Edges:
[0, 1, 1][1, 2, 2][0, 2, 3][1, 3, 4][2, 3, 5]
Sorted by weight:
1, 2, 3, 4, 5
Process:
- take
[0, 1, 1] - take
[1, 2, 2] - skip
[0, 2, 3]because0and2are already connected - take
[1, 3, 4]
Total MST cost:
1 + 2 + 4 = 7
Time and Space Complexity
Brute force:
- Time: combinatorial in the number of edges
- Space: subset bookkeeping dependent
Kruskal with DSU:
- Time:
O(E log E) - Space:
O(V + E)
Edge Cases
- disconnected graph
- duplicate edges between the same pair
- negative or zero edge weights
- self-loops, which should never help the MST
Common Mistakes
- forgetting that MSTs are for undirected graphs
- returning a cost before checking that
V - 1edges were chosen - not using DSU roots when testing connectivity
Worked Example 2: Minimum Spanning Tree with Prim's Algorithm
Problem Statement
Given an undirected weighted graph, return the total weight of its minimum spanning tree using Prim's algorithm. Return -1 if the graph is disconnected.
Why This Example Matters
It gives a second MST construction strategy and highlights the contrast between edge-list-first and adjacency-first thinking.
Constraints or Assumptions
- the graph is undirected
- the graph may be disconnected
- any start node is acceptable
Brute-Force Approach
Build the tree one node at a time by scanning all graph edges repeatedly to find the cheapest edge leaving the current tree.
That works conceptually, but it wastes work because it keeps rescanning edges that have already been considered.
Better Approach
Use Prim's algorithm with an adjacency list and a min-priority queue.
Why the Better Approach Works
The priority queue always exposes the cheapest edge crossing from the built tree to an outside node. That is exactly the next safe greedy choice.
Pragmatic Java Choice
Use:
- an undirected adjacency list
- a
PriorityQueue<State>keyed by edge weight - a boolean array to mark nodes already included in the MST
Java Solution
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
class PrimMstExample {
private static final class Edge {
final int to;
final int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
private static final class State implements Comparable<State> {
final int node;
final int edgeWeight;
State(int node, int edgeWeight) {
this.node = node;
this.edgeWeight = edgeWeight;
}
@Override
public int compareTo(State other) {
return Integer.compare(this.edgeWeight, other.edgeWeight);
}
}
static long minimumSpanningTreeCost(int nodeCount, int[][] edgesArray) {
if (nodeCount == 0) {
return 0L;
}
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edgesArray) {
int first = edge[0];
int second = edge[1];
int weight = edge[2];
graph.get(first).add(new Edge(second, weight));
graph.get(second).add(new Edge(first, weight));
}
boolean[] used = new boolean[nodeCount];
PriorityQueue<State> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(new State(0, 0));
long totalCost = 0L;
int usedCount = 0;
while (!priorityQueue.isEmpty() && usedCount < nodeCount) {
State current = priorityQueue.poll();
if (used[current.node]) {
continue;
}
used[current.node] = true;
usedCount++;
totalCost += current.edgeWeight;
for (Edge edge : graph.get(current.node)) {
if (!used[edge.to]) {
priorityQueue.offer(new State(edge.to, edge.weight));
}
}
}
return usedCount == nodeCount ? totalCost : -1L;
}
}
Dry Run
Use the same graph as before.
Start:
- tree contains only node
0 - queue contains edges leaving
0
Process:
- choose edge
(0, 1, 1), total becomes1 - from nodes
{0, 1}, cheapest crossing edge is(1, 2, 2), total becomes3 - from nodes
{0, 1, 2}, cheapest crossing edge is(1, 3, 4), total becomes7
All nodes are now connected.
Time and Space Complexity
Repeated full-edge scanning baseline:
- Time: often
O(VE)in simple implementations - Space:
O(V + E)
Prim with priority queue:
- Time:
O(E log V) - Space:
O(V + E)
Edge Cases
- disconnected graph
- one-node graph
- duplicate edges
- large weight values
Common Mistakes
- forgetting to add both directions to the adjacency list
- counting the starting node's fake edge weight incorrectly
- confusing Prim's greedy choice with Dijkstra's distance logic
Worked Example 3: Offline Connectivity Queries with DSU
Problem Statement
You are given an undirected weighted graph and many queries of the form [u, v, limit]. For each query, decide whether u and v are connected using only edges with weight strictly less than limit.
Why This Example Matters
It shows how DSU goes beyond MSTs and solves batched connectivity problems by reusing work across sorted queries.
Constraints or Assumptions
- the graph is undirected
- queries can be processed offline
- connectivity uses only edges with weight
< limit
Brute-Force Approach
For each query:
- build or filter the graph using only edges below the limit
- run BFS or DFS from
u - check whether
vis reachable
That repeats nearly the same work for every query.
Better Approach
Sort edges by weight, sort queries by limit, and union edges incrementally with DSU.
Why the Better Approach Works
As query limits increase, the set of allowed edges only grows. So each edge needs to be added at most once. DSU keeps connectivity up to date cheaply.
Pragmatic Java Choice
Use:
- helper objects for edges and queries
Arrays.sort- DSU with path compression and union by rank
Java Solution
import java.util.Arrays;
import java.util.Comparator;
class OfflineConnectivityQueriesExample {
private static final class Edge {
final int from;
final int to;
final int weight;
Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
private static final class Query {
final int from;
final int to;
final int limit;
final int index;
Query(int from, int to, int limit, int index) {
this.from = from;
this.to = to;
this.limit = limit;
this.index = index;
}
}
private static final class DisjointSetUnion {
private final int[] parent;
private final int[] rank;
DisjointSetUnion(int size) {
this.parent = new int[size];
this.rank = new int[size];
for (int node = 0; node < size; node++) {
parent[node] = node;
}
}
int find(int node) {
if (parent[node] != node) {
parent[node] = find(parent[node]);
}
return parent[node];
}
void union(int first, int second) {
int rootFirst = find(first);
int rootSecond = find(second);
if (rootFirst == rootSecond) {
return;
}
if (rank[rootFirst] < rank[rootSecond]) {
parent[rootFirst] = rootSecond;
} else if (rank[rootFirst] > rank[rootSecond]) {
parent[rootSecond] = rootFirst;
} else {
parent[rootSecond] = rootFirst;
rank[rootFirst]++;
}
}
}
static boolean[] distanceLimitedPathsExist(int nodeCount, int[][] edgesArray, int[][] queriesArray) {
Edge[] edges = new Edge[edgesArray.length];
for (int i = 0; i < edgesArray.length; i++) {
edges[i] = new Edge(edgesArray[i][0], edgesArray[i][1], edgesArray[i][2]);
}
Arrays.sort(edges, Comparator.comparingInt(edge -> edge.weight));
Query[] queries = new Query[queriesArray.length];
for (int i = 0; i < queriesArray.length; i++) {
queries[i] = new Query(queriesArray[i][0], queriesArray[i][1], queriesArray[i][2], i);
}
Arrays.sort(queries, Comparator.comparingInt(query -> query.limit));
boolean[] answer = new boolean[queriesArray.length];
DisjointSetUnion dsu = new DisjointSetUnion(nodeCount);
int edgeIndex = 0;
for (Query query : queries) {
while (edgeIndex < edges.length && edges[edgeIndex].weight < query.limit) {
dsu.union(edges[edgeIndex].from, edges[edgeIndex].to);
edgeIndex++;
}
answer[query.index] = dsu.find(query.from) == dsu.find(query.to);
}
return answer;
}
}
Dry Run
Edges:
[0, 1, 2][1, 2, 4][2, 3, 6][0, 3, 10]
Queries:
[0, 2, 5][0, 3, 5][0, 3, 11]
Sort by limit:
- limit
5 - limit
5 - limit
11
Sweep:
- before limit
5, union edges of weights2and4 - now
0and2are connected, so first query istrue 0and3are not yet connected, so second query isfalse- before limit
11, also union weights6and10 - now
0and3are connected, so third query istrue
Time and Space Complexity
Per-query BFS baseline:
- Time: roughly
O(Q(V + E)) - Space: graph and traversal dependent
Offline DSU approach:
- Time:
O(E log E + Q log Q + (E + Q) * alpha(V)) - Space:
O(V + E + Q)
Edge Cases
- query endpoints already equal
- disconnected graph
- duplicate edges with different weights
- strict inequality
< limitversus non-strict inequality<= limit
Common Mistakes
- sorting queries but forgetting their original indices
- using the wrong threshold comparison
- rebuilding DSU per query and losing the main optimization
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- Kruskal's algorithm:
O(E log E). Choose it when the graph is naturally given as an edge list or when DSU reasoning is already central. - Prim's algorithm with a priority queue:
O(E log V). Choose it when the graph is already stored as adjacency lists and you want to grow one tree directly. - DSU operations with path compression and union by rank: effectively near-constant amortized time. Choose DSU when the core question is "are these nodes already connected?"
- Offline connectivity with DSU: sorting plus near-constant unions and finds. Choose it when many connectivity queries can be reordered.
Recognition signals:
- "connect all nodes with minimum total cost" suggests MST
- "avoid cycles while taking cheap edges" suggests Kruskal
- "grow the tree from one seed" suggests Prim
- "many union/find or connectivity checks" suggests DSU
- "many threshold queries" suggests offline DSU
Signals not to force a technique:
- do not use MST when the problem is really shortest path from one source
- do not use DSU when you need actual path reconstruction
- do not use Prim or Kruskal on directed graphs as if nothing changed
- do not process offline queries online if the problem forbids reordering
A practical rule:
- MST goal means Kruskal or Prim
- repeated connectivity goal means DSU
- thresholded batch connectivity goal means offline DSU
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- forgetting the graph is undirected
- accepting self-loops into the MST
- returning an MST cost on a disconnected graph
- decrementing component count on failed unions
- forgetting path compression inside
find - getting the offline threshold comparison wrong
Boundary handling:
nodeCount = 0should not crashnodeCount = 1has MST cost0- duplicate edges are legal and should be handled naturally
- negative edge weights can still appear in an MST problem
Short debugging checklist:
- verify that undirected edges are added in both directions for Prim
- verify Kruskal counts exactly successful unions
- verify
find(find(x)) == find(x)after compression - verify component merges only happen when roots differ
- verify disconnected graphs return
-1for MST - verify offline query answers are restored to original order
6. Practice Problems
Easy
- Title: Redundant Connection. One-line prompt: return the edge that first creates a cycle in an undirected graph. Expected pattern or core idea: DSU cycle detection.
- Title: Number of Connected Components in an Undirected Graph. One-line prompt: count how many components remain after processing all edges. Expected pattern or core idea: DSU or traversal.
- Title: Connecting Cities with Minimum Cost. One-line prompt: connect all cities as cheaply as possible or report impossibility. Expected pattern or core idea: Kruskal's algorithm.
Medium
- Title: Min Cost to Connect All Points. One-line prompt: connect all points using edge costs based on coordinate distance. Expected pattern or core idea: Prim or Kruskal MST.
- Title: Number of Operations to Make Network Connected. One-line prompt: decide whether spare cables can connect all computers and count the needed operations. Expected pattern or core idea: DSU component counting.
- Title: Accounts Merge. One-line prompt: merge records that share identifiers. Expected pattern or core idea: DSU on entities linked by shared keys.
Hard
- Title: Checking Existence of Edge Length Limited Paths. One-line prompt: answer many connectivity queries under edge-weight limits. Expected pattern or core idea: offline DSU.
- Title: Optimize Water Distribution in a Village. One-line prompt: choose wells and pipes to minimize total cost. Expected pattern or core idea: MST with a virtual node.
- Title: Critical and Pseudo-Critical Edges in Minimum Spanning Tree. One-line prompt: classify edges by how essential they are to MST construction. Expected pattern or core idea: repeated Kruskal reasoning.
7. Short Recap
The core idea of this chapter is that graph-wide cheapest connectivity is different from shortest paths.
The most important optimization insight is that DSU turns cycle checks and connectivity checks into very cheap operations, which makes Kruskal and many offline query solutions practical.
The most important implementation warning is to keep the graph undirected where appropriate and to union only by component representatives.
This chapter prepares the next chapter by moving from global graph connectivity to deeper structural analysis inside directed and undirected graphs.
8. Coverage Check
- 26.1 Greedy view of minimum spanning trees
- 26.2 Kruskal's algorithm
- 26.3 Prim's algorithm
- 26.4 Find and union operations
- 26.5 Path compression and union by rank
- 26.6 Connectivity and offline query problems
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 27: Strongly Connected Components, Bridges, and Articulation Points
27: Strongly Connected Components, Bridges, and Articulation Points
Goal: Teach how to analyze graph structure under failure, using SCC decomposition in directed graphs and low-link reasoning for bridges and articulation points in undirected graphs.
Outcome: By the end of this chapter, you can find strongly connected components with Kosaraju's and Tarjan's algorithms, identify bridges and articulation points with low-link values, and explain what these structures mean for graph resilience.
1. Intuition First
This chapter matters because many graph problems are not only about reachability or minimum cost. Sometimes the real question is structural:
- which vertices mutually depend on each other
- which edge is a single point of failure
- which vertex disconnects the network if it fails
A simple real-world analogy is a company network:
- a strongly connected component is a group of services that can all call each other through some chain
- a bridge is a single cable whose removal splits the network
- an articulation point is a router whose failure disconnects parts of the system
The core mental model is depth-first search plus structural timestamps. DFS gives a tree. Low-link reasoning tells us whether a subtree can reconnect to an earlier part of the graph without using its parent edge.
The most common beginner confusion point is mixing directed and undirected settings:
- SCCs are a directed-graph concept
- bridges and articulation points are usually defined on undirected graphs
- the low-link idea appears in both, but the exact condition changes
This chapter closes Part V. The earlier graph chapters taught traversal, shortest paths, and spanning trees. This chapter shifts from "how do I move through the graph?" to "what structural pieces hold the graph together?" That prepares the transition into Part VI, where correctness arguments matter more than surface pattern matching.
2. Core Concepts and Techniques
Concept Cluster: Mutual Reachability and Kosaraju
Key concepts in this block:
- 27.1 Strongly connected components
- 27.2 Kosaraju's algorithm
Intuition
A strongly connected component, or SCC, is a maximal set of vertices in a directed graph where every vertex can reach every other vertex.
Why It Matters
SCCs compress cyclic dependency regions into single units. After compression, the graph becomes a DAG, which is much easier to reason about.
How It Works
Kosaraju's algorithm uses two DFS passes:
- first DFS on the original graph to record vertices by finishing order
- second DFS on the reversed graph, processing vertices in reverse finishing order
- each second-pass DFS tree is one SCC
The correctness idea is that the finishing order isolates source and sink behavior across SCC boundaries.
Java Implementation Notes
- Build both the graph and the reversed graph.
- Store a finishing-order list from the first pass.
- Reset
visitedbefore the second pass.
Common Mistakes
- forgetting to reverse the graph
- processing the second pass in the wrong order
- applying SCC logic to an undirected graph
Quick Example
If 0 -> 1 -> 2 -> 0 and 2 -> 3 -> 4 -> 3, then the SCCs are {0, 1, 2} and {3, 4}.
Debugging Tip
If the second pass returns too many one-node components, check the order of the first-pass finishing list.
Advanced Note
If you contract every SCC into one node, you get the condensation graph, which is always a DAG.
Concept Cluster: Tarjan's Algorithm
Key concepts in this block:
- 27.3 Tarjan's algorithm
Intuition
Tarjan's SCC algorithm finds SCCs in one DFS by tracking which nodes are still active on the current recursion stack.
Why It Matters
It avoids building the reversed graph and gives a very compact one-pass SCC routine.
How It Works
For each node, Tarjan stores:
discoveryTime[node]lowLink[node]- whether the node is currently on the stack
When lowLink[node] == discoveryTime[node], that node is the root of one SCC, so the algorithm pops the stack until it reaches that root.
Java Implementation Notes
- Use a stack plus a boolean
onStack[]. - Update low-link values only through neighbors that are still on the stack.
- Use one shared DFS timer.
Common Mistakes
- updating low-link through every visited node instead of only stack-active nodes
- forgetting to mark nodes as removed from the stack
- mixing Tarjan SCC rules with bridge rules from undirected graphs
Quick Example
If DFS enters 0, 1, 2, and 2 has a back edge to 0, then all three can end up with the same low-link value.
Debugging Tip
Print (node, discoveryTime, lowLink, onStack) during DFS. Most Tarjan bugs show up there immediately.
Advanced Note
Tarjan's SCC algorithm and Tarjan-style bridge algorithms share the low-link idea, but the exact update rules depend on whether the graph is directed and whether the neighbor is on the active stack.
Concept Cluster: Bridges in Graphs
Key concepts in this block:
- 27.4 Bridges in graphs
Intuition
A bridge is an undirected edge whose removal increases the number of connected components.
Why It Matters
Bridges represent single points of failure in physical networks, dependency graphs, and road systems.
How It Works
Run DFS and compute discoveryTime and lowLink.
For a DFS tree edge u -> v, the edge is a bridge if:
lowLink[v] > discoveryTime[u]
That means the subtree rooted at v cannot reach u or any ancestor of u without using the edge (u, v).
Java Implementation Notes
- In undirected graphs, skip only the exact parent edge, not every edge back to the parent vertex if parallel edges are possible.
- Edge IDs make the implementation safer than only storing parent nodes.
Common Mistakes
- using
>=instead of> - skipping all edges to the parent node and breaking parallel-edge cases
- forgetting to visit disconnected components
Quick Example
In the graph 0-1-2 with an extra triangle 1-3-4-1, the edge 0-1 is a bridge, but the edges inside the triangle are not.
Debugging Tip
When an expected bridge is missing, inspect the child's low-link value. It is almost always being lowered incorrectly.
Advanced Note
Bridges split the graph into 2-edge-connected regions.
Concept Cluster: Articulation Points
Key concepts in this block:
- 27.5 Articulation points
Intuition
An articulation point is a vertex whose removal increases the number of connected components.
Why It Matters
Articulation points are failure-critical routers, cities, or modules. They are often more important than individual edges.
How It Works
For a non-root DFS node u, if it has a child v such that:
lowLink[v] >= discoveryTime[u]
then u is an articulation point.
For the DFS root, the rule is different:
- the root is an articulation point only if it has more than one DFS child
Java Implementation Notes
- Count DFS children for the root.
- Use the same
discoveryTimeandlowLinkframework as bridges. - Collect articulation points in ascending order if you want stable output.
Common Mistakes
- using the non-root rule on the root
- using
>instead of>= - forgetting to reset or initialize arrays for multiple components
Quick Example
If 1 connects the left half and right half of a network, then removing 1 disconnects the graph even if no single incident edge alone is enough to describe the failure.
Debugging Tip
When a root is incorrectly marked, count how many DFS tree children it actually has. The root rule is special.
Advanced Note
Articulation points split the graph into 2-vertex-connected regions.
Concept Cluster: Failure Analysis and Graph-Cut Intuition
Key concepts in this block:
- 27.6 Failure analysis and graph-cut intuition
Intuition
This chapter is really about asking what breaks when a piece disappears.
Why It Matters
Graph algorithms become much easier to choose when you name the kind of failure you care about:
- mutual reachability in directed graphs suggests SCCs
- edge failure in undirected graphs suggests bridges
- vertex failure in undirected graphs suggests articulation points
How It Works
The cut intuition is:
- SCCs compress strongly cyclic regions into one node
- bridges are edges crossing a structural cut with no alternative route
- articulation points are vertices that sit on all paths between regions
Java Implementation Notes
- Decide first whether the graph is directed or undirected.
- Decide second whether the failure unit is an edge or a vertex.
- Then choose the matching DFS condition.
Common Mistakes
- trying to use SCCs to answer an undirected bridge question
- treating every important-looking high-degree node as an articulation point
- forcing one graph template onto all failure questions
Quick Example
A node can have high degree and still not be an articulation point if many cycles route around it.
Debugging Tip
Draw the DFS tree and mark back edges. Low-link logic becomes obvious on paper.
Advanced Note
These ideas appear again in advanced topics such as 2-SAT, block-cut trees, and bridge trees.
3. Worked Examples and Full Solutions
Worked Example 1: SCC Decomposition with Kosaraju's Algorithm
Problem Statement
Given a directed graph with nodeCount vertices and edges, return all strongly connected components.
Why This Example Matters
This is the standard SCC entry point. It directly teaches mutual reachability and the two-pass decomposition idea.
Constraints or Assumptions
- the graph is directed
- the graph may be disconnected
- multiple SCCs may exist
Brute-Force Approach
For each vertex, run DFS to compute all reachable vertices. Then group vertices u and v together if u reaches v and v reaches u.
This works conceptually, but it costs O(V(V + E)) and becomes wasteful on large graphs.
Better Approach
Use Kosaraju's algorithm.
Why the Better Approach Works
The first DFS pass computes a finishing order that respects SCC boundaries. The second DFS pass on the reversed graph peels off exactly one SCC at a time.
Pragmatic Java Choice
Use:
- two adjacency lists: original and reversed
- a finishing-order list
- recursive DFS for clarity
Java Solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class KosarajuSccExample {
static List<List<Integer>> stronglyConnectedComponents(int nodeCount, int[][] edges) {
List<List<Integer>> graph = new ArrayList<>();
List<List<Integer>> reverseGraph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
reverseGraph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
reverseGraph.get(edge[1]).add(edge[0]);
}
boolean[] visited = new boolean[nodeCount];
List<Integer> finishingOrder = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
if (!visited[node]) {
dfsOrder(node, graph, visited, finishingOrder);
}
}
Collections.reverse(finishingOrder);
visited = new boolean[nodeCount];
List<List<Integer>> components = new ArrayList<>();
for (int node : finishingOrder) {
if (!visited[node]) {
List<Integer> component = new ArrayList<>();
dfsCollect(node, reverseGraph, visited, component);
components.add(component);
}
}
return components;
}
private static void dfsOrder(int node, List<List<Integer>> graph, boolean[] visited, List<Integer> order) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfsOrder(neighbor, graph, visited, order);
}
}
order.add(node);
}
private static void dfsCollect(int node, List<List<Integer>> graph, boolean[] visited, List<Integer> component) {
visited[node] = true;
component.add(node);
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfsCollect(neighbor, graph, visited, component);
}
}
}
}
Dry Run
Graph:
0 -> 11 -> 22 -> 02 -> 33 -> 44 -> 55 -> 35 -> 6
First pass finishing order ends with nodes from the sink side later.
Second pass on the reversed graph:
- starting from
0collects{0, 1, 2} - later starting from
3collects{3, 4, 5} 6is alone
Time and Space Complexity
Brute force:
- Time:
O(V(V + E)) - Space:
O(V + E)
Kosaraju:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- isolated vertices
- one large SCC containing all vertices
- graph with no directed cycles
- disconnected directed graph
Common Mistakes
- forgetting to reverse the finishing-order list
- building the reverse graph incorrectly
- thinking SCCs are the same as connected components
Worked Example 2: SCC Decomposition with Tarjan's Algorithm
Problem Statement
Given a directed graph, return all strongly connected components using a one-pass DFS algorithm.
Why This Example Matters
Tarjan's algorithm is the compact, interview-ready SCC routine when you want one traversal and tight control over DFS state.
Constraints or Assumptions
- the graph is directed
- the graph may be disconnected
- recursion depth must fit the environment
Brute-Force Approach
Again, compute mutual reachability by running DFS from every vertex and grouping vertices that can reach each other.
That is correct but slow and does not expose the deeper structural invariant.
Better Approach
Use Tarjan's algorithm with a stack and low-link values.
Why the Better Approach Works
A node stays on the stack exactly while its SCC is still open. When lowLink[node] == discoveryTime[node], the algorithm has reached the root of one SCC and can pop that whole component.
Pragmatic Java Choice
Use:
- adjacency lists
- arrays for
discoveryTime,lowLink, andonStack ArrayDeque<Integer>as the DFS stack
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
class TarjanSccExample {
static List<List<Integer>> stronglyConnectedComponents(int nodeCount, int[][] edges) {
List<List<Integer>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
}
int[] discoveryTime = new int[nodeCount];
int[] lowLink = new int[nodeCount];
boolean[] onStack = new boolean[nodeCount];
Deque<Integer> stack = new ArrayDeque<>();
int[] timer = {1};
List<List<Integer>> components = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
if (discoveryTime[node] == 0) {
dfs(node, graph, discoveryTime, lowLink, onStack, stack, timer, components);
}
}
return components;
}
private static void dfs(
int node,
List<List<Integer>> graph,
int[] discoveryTime,
int[] lowLink,
boolean[] onStack,
Deque<Integer> stack,
int[] timer,
List<List<Integer>> components) {
discoveryTime[node] = timer[0];
lowLink[node] = timer[0];
timer[0]++;
stack.push(node);
onStack[node] = true;
for (int neighbor : graph.get(node)) {
if (discoveryTime[neighbor] == 0) {
dfs(neighbor, graph, discoveryTime, lowLink, onStack, stack, timer, components);
lowLink[node] = Math.min(lowLink[node], lowLink[neighbor]);
} else if (onStack[neighbor]) {
lowLink[node] = Math.min(lowLink[node], discoveryTime[neighbor]);
}
}
if (lowLink[node] == discoveryTime[node]) {
List<Integer> component = new ArrayList<>();
while (true) {
int current = stack.pop();
onStack[current] = false;
component.add(current);
if (current == node) {
break;
}
}
components.add(component);
}
}
}
Dry Run
Graph:
0 -> 11 -> 22 -> 01 -> 33 -> 44 -> 3
DFS enters 0, 1, 2. The back edge from 2 to 0 lowers low-link values for that cycle.
Later DFS enters 3, 4. Since 4 reaches back to 3, they form one SCC.
The algorithm pops {4, 3} and then {2, 1, 0}.
Time and Space Complexity
Brute force:
- Time:
O(V(V + E)) - Space:
O(V + E)
Tarjan:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- one-node SCCs
- self-loops
- multiple disconnected SCC regions
- directed acyclic graph, where every SCC has size
1
Common Mistakes
- updating low-link through every visited node instead of only stack-active neighbors
- not clearing
onStackwhen popping - using bridge logic instead of SCC stack logic
Worked Example 3: Finding Bridges in an Undirected Graph
Problem Statement
Given an undirected graph, return every bridge edge.
Why This Example Matters
Bridges are the most direct edge-failure question. This problem forces you to understand low-link values precisely.
Constraints or Assumptions
- the graph is undirected
- the graph may be disconnected
- parallel edges may exist
Brute-Force Approach
For each edge:
- temporarily remove it
- run DFS or BFS
- check whether the number of connected components increases
This costs O(E(V + E)) and repeats almost the same traversal many times.
Better Approach
Use one DFS with low-link values.
Why the Better Approach Works
A tree edge (u, v) is a bridge exactly when the subtree of v cannot reconnect to u or above without that edge. The condition is:
lowLink[v] > discoveryTime[u]
Pragmatic Java Choice
Use:
- adjacency lists with edge IDs
- arrays for discovery and low-link
- a
List<int[]>for the answer
Java Solution
import java.util.ArrayList;
import java.util.List;
class BridgesExample {
private static final class Edge {
final int to;
final int id;
Edge(int to, int id) {
this.to = to;
this.id = id;
}
}
static List<int[]> bridges(int nodeCount, int[][] edgesArray) {
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int edgeId = 0; edgeId < edgesArray.length; edgeId++) {
int from = edgesArray[edgeId][0];
int to = edgesArray[edgeId][1];
graph.get(from).add(new Edge(to, edgeId));
graph.get(to).add(new Edge(from, edgeId));
}
int[] discoveryTime = new int[nodeCount];
int[] lowLink = new int[nodeCount];
int[] timer = {1};
List<int[]> answer = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
if (discoveryTime[node] == 0) {
dfs(node, -1, graph, discoveryTime, lowLink, timer, answer);
}
}
return answer;
}
private static void dfs(
int node,
int parentEdgeId,
List<List<Edge>> graph,
int[] discoveryTime,
int[] lowLink,
int[] timer,
List<int[]> answer) {
discoveryTime[node] = timer[0];
lowLink[node] = timer[0];
timer[0]++;
for (Edge edge : graph.get(node)) {
int neighbor = edge.to;
if (edge.id == parentEdgeId) {
continue;
}
if (discoveryTime[neighbor] == 0) {
dfs(neighbor, edge.id, graph, discoveryTime, lowLink, timer, answer);
lowLink[node] = Math.min(lowLink[node], lowLink[neighbor]);
if (lowLink[neighbor] > discoveryTime[node]) {
answer.add(new int[]{node, neighbor});
}
} else {
lowLink[node] = Math.min(lowLink[node], discoveryTime[neighbor]);
}
}
}
}
Dry Run
Graph:
0-11-22-01-33-4
The triangle on 0,1,2 keeps those edges safe.
DFS then explores 1-3-4:
4has no back edge, solowLink[4] > discoveryTime[3], making3-4a bridge3cannot reach above1, so1-3is also a bridge
Time and Space Complexity
Brute force:
- Time:
O(E(V + E)) - Space:
O(V + E)
Low-link DFS:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- disconnected graph
- graph with no bridges
- a tree, where every edge is a bridge
- parallel edges, where one copy may protect the other
Common Mistakes
- using
>=instead of> - skipping all parent-vertex edges instead of only the parent edge ID
- forgetting to start DFS from every component
Worked Example 4: Finding Articulation Points in an Undirected Graph
Problem Statement
Given an undirected graph, return every articulation point.
Why This Example Matters
This is the vertex-failure version of the bridge problem and a very common interview follow-up.
Constraints or Assumptions
- the graph is undirected
- the graph may be disconnected
- return articulation points in ascending order
Brute-Force Approach
For each vertex:
- remove it conceptually
- run DFS from a remaining vertex
- check whether connectivity worsens
This costs O(V(V + E)).
Better Approach
Use one DFS with low-link values and special handling for the DFS root.
Why the Better Approach Works
For a non-root node u, if some child subtree cannot reconnect above u, then removing u disconnects that subtree. The condition is:
lowLink[child] >= discoveryTime[u]
The root is special because it becomes critical only if it has at least two DFS children.
Pragmatic Java Choice
Use:
- adjacency lists with edge IDs
- boolean array to mark articulation points
- one final pass to collect marked nodes in order
Java Solution
import java.util.ArrayList;
import java.util.List;
class ArticulationPointsExample {
private static final class Edge {
final int to;
final int id;
Edge(int to, int id) {
this.to = to;
this.id = id;
}
}
static List<Integer> articulationPoints(int nodeCount, int[][] edgesArray) {
List<List<Edge>> graph = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
graph.add(new ArrayList<>());
}
for (int edgeId = 0; edgeId < edgesArray.length; edgeId++) {
int from = edgesArray[edgeId][0];
int to = edgesArray[edgeId][1];
graph.get(from).add(new Edge(to, edgeId));
graph.get(to).add(new Edge(from, edgeId));
}
int[] discoveryTime = new int[nodeCount];
int[] lowLink = new int[nodeCount];
boolean[] isArticulation = new boolean[nodeCount];
int[] timer = {1};
for (int node = 0; node < nodeCount; node++) {
if (discoveryTime[node] == 0) {
dfs(node, -1, -1, graph, discoveryTime, lowLink, isArticulation, timer);
}
}
List<Integer> answer = new ArrayList<>();
for (int node = 0; node < nodeCount; node++) {
if (isArticulation[node]) {
answer.add(node);
}
}
return answer;
}
private static void dfs(
int node,
int parentNode,
int parentEdgeId,
List<List<Edge>> graph,
int[] discoveryTime,
int[] lowLink,
boolean[] isArticulation,
int[] timer) {
discoveryTime[node] = timer[0];
lowLink[node] = timer[0];
timer[0]++;
int childCount = 0;
for (Edge edge : graph.get(node)) {
int neighbor = edge.to;
if (edge.id == parentEdgeId) {
continue;
}
if (discoveryTime[neighbor] == 0) {
childCount++;
dfs(neighbor, node, edge.id, graph, discoveryTime, lowLink, isArticulation, timer);
lowLink[node] = Math.min(lowLink[node], lowLink[neighbor]);
if (parentNode != -1 && lowLink[neighbor] >= discoveryTime[node]) {
isArticulation[node] = true;
}
} else {
lowLink[node] = Math.min(lowLink[node], discoveryTime[neighbor]);
}
}
if (parentNode == -1 && childCount > 1) {
isArticulation[node] = true;
}
}
}
Dry Run
Use the same graph:
0-11-22-01-33-4
Articulation points are:
1, because it separates the triangle from the3-4branch3, because it separates4from the rest
The root rule matters if DFS starts at a node with multiple independent children.
Time and Space Complexity
Brute force:
- Time:
O(V(V + E)) - Space:
O(V + E)
Low-link DFS:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- one-vertex graph
- fully biconnected graph with no articulation points
- tree graphs, where many internal nodes are articulation points
- disconnected graph with multiple DFS roots
Common Mistakes
- forgetting the special root rule
- using
>instead of>= - not collecting results from all components
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- brute-force SCC grouping:
O(V(V + E)) - Kosaraju's algorithm:
O(V + E) - Tarjan's SCC algorithm:
O(V + E) - bridge finding:
O(V + E) - articulation point finding:
O(V + E)
When to choose which technique:
- choose SCC algorithms when the graph is directed and the question is about mutual reachability
- choose Kosaraju when a two-pass solution feels easiest to reason about
- choose Tarjan when you want a compact one-pass SCC routine
- choose bridge logic when the failure unit is an edge
- choose articulation-point logic when the failure unit is a vertex
Recognition signals:
- "if we collapse cyclic dependency groups" suggests SCCs
- "critical connection" suggests bridges
- "critical router" or "critical city" suggests articulation points
- "what breaks if this service or road fails?" suggests graph-cut intuition
Signals not to force this technique:
- do not use SCCs for undirected edge-failure questions
- do not use bridge logic in directed graphs as if nothing changed
- do not use DSU when the question depends on DFS tree structure rather than only connectivity
A practical rule:
- directed mutual reachability: SCC
- undirected edge failure: bridge
- undirected vertex failure: articulation point
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- mixing directed and undirected logic
- updating low-link with the wrong timestamp
- forgetting to process disconnected components
- mishandling the DFS root for articulation points
- skipping every edge to the parent vertex instead of the exact parent edge
Boundary handling:
- isolated vertices form SCCs of size
1 - a tree has no SCC issue but every edge is a bridge
- an SCC can be size
1even with no self-loop - parallel edges can remove what would otherwise be a bridge
Short debugging checklist:
- verify whether the graph is directed or undirected
- verify discovery times strictly increase once per first visit
- verify low-link values only decrease through valid back-edge logic
- verify the root articulation rule is handled separately
- verify SCC Tarjan updates only through neighbors still on the stack
- draw the DFS tree and mark back edges if the answer looks wrong
6. Practice Problems
Easy
- Title: Count Strongly Connected Groups. One-line prompt: return how many SCCs exist in a small directed graph. Expected pattern or core idea: Kosaraju or Tarjan SCC decomposition.
- Title: Is This Road Critical? One-line prompt: determine whether one named undirected edge is a bridge. Expected pattern or core idea: bridge definition plus low-link intuition.
- Title: Is This Router Critical? One-line prompt: determine whether removing one vertex disconnects the graph. Expected pattern or core idea: articulation-point conditions.
Medium
- Title: Critical Connections in a Network. One-line prompt: list all edges whose removal disconnects the undirected network. Expected pattern or core idea: Tarjan bridge algorithm.
- Title: Strong Connectivity Compression. One-line prompt: decompose a directed graph into SCCs and build the condensation DAG. Expected pattern or core idea: SCC decomposition.
- Title: Minimum New Links for Strong Connectivity. One-line prompt: find how many directed edges must be added after SCC compression. Expected pattern or core idea: SCC condensation indegree and outdegree reasoning.
Hard
- Title: 2-SAT Satisfiability Check. One-line prompt: decide whether implication constraints are satisfiable. Expected pattern or core idea: SCCs on an implication graph.
- Title: Offline Critical Vertex Queries. One-line prompt: answer whether removing certain vertices disconnects key pairs. Expected pattern or core idea: articulation structure and block reasoning.
- Title: Robust Network Upgrade Planning. One-line prompt: identify bridge-heavy and articulation-heavy regions before adding redundancy. Expected pattern or core idea: graph-cut intuition on DFS structure.
7. Short Recap
The core idea of this chapter is that graph structure under failure can be read from DFS order and low-link values.
The most important optimization insight is that one DFS can replace many repeated connectivity checks.
The most important implementation warning is to keep the directed SCC rules separate from the undirected bridge and articulation rules.
This chapter prepares the next chapter by finishing graph structure analysis and setting up the Part VI transition into proof-driven algorithm design.
8. Coverage Check
- 27.1 Strongly connected components
- 27.2 Kosaraju's algorithm
- 27.3 Tarjan's algorithm
- 27.4 Bridges in graphs
- 27.5 Articulation points
- 27.6 Failure analysis and graph-cut intuition
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 28: Greedy Algorithms
28: Greedy Algorithms
Goal: Teach when a locally optimal choice leads to a globally optimal solution, and how to justify greedy decisions with clear correctness arguments.
Outcome: By the end of this chapter, you can recognize greedy-choice structure, solve classic scheduling, fractional knapsack, and Huffman coding problems, and explain why a greedy strategy is correct instead of just hoping it works.
1. Intuition First
This chapter matters because greedy algorithms are fast, elegant, and common, but they are also easy to misuse. A greedy solution is not "do something that feels good right now." It is "make a local choice that can be proved safe."
A simple real-world analogy is booking meeting rooms for as many short meetings as possible. If you always keep the room free as early as possible, later meetings have a better chance to fit. That is not luck. That is structure.
The core mental model is:
- define the local choice rule
- prove that some optimal solution can start with that choice
- repeat the same reasoning on the remaining smaller problem
The most common beginner confusion point is thinking that every optimization problem should have a greedy shortcut. Many do not. If the local choice blocks a better future, greedy fails and you usually need dynamic programming, backtracking, or another approach.
This chapter begins Part VI. The graph chapters already used safe greedy choices in algorithms like Dijkstra and Kruskal. Now the focus shifts from pattern recognition to proof-oriented thinking: when is the local move actually safe?
2. Core Concepts and Techniques
Concept Cluster: Greedy-Choice Property
Key concepts in this block:
- 28.1 Greedy-choice property
Intuition
A problem has the greedy-choice property if making one best local choice can still lead to some globally optimal solution.
Why It Matters
Without this property, a greedy rule is only a heuristic.
How It Works
The usual workflow is:
- propose a local rule
- prove it is safe with an exchange argument, stays-ahead argument, or structural argument
- recurse or iterate on the remaining problem
Java Implementation Notes
- Greedy solutions often start with sorting.
Arrays.sort,Collections.sort, andPriorityQueueare common tools.- Keep the choice rule explicit in code.
Common Mistakes
- picking a local rule without proof
- confusing "works on my examples" with correctness
- sorting by the wrong key
Quick Example
For activity selection, choosing the activity with the earliest finishing time is safe because it leaves the most room for later activities.
Debugging Tip
Build a tiny counterexample by hand. If your local rule fails there, it is not a valid greedy strategy.
Advanced Note
Some problems look greedy but actually require dynamic programming because the future depends on more than one local choice.
Concept Cluster: Activity Selection
Key concepts in this block:
- 28.2 Activity selection
Intuition
Choose the next compatible activity that finishes earliest.
Why It Matters
It is the classic proof-friendly greedy problem and the cleanest place to learn exchange arguments.
How It Works
Sort activities by end time. Scan left to right. Take an activity if its start time is compatible with the last chosen finish time.
Java Implementation Notes
- Represent activities as
(start, end)pairs. - Sort by
end, then tie-break bystartif needed. - Track only the finish time of the last chosen activity.
Common Mistakes
- sorting by start time or duration instead of end time
- not clarifying whether touching intervals are allowed
- forgetting tie behavior
Quick Example
If activities are (1, 3), (2, 5), (3, 4), choose (1, 3) and then (3, 4).
Debugging Tip
If the result seems too small, print the sorted order and every accept or reject decision.
Advanced Note
This same earliest-finish idea reappears in many interval problems.
Concept Cluster: Fractional Knapsack
Key concepts in this block:
- 28.3 Fractional knapsack
Intuition
When fractions are allowed, the best local choice is to take the item with the highest value density first.
Why It Matters
It is a standard example where greedy works for the fractional version but fails for the 0/1 version.
How It Works
Compute value / weight for each item, sort in descending order, and take as much as possible from each item until capacity is full.
Java Implementation Notes
- Use
doublefor ratios and total value. - Avoid integer division.
- Guard against zero-weight edge cases if the problem allows them.
Common Mistakes
- applying this greedy rule to 0/1 knapsack
- sorting by raw value instead of value density
- losing precision with integer division
Quick Example
If densities are 6.0, 5.0, and 4.0, take the 6.0 item first even if it is not the heaviest or highest raw value.
Debugging Tip
Print (value, weight, density) after sorting. Wrong answers often come from the wrong sort key.
Advanced Note
Fractional knapsack works because the final partial item does not break the density argument.
Concept Cluster: Interval Scheduling
Key concepts in this block:
- 28.4 Interval scheduling
Intuition
Intervals are activities with start and end points. The goal is usually to keep as many compatible intervals as possible or remove as few overlaps as possible.
Why It Matters
It generalizes activity selection language into the broader interval family.
How It Works
For the maximum-count version, the same earliest-finish greedy rule is usually the right choice. For other interval variants, the greedy key may change, so read the objective carefully.
Java Implementation Notes
- Sort intervals as objects or
int[]. - Be explicit about compatibility:
current.start >= lastEndversus>. - Keep the rule and the objective aligned.
Common Mistakes
- reusing the same rule for a different interval objective without proof
- mixing closed-interval and half-open-interval assumptions
- counting overlap incorrectly
Quick Example
To remove the minimum number of overlapping intervals, keep the interval that ends earlier and discard the one that blocks more future room.
Debugging Tip
When interval answers are off by one, inspect whether equality at boundaries should be accepted.
Advanced Note
Not every interval problem is greedy. Weighted interval scheduling is a classic counterexample and needs dynamic programming.
Concept Cluster: Huffman Coding
Key concepts in this block:
- 28.5 Huffman coding
Intuition
Repeatedly merge the two least frequent symbols so expensive code lengths are assigned to rare symbols, not common ones.
Why It Matters
It is a greedy algorithm on trees and one of the best examples of a greedy rule justified by structure rather than simple sorting.
How It Works
Insert all symbol frequencies into a min-heap. Repeatedly remove the two smallest, merge them into a new node, and push the merged node back.
Java Implementation Notes
- Use a
PriorityQueue<Node>. - A Huffman tree is a full binary tree.
- Assign
0and1while traversing from root to leaves.
Common Mistakes
- forgetting the single-symbol edge case
- using a max-heap by accident
- assuming Huffman codes are unique
Quick Example
For frequencies 5, 9, 12, 13, merge 5 and 9 first, then continue with the new combined weight.
Debugging Tip
Print each merge step. If the heap order is wrong once, the whole tree changes.
Advanced Note
Huffman coding is really the optimal merge pattern in disguise.
Concept Cluster: Proving a Greedy Strategy
Key concepts in this block:
- 28.6 Proving a greedy strategy
Intuition
A greedy algorithm is complete only after the proof.
Why It Matters
Part VI expects stronger reasoning than "this pattern is common." You should be able to defend why the local rule is safe.
How It Works
Common proof styles:
- exchange argument: swap the first choice in an optimal solution with the greedy choice
- stays-ahead argument: show the greedy partial solution is never worse than any competitor at the same step
- cut or structure argument: show the greedy choice is forced by the problem structure
Java Implementation Notes
- Let the proof drive the implementation, not the other way around.
- Keep the state small and aligned with the proof invariant.
- Comments can name the invariant when the code is subtle.
Common Mistakes
- proving only the first choice and not the repeated step
- arguing from examples instead of structure
- using a proof style that does not match the problem
Quick Example
In activity selection, if an optimal solution starts with a later-finishing activity, you can exchange it with the earlier-finishing greedy activity without reducing the number of activities selected.
Debugging Tip
If you cannot state the invariant in one sentence, the greedy rule is probably not fully understood yet.
Advanced Note
When no clean greedy proof appears, that is often the signal to step back and try DP or backtracking.
3. Worked Examples and Full Solutions
Worked Example 1: Maximum Non-Overlapping Activities
Problem Statement
Given a list of activities as [start, end], select the maximum number of pairwise non-overlapping activities.
Why This Example Matters
This is the foundational greedy scheduling problem. It also captures the core idea behind many interval scheduling variants.
Constraints or Assumptions
- activities are compatible if
next.start >= previous.end - intervals may be unsorted
- you only need one optimal selection
Brute-Force Approach
Enumerate every subset of activities, keep only compatible subsets, and return the largest one.
This is O(2^n * n log n) or worse, depending on how compatibility is checked.
Better Approach
Sort by finish time and greedily take the earliest-finishing compatible activity.
Why the Better Approach Works
The earliest-finishing activity leaves the most room for the remaining schedule. Any optimal solution can exchange its first activity for this one without reducing how many activities fit later.
Pragmatic Java Choice
Use:
- a small
Activityclass - sorting by finish time
- a simple greedy scan
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class ActivitySelectionExample {
static final class Activity {
final int start;
final int finish;
Activity(int start, int finish) {
this.start = start;
this.finish = finish;
}
}
static List<Activity> selectMaximumActivities(int[][] intervals) {
Activity[] activities = new Activity[intervals.length];
for (int i = 0; i < intervals.length; i++) {
activities[i] = new Activity(intervals[i][0], intervals[i][1]);
}
Arrays.sort(activities, Comparator
.comparingInt((Activity activity) -> activity.finish)
.thenComparingInt(activity -> activity.start));
List<Activity> chosen = new ArrayList<>();
int lastFinish = Integer.MIN_VALUE;
for (Activity activity : activities) {
if (activity.start >= lastFinish) {
chosen.add(activity);
lastFinish = activity.finish;
}
}
return chosen;
}
}
Dry Run
Activities:
[1, 3][2, 5][3, 4][0, 7][5, 7][8, 9]
Sorted by finish:
[1, 3],[3, 4],[2, 5],[0, 7],[5, 7],[8, 9]
Greedy picks:
[1, 3][3, 4]- skip
[2, 5] - skip
[0, 7] [5, 7][8, 9]
Time and Space Complexity
Brute force:
- Time: exponential
- Space: subset bookkeeping dependent
Greedy:
- Time:
O(n log n) - Space:
O(n)for the returned selection
Edge Cases
- empty input
- intervals that touch exactly at endpoints
- multiple optimal schedules
- many identical finish times
Common Mistakes
- sorting by start time
- treating endpoint equality inconsistently
- forgetting that the objective is maximum count, not maximum total duration
Worked Example 2: Fractional Knapsack
Problem Statement
Given items with [value, weight] and a knapsack capacity, return the maximum total value when you may take fractional parts of items.
Why This Example Matters
It is the cleanest example of a problem where greedy is correct only because fractional splitting is allowed.
Constraints or Assumptions
- every item has positive weight
- partial items are allowed
- return the maximum total value as a
double
Brute-Force Approach
Try every subset of full items and every possible choice of a final fractional item.
That is combinatorial and unnecessary.
Better Approach
Sort items by value density, value / weight, in descending order.
Why the Better Approach Works
If two items are still available, any solution that takes lower density mass before higher density mass can be improved by swapping that mass. So the density order is always safe.
Pragmatic Java Choice
Use:
- an
Itemclass Arrays.sortwith a density comparatordoublearithmetic
Java Solution
import java.util.Arrays;
import java.util.Comparator;
class FractionalKnapsackExample {
private static final class Item {
final int value;
final int weight;
Item(int value, int weight) {
this.value = value;
this.weight = weight;
}
double density() {
return (double) value / weight;
}
}
static double maximumValue(int capacity, int[][] itemsArray) {
Item[] items = new Item[itemsArray.length];
for (int i = 0; i < itemsArray.length; i++) {
items[i] = new Item(itemsArray[i][0], itemsArray[i][1]);
}
Arrays.sort(items, Comparator.comparingDouble(Item::density).reversed());
double totalValue = 0.0;
int remainingCapacity = capacity;
for (Item item : items) {
if (remainingCapacity == 0) {
break;
}
int takeWeight = Math.min(remainingCapacity, item.weight);
totalValue += takeWeight * item.density();
remainingCapacity -= takeWeight;
}
return totalValue;
}
}
Dry Run
Items:
- value
60, weight10, density6.0 - value
100, weight20, density5.0 - value
120, weight30, density4.0
Capacity 50
Take:
- all of
(60, 10)-> value60 - all of
(100, 20)-> total160 20/30of(120, 30)-> add80
Final value: 240.0
Time and Space Complexity
Brute force:
- Time: exponential
- Space: subset tracking dependent
Greedy:
- Time:
O(n log n) - Space:
O(n)
Edge Cases
- capacity
0 - one item heavier than the whole capacity
- many items with the same density
- precision formatting in output
Common Mistakes
- using integer division for density
- applying the same rule to 0/1 knapsack
- sorting by value instead of density
Worked Example 3: Huffman Coding
Problem Statement
Given symbols and frequencies, build one optimal prefix-free binary code.
Why This Example Matters
This is a greedy algorithm on tree construction, not just sorting, and it is a strong test of proof-based thinking.
Constraints or Assumptions
- every symbol has positive frequency
- any optimal prefix-free code is acceptable
- if there is one symbol, give it code
"0"
Brute-Force Approach
Enumerate all full binary tree shapes and all leaf placements, compute weighted code length for each, and keep the best one.
That is completely impractical.
Better Approach
Use a min-heap and repeatedly merge the two least frequent nodes.
Why the Better Approach Works
The two least frequent symbols can be placed deepest together in some optimal tree. Merging them reduces the problem to a smaller one of the same form.
Pragmatic Java Choice
Use:
- a
PriorityQueue<Node> - a tree node with left and right children
- a DFS to generate bit strings
Java Solution
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
class HuffmanCodingExample {
private static final class Node implements Comparable<Node> {
final char symbol;
final int frequency;
final Node left;
final Node right;
Node(char symbol, int frequency, Node left, Node right) {
this.symbol = symbol;
this.frequency = frequency;
this.left = left;
this.right = right;
}
boolean isLeaf() {
return left == null && right == null;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.frequency, other.frequency);
}
}
static Map<Character, String> buildCodes(char[] symbols, int[] frequencies) {
PriorityQueue<Node> minHeap = new PriorityQueue<>();
for (int i = 0; i < symbols.length; i++) {
minHeap.offer(new Node(symbols[i], frequencies[i], null, null));
}
if (minHeap.isEmpty()) {
return new HashMap<>();
}
while (minHeap.size() > 1) {
Node first = minHeap.poll();
Node second = minHeap.poll();
minHeap.offer(new Node('\0', first.frequency + second.frequency, first, second));
}
Node root = minHeap.poll();
Map<Character, String> codes = new HashMap<>();
buildCodes(root, "", codes);
return codes;
}
private static void buildCodes(Node node, String prefix, Map<Character, String> codes) {
if (node.isLeaf()) {
codes.put(node.symbol, prefix.isEmpty() ? "0" : prefix);
return;
}
buildCodes(node.left, prefix + "0", codes);
buildCodes(node.right, prefix + "1", codes);
}
}
Dry Run
Frequencies:
a: 5b: 9c: 12d: 13e: 16f: 45
Merge order begins:
5 + 9 = 1412 + 13 = 2514 + 16 = 3025 + 30 = 5545 + 55 = 100
Then DFS assigns shorter codes to more frequent symbols.
Time and Space Complexity
Brute force:
- Time: super-exponential in practice
- Space: tree enumeration dependent
Huffman:
- Time:
O(n log n) - Space:
O(n)
Edge Cases
- one symbol only
- repeated equal frequencies
- many symbols with very small frequencies
- different valid optimal code assignments
Common Mistakes
- using a max-heap
- forgetting the one-symbol case
- expecting a unique code assignment
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- greedy scheduling by sorting: usually
O(n log n) - fractional knapsack by density sorting:
O(n log n) - Huffman coding with a heap:
O(n log n) - brute-force baselines: typically exponential or structurally infeasible
When to choose greedy:
- the problem has a clean local-choice rule
- you can write a short proof that the rule is safe
- the remaining problem after the local choice has the same structure
Recognition signals:
- "maximize count of compatible intervals" suggests earliest-finish greedy
- "fractional take is allowed" suggests density-based greedy
- "repeatedly combine the two lightest or cheapest pieces" suggests a min-heap greedy pattern
- "prefix-free code with frequencies" suggests Huffman coding
Signals not to force this technique:
- 0/1 knapsack is not solved by fractional knapsack logic
- weighted interval scheduling is not solved by plain activity selection
- if the best future depends on multiple past choices, greedy may fail
- if you cannot justify the local rule, stop and reassess
A practical rule:
- greedy first asks for a proof
- if the proof does not come, do not pretend the pattern still fits
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- sorting by the wrong key
- mixing endpoint conventions in interval problems
- using integer division in density calculations
- using the wrong heap direction in Huffman coding
- applying a greedy rule to a nearby but different objective
Boundary handling:
- empty activity list should return an empty selection
- equal interval endpoints need a clear compatibility rule
- capacity
0in knapsack should return value0 - one-symbol Huffman input still needs a valid code
Short debugging checklist:
- verify the objective before choosing the greedy key
- verify the data is sorted by the intended field
- verify each accepted choice preserves the invariant
- test a tiny counterexample by hand
- for Huffman, print each heap merge step
- for interval problems, test boundary equality cases
6. Practice Problems
Easy
- Title: Maximum Number of Compatible Meetings. One-line prompt: select the most non-overlapping intervals from a meeting list. Expected pattern or core idea: earliest-finish-time greedy.
- Title: Non-Overlapping Intervals. One-line prompt: remove the minimum number of intervals so the rest do not overlap. Expected pattern or core idea: interval scheduling greedy.
- Title: Minimum Number of Arrows to Burst Balloons. One-line prompt: use the fewest points to hit all overlapping balloon intervals. Expected pattern or core idea: interval sorting and greedy placement.
Medium
- Title: Fractional Cargo Loading. One-line prompt: maximize shipment value when partial crates are allowed. Expected pattern or core idea: density-based greedy.
- Title: Optimal Merge Pattern. One-line prompt: repeatedly merge files at minimum total cost. Expected pattern or core idea: min-heap greedy similar to Huffman.
- Title: Partition Labels. One-line prompt: split a string into the most partitions so letters do not cross partitions. Expected pattern or core idea: greedy interval closure.
Hard
- Title: Huffman Code Construction. One-line prompt: build an optimal prefix-free code from symbol frequencies. Expected pattern or core idea: heap-based greedy with tree merges.
- Title: Job Sequencing with Deadlines. One-line prompt: choose profitable jobs under slot deadlines. Expected pattern or core idea: greedy ordering plus data structure support.
- Title: Prove or Reject the Greedy Rule. One-line prompt: decide whether a proposed local-choice rule is correct and justify the answer. Expected pattern or core idea: exchange argument or counterexample construction.
7. Short Recap
The core idea of this chapter is that greedy algorithms work only when a local choice can be proved safe.
The most important optimization insight is that the correct sort key or heap rule often turns an exponential search into an O(n log n) routine.
The most important implementation warning is not technical but conceptual: a greedy rule without a proof is not finished.
This chapter prepares the next chapter by moving from one-step-safe choices to full decision-tree exploration with backtracking.
8. Coverage Check
- 28.1 Greedy-choice property
- 28.2 Activity selection
- 28.3 Fractional knapsack
- 28.4 Interval scheduling
- 28.5 Huffman coding
- 28.6 Proving a greedy strategy
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 29: Backtracking
29: Backtracking
Goal: Teach how to explore a decision tree systematically, build partial solutions, prune impossible branches, and undo choices cleanly in Java.
Outcome: By the end of this chapter, you can model a search space, write reusable backtracking templates, and solve subsets, permutations, combination sum, N-Queens, and Sudoku-style problems with correct pruning.
1. Intuition First
This chapter matters because some problems do not have a safe greedy move and do not fit a direct formula. Instead, you must try choices, detect failure early, and back out cleanly.
A simple real-world analogy is filling a schedule or puzzle one decision at a time:
- place one item
- check whether the partial state is still legal
- continue if it is
- undo and try a different choice if it is not
The core mental model is a decision tree:
- each node is a partial solution
- each edge is one next choice
- a base case records a full valid solution
- pruning cuts off a branch before it wastes more work
The most common beginner confusion point is mixing backtracking with plain brute force. Backtracking is still exhaustive in the worst case, but it avoids exploring obviously invalid partial states. It is organized search, not blind search.
This chapter continues the Part VI shift into state design. Greedy asked, "What local choice is safe?" Backtracking asks, "What state do I need to represent a partial solution, and when can I stop exploring this branch?"
2. Core Concepts and Techniques
Concept Cluster: Search Space and Decision Trees
Key concepts in this block:
- 29.1 Search space and decision trees
Intuition
Backtracking is DFS over a space of possible decisions.
Why It Matters
If you cannot describe the search tree, you cannot write the recursion cleanly.
How It Works
A backtracking function usually answers:
- what choices are available now
- how to apply one choice
- how to undo it
- when a partial state is invalid
- when a full solution is complete
Java Implementation Notes
- Pass mutable
Listor board state plus a result container. - Undo mutations immediately after the recursive call.
- Keep the recursive signature small and explicit.
Common Mistakes
- forgetting to undo a choice
- storing the same mutable list reference in the result
- not defining the base case precisely
Quick Example
In a subset problem, every index gives two branches: include or exclude.
Debugging Tip
Print the recursion depth, current path, and next index. That usually exposes state leaks.
Advanced Note
Pruning quality often matters more than the bare recursion template.
Concept Cluster: Subsets
Key concepts in this block:
- 29.2 Subsets
Intuition
For each element, decide whether it is in the subset.
Why It Matters
This is the simplest backtracking pattern and the cleanest entry point for recursion trees.
How It Works
At index i, branch into:
- do not take
values[i] - take
values[i]
When i == n, record the current subset.
Java Implementation Notes
- Use one
List<Integer> current. - Add before the recursive call and remove after it.
- Copy the list when storing a solution.
Common Mistakes
- forgetting to copy the current subset
- mixing subset order with permutation order
- stopping too early
Quick Example
For [1, 2], the subsets are [], [2], [1], [1, 2].
Debugging Tip
If subsets repeat, check whether the same list object is being reused in the result.
Advanced Note
Bitmask iteration is another way to generate subsets, but backtracking generalizes better when constraints appear.
Concept Cluster: Permutations
Key concepts in this block:
- 29.3 Permutations
Intuition
A permutation chooses the next unused element at every depth.
Why It Matters
This introduces "used versus unused" state and order-sensitive search.
How It Works
At depth d, try every element not yet used, append it to the path, recurse, then undo.
Java Implementation Notes
- Use
boolean[] used. - The permutation is complete when
path.size() == values.length. - For duplicate elements, extra deduplication logic is needed.
Common Mistakes
- forgetting to reset
used[i] - assuming subset logic also handles order
- not handling duplicates separately
Quick Example
For [1, 2, 3], the first layer has three branches: start with 1, 2, or 3.
Debugging Tip
Print used[] alongside the current path. Permutation bugs are usually state-reset bugs.
Advanced Note
Many ordering problems reduce to permutation search plus pruning.
Concept Cluster: Combination Sum
Key concepts in this block:
- 29.4 Combination sum
Intuition
Choose numbers that build toward a target while pruning branches that already overshoot.
Why It Matters
This is the standard "search with constraints" pattern where pruning meaningfully reduces the tree.
How It Works
Sort the candidates, keep a remaining target, and recurse with either:
- the same index again if reuse is allowed
- the next index if reuse is not allowed
Stop when the remaining target becomes 0 or negative.
Java Implementation Notes
- Sorting enables early break pruning.
- Pass the current start index to control reuse.
- Keep the remaining target instead of recomputing sums.
Common Mistakes
- not sorting before pruning
- using the wrong next index for reuse versus no-reuse versions
- continuing after the target already became negative
Quick Example
For candidates [2, 3, 6, 7] and target 7, the valid combinations are [2, 2, 3] and [7].
Debugging Tip
Log (startIndex, remainingTarget, path) before branching. That makes pruning decisions easy to inspect.
Advanced Note
This family often branches into subset sum, partitioning, and k-combination variants.
Concept Cluster: N-Queens
Key concepts in this block:
- 29.5 N-Queens
Intuition
Place one queen per row and rule out attacked columns and diagonals.
Why It Matters
It is the classic board backtracking problem and teaches how to encode constraints for fast pruning.
How It Works
At row r, try each column c that is not already blocked by:
- another queen in column
c - a queen on the main diagonal
- a queen on the anti-diagonal
Java Implementation Notes
- Use boolean arrays for columns and diagonals.
- Row-by-row placement avoids checking every board cell.
- Build string rows only when a full solution is found.
Common Mistakes
- wrong diagonal indexing
- forgetting to undo diagonal marks
- placing more than one queen per row
Quick Example
On a 4 x 4 board, placing a queen at (0, 1) blocks column 1, diagonal row - col = -1, and anti-diagonal row + col = 1.
Debugging Tip
Print the row and chosen column each time you place a queen. Diagonal index bugs show up fast.
Advanced Note
N-Queens is a strong example of pruning transforming an impossible full-board search into a manageable row-based search.
Concept Cluster: Sudoku Solver
Key concepts in this block:
- 29.6 Sudoku solver
Intuition
Fill one empty cell at a time, but only with digits consistent with the row, column, and box constraints.
Why It Matters
Sudoku combines backtracking with tight constraint propagation and shows how strong pruning makes search practical.
How It Works
Precompute which digits are already used in each row, column, and 3 x 3 box. For each empty cell, try only legal digits, recurse, and undo.
Java Implementation Notes
- Use
boolean[9][10]for row, column, and box usage. - Collect empty cells first.
- Backtrack as soon as one full valid board is found if only one solution is needed.
Common Mistakes
- using the wrong box index
- forgetting to clear row, column, or box state on undo
- validating the whole board repeatedly instead of maintaining constraint state
Quick Example
For cell (4, 7), the box index is (4 / 3) * 3 + (7 / 3) = 5.
Debugging Tip
If the solver gets stuck too early, print the legal digits for the first few empty cells.
Advanced Note
Sudoku is a preview of constraint-satisfaction thinking more than a pure brute-force problem.
3. Worked Examples and Full Solutions
Worked Example 1: Generate All Permutations of Distinct Integers
Problem Statement
Given an array of distinct integers, return all permutations.
Why This Example Matters
This is the standard order-sensitive backtracking template. It teaches how to represent "already used" choices.
Constraints or Assumptions
- all values are distinct
- order matters
- every permutation should appear exactly once
Brute-Force Approach
Generate every length-n sequence by choosing any value at each position, then filter out sequences that reuse the same value.
That creates n^n sequences before filtering, which is far too wasteful.
Better Approach
Build the permutation one position at a time and only choose unused elements.
Why the Better Approach Works
A partial permutation is valid exactly when no value is repeated. By enforcing that rule during construction, the search explores only legal prefixes.
Pragmatic Java Choice
Use:
boolean[] used- a mutable
List<Integer> path - a result list of copied paths
Java Solution
import java.util.ArrayList;
import java.util.List;
class PermutationsBacktrackingExample {
static List<List<Integer>> permute(int[] values) {
List<List<Integer>> result = new ArrayList<>();
boolean[] used = new boolean[values.length];
backtrack(values, used, new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] values, boolean[] used, List<Integer> path, List<List<Integer>> result) {
if (path.size() == values.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < values.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
path.add(values[i]);
backtrack(values, used, path, result);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
Dry Run
Input: [1, 2, 3]
Tree start:
- choose
1, then explore[1, 2, 3]and[1, 3, 2] - choose
2, then explore[2, 1, 3]and[2, 3, 1] - choose
3, then explore[3, 1, 2]and[3, 2, 1]
Time and Space Complexity
Brute force:
- Time:
O(n^n) - Space: sequence generation dependent
Backtracking:
- Time:
O(n * n!) - Space:
O(n)recursion depth plus output storage
Edge Cases
- empty array
- single element
- duplicate values, which need extra handling not shown here
- large
n, where output size dominates everything
Common Mistakes
- not resetting
used[i] - forgetting to copy
path - confusing permutation logic with subset logic
Worked Example 2: Combination Sum
Problem Statement
Given distinct candidate numbers and a target, return all unique combinations where the chosen numbers sum to the target. You may reuse the same candidate multiple times.
Why This Example Matters
This is the classic pruning example. It shows how sorting and remaining-target logic shrink the search tree.
Constraints or Assumptions
- candidates are positive
- reuse is allowed
- output order does not matter
Brute-Force Approach
Enumerate every sequence of candidate picks up to some length bound, compute its sum, and filter the ones that equal the target.
That explores many paths that already overshoot the target or differ only by useless ordering.
Better Approach
Sort the candidates and backtrack with:
startIndexremainingTarget- early break when the candidate is too large
Why the Better Approach Works
All choices keep the partial sum valid. Sorting means once one candidate is too large, all later ones are too large too, so the whole suffix can be pruned.
Pragmatic Java Choice
Use:
Arrays.sort- one mutable
path - recursion that passes the current index again to allow reuse
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class CombinationSumBacktrackingExample {
static List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, target, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(
int[] candidates,
int remainingTarget,
int startIndex,
List<Integer> path,
List<List<Integer>> result) {
if (remainingTarget == 0) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
int candidate = candidates[i];
if (candidate > remainingTarget) {
break;
}
path.add(candidate);
backtrack(candidates, remainingTarget - candidate, i, path, result);
path.remove(path.size() - 1);
}
}
}
Dry Run
Candidates: [2, 3, 6, 7], target 7
Search starts:
- take
2-> remaining5 - take another
2-> remaining3 - take
3-> remaining0, record[2, 2, 3] - backtrack and try
7directly -> record[7]
Branches involving 6 after remaining 5 are cut immediately.
Time and Space Complexity
Brute force:
- Time: exponential with large constant waste
- Space: recursion and output dependent
Backtracking with pruning:
- Time: still exponential in the worst case
- Space:
O(target / minCandidate)recursion depth plus output storage
Edge Cases
- target
0 - no valid combination
- one candidate larger than target
- many combinations causing large output
Common Mistakes
- forgetting to sort before pruning
- using
i + 1and accidentally disallowing reuse - not breaking once the sorted candidate is too large
Worked Example 3: N-Queens
Problem Statement
Given n, return all valid ways to place n queens on an n x n chessboard so that no two queens attack each other.
Why This Example Matters
This is the classic structured board-search problem. The main lesson is that good constraint encoding matters.
Constraints or Assumptions
- one queen per row
- no two queens share a column
- no two queens share a diagonal
Brute-Force Approach
Choose any n cells from the n^2 board and test whether those cells form a valid configuration.
That is much too large and ignores obvious structure.
Better Approach
Place one queen per row and maintain blocked columns and diagonals.
Why the Better Approach Works
Each recursive level represents one row, so the search never creates illegal states with multiple queens in one row. Columns and diagonals let the algorithm reject invalid positions immediately.
Pragmatic Java Choice
Use:
- a mutable
char[][] board boolean[] columnsboolean[] diagonalDownforrow + colboolean[] diagonalUpforrow - col + n
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class NQueensBacktrackingExample {
static List<List<String>> solveNQueens(int size) {
char[][] board = new char[size][size];
for (char[] row : board) {
Arrays.fill(row, '.');
}
boolean[] columns = new boolean[size];
boolean[] diagonalDown = new boolean[2 * size];
boolean[] diagonalUp = new boolean[2 * size];
List<List<String>> result = new ArrayList<>();
backtrack(0, size, board, columns, diagonalDown, diagonalUp, result);
return result;
}
private static void backtrack(
int row,
int size,
char[][] board,
boolean[] columns,
boolean[] diagonalDown,
boolean[] diagonalUp,
List<List<String>> result) {
if (row == size) {
List<String> solution = new ArrayList<>();
for (char[] boardRow : board) {
solution.add(new String(boardRow));
}
result.add(solution);
return;
}
for (int col = 0; col < size; col++) {
int downIndex = row + col;
int upIndex = row - col + size;
if (columns[col] || diagonalDown[downIndex] || diagonalUp[upIndex]) {
continue;
}
columns[col] = true;
diagonalDown[downIndex] = true;
diagonalUp[upIndex] = true;
board[row][col] = 'Q';
backtrack(row + 1, size, board, columns, diagonalDown, diagonalUp, result);
board[row][col] = '.';
diagonalUp[upIndex] = false;
diagonalDown[downIndex] = false;
columns[col] = false;
}
}
}
Dry Run
For n = 4:
- row
0: try column1 - row
1: safe choice becomes column3 - row
2: safe choice becomes column0 - row
3: safe choice becomes column2
That gives one solution:
.Q.....QQ.....Q.
Time and Space Complexity
Brute force:
- Time: combinatorial over board-cell subsets
- Space: board-check dependent
Backtracking with pruning:
- Time: exponential in the worst case
- Space:
O(n)recursion depth plus output storage
Edge Cases
n = 1n = 2andn = 3, which have no solutions- large
n, where output can be huge - diagonal-index mistakes
Common Mistakes
- wrong diagonal formulas
- not undoing column or diagonal marks
- scanning the entire board to validate every move instead of maintaining state
Worked Example 4: Sudoku Solver
Problem Statement
Given a partially filled 9 x 9 Sudoku board, fill it in place so every row, column, and 3 x 3 box contains digits 1 through 9.
Why This Example Matters
This is the most constraint-heavy example in the chapter. It shows how maintaining legality state turns blind search into practical backtracking.
Constraints or Assumptions
- the input board is valid so far
- empty cells contain
'.' - one valid solution is enough
Brute-Force Approach
Fill every empty cell with digits 1 through 9 in every possible way, then validate the full board at the end.
That explores 9^k assignments for k empty cells and wastes work on clearly invalid partial states.
Better Approach
Track used digits in rows, columns, and boxes, and only try legal digits for each empty cell.
Why the Better Approach Works
Every recursive step preserves Sudoku constraints, so the search never descends into a branch that is already impossible.
Pragmatic Java Choice
Use:
boolean[9][10]for row, column, and box usage- a list of empty cell positions
- recursion that stops when one complete board is found
Java Solution
import java.util.ArrayList;
import java.util.List;
class SudokuSolverBacktrackingExample {
static void solveSudoku(char[][] board) {
boolean[][] rowUsed = new boolean[9][10];
boolean[][] columnUsed = new boolean[9][10];
boolean[][] boxUsed = new boolean[9][10];
List<int[]> emptyCells = new ArrayList<>();
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
char cell = board[row][col];
if (cell == '.') {
emptyCells.add(new int[]{row, col});
} else {
int digit = cell - '0';
int box = boxIndex(row, col);
rowUsed[row][digit] = true;
columnUsed[col][digit] = true;
boxUsed[box][digit] = true;
}
}
}
backtrack(0, emptyCells, board, rowUsed, columnUsed, boxUsed);
}
private static boolean backtrack(
int index,
List<int[]> emptyCells,
char[][] board,
boolean[][] rowUsed,
boolean[][] columnUsed,
boolean[][] boxUsed) {
if (index == emptyCells.size()) {
return true;
}
int row = emptyCells.get(index)[0];
int col = emptyCells.get(index)[1];
int box = boxIndex(row, col);
for (int digit = 1; digit <= 9; digit++) {
if (rowUsed[row][digit] || columnUsed[col][digit] || boxUsed[box][digit]) {
continue;
}
board[row][col] = (char) ('0' + digit);
rowUsed[row][digit] = true;
columnUsed[col][digit] = true;
boxUsed[box][digit] = true;
if (backtrack(index + 1, emptyCells, board, rowUsed, columnUsed, boxUsed)) {
return true;
}
board[row][col] = '.';
rowUsed[row][digit] = false;
columnUsed[col][digit] = false;
boxUsed[box][digit] = false;
}
return false;
}
private static int boxIndex(int row, int col) {
return (row / 3) * 3 + (col / 3);
}
}
Dry Run
Suppose the first empty cell is (0, 2):
- digits already used in row
0, column2, and box0remove most options - only legal digits are tried
- after placing one digit, the solver moves to the next empty cell
- if a later contradiction appears, it undoes the digit and tries the next one
Time and Space Complexity
Brute force:
- Time:
O(9^k)forkempty cells - Space: recursion depth
O(k)
Backtracking with constraint tables:
- Time: still exponential in the worst case, but much faster in practice due to pruning
- Space:
O(k)recursion depth plus fixed Sudoku state
Edge Cases
- already solved board
- board with very few clues
- invalid board state if input guarantees are not respected
- many empty cells causing deep recursion
Common Mistakes
- wrong box index
- forgetting to undo row, column, or box marks
- revalidating the full board on every step instead of maintaining state
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- subsets:
O(2^n) - permutations:
O(n * n!) - combination-style searches: exponential in the worst case
- N-Queens and Sudoku: exponential search with strong pruning benefits
When to choose backtracking:
- you must construct actual solutions, not just count with a closed formula
- partial solutions can be checked for validity early
- the problem naturally forms a choice tree
Recognition signals:
- "generate all valid configurations"
- "try choices until one works"
- "place items under constraints"
- "search all combinations or arrangements with pruning"
Signals not to force this technique:
- if the problem has a safe greedy rule, greedy is better
- if the same subproblem repeats heavily, dynamic programming may be better
- if the state is just graph reachability or shortest path, standard graph algorithms are usually better
A practical rule:
- backtracking is the right tool when the search tree is unavoidable but can be pruned intelligently
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- forgetting to undo mutations
- storing a mutable path without copying it
- weak pruning that allows obviously impossible branches
- wrong base case or stop condition
- mixing reuse and no-reuse logic in combination problems
Boundary handling:
- empty input often has one valid trivial configuration
- duplicates need extra care in subset and permutation problems
- constraint tables must stay consistent after every undo
- recursion depth can become large on big search spaces
Short debugging checklist:
- print the current path or board before and after each recursive call
- verify every mutation has a matching undo
- verify the base case exactly matches a complete solution
- verify pruning conditions are correct and not too aggressive
- test the smallest nontrivial input first
- for boards, print row, column, and diagonal or box state explicitly
6. Practice Problems
Easy
- Title: Subsets. One-line prompt: return every subset of a list of distinct integers. Expected pattern or core idea: include-or-exclude backtracking.
- Title: Letter Combinations of a Phone Number. One-line prompt: generate all strings formed from digit-to-letter mappings. Expected pattern or core idea: decision tree over choices per position.
- Title: Combination Sum. One-line prompt: return all combinations that add to a target with reuse allowed. Expected pattern or core idea: backtracking with pruning on remaining target.
Medium
- Title: Permutations. One-line prompt: return every ordering of distinct integers. Expected pattern or core idea: used-array backtracking.
- Title: Palindrome Partitioning. One-line prompt: split a string into all partitions where every piece is a palindrome. Expected pattern or core idea: backtracking over cut positions plus validity checks.
- Title: Generate Parentheses. One-line prompt: generate all valid parenthesis strings of length
2n. Expected pattern or core idea: constrained backtracking with state counts.
Hard
- Title: N-Queens. One-line prompt: return all valid queen placements on an
n x nboard. Expected pattern or core idea: row-by-row backtracking with column and diagonal constraints. - Title: Sudoku Solver. One-line prompt: fill a partially completed Sudoku board. Expected pattern or core idea: constraint-backed backtracking.
- Title: Expression Add Operators. One-line prompt: insert operators into a digit string to hit a target value. Expected pattern or core idea: backtracking with rolling expression state.
7. Short Recap
The core idea of this chapter is that backtracking explores a decision tree while rejecting invalid partial states as early as possible.
The most important optimization insight is that pruning and good state representation matter more than the raw recursion template.
The most important implementation warning is to undo every mutation exactly once.
This chapter prepares the next chapter by shifting from search-tree reasoning to split-solve-combine reasoning in divide and conquer.
8. Coverage Check
- 29.1 Search space and decision trees
- 29.2 Subsets
- 29.3 Permutations
- 29.4 Combination sum
- 29.5 N-Queens
- 29.6 Sudoku solver
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 30: Divide and Conquer
30: Divide and Conquer
Goal: Teach how to solve problems by splitting them into smaller independent parts, solving those parts recursively, and combining the results with clear recurrence thinking.
Outcome: By the end of this chapter, you can recognize divide-and-conquer structure, implement merge sort, quick sort, binary search, and the closest pair algorithm, and reason about recursive solution structure with recurrences.
1. Intuition First
This chapter matters because not every recursive algorithm is backtracking. Backtracking explores many possible futures. Divide and conquer solves the same kind of smaller problem repeatedly and then combines the answers.
A simple real-world analogy is grading a huge stack of papers:
- split the stack in half
- solve each half the same way
- combine the results when needed
The core mental model is:
- divide the problem into smaller independent subproblems
- conquer the subproblems recursively
- combine their answers
- analyze the recurrence this creates
The most common beginner confusion point is thinking recursion alone means divide and conquer. It does not. A recursive algorithm is divide and conquer only when the subproblems are structurally smaller versions of the same problem and there is a meaningful combine step.
This chapter closes the non-DP part of Part VI. Backtracking focused on search trees. Divide and conquer focuses on recurrence structure. That sets up the next chapter, where overlapping subproblems turn recurrences into dynamic programming.
2. Core Concepts and Techniques
Concept Cluster: Divide-and-Conquer Strategy
Key concepts in this block:
- 30.1 Divide-and-conquer strategy
Intuition
Break the problem into smaller pieces of the same type, solve them, then merge the partial answers.
Why It Matters
This pattern produces many fast algorithms and gives a clean way to reason about recursion.
How It Works
Most divide-and-conquer algorithms answer three questions:
- how do I split the problem
- what is the base case
- how do I combine the sub-results
Java Implementation Notes
- Keep recursive boundaries explicit with
leftandright. - Prefer
mid = left + (right - left) / 2to avoid overflow. - Separate the combine step into its own helper when useful.
Common Mistakes
- vague base cases
- forgetting the combine cost in complexity analysis
- splitting into overlapping subproblems and pretending it is the same pattern
Quick Example
Merge sort splits an array into halves, sorts both halves, then merges them.
Debugging Tip
Write the recurrence before the code. It exposes missing split or combine logic early.
Advanced Note
When subproblems overlap heavily, divide and conquer often transitions into dynamic programming.
Concept Cluster: Merge Sort as a Case Study
Key concepts in this block:
- 30.2 Merge sort as a case study
Intuition
Sort the left half, sort the right half, then merge two sorted halves.
Why It Matters
Merge sort is the cleanest divide-and-conquer sorting algorithm and a standard recurrence example.
How It Works
Recursively split until subarrays of size 1, then merge sorted pieces in linear time.
Java Implementation Notes
- Use one reusable buffer array.
- Keep merge logic stable by taking from the left side first on equal values.
- In-place merge is possible but not the beginner-friendly version.
Common Mistakes
- wrong copy-back indices
- forgetting the base case
- allocating too many temporary arrays in every recursive call
Quick Example
[5, 2, 4, 1] becomes [5, 2] and [4, 1], then [2, 5] and [1, 4], then [1, 2, 4, 5].
Debugging Tip
Print the current (left, mid, right) ranges before each merge.
Advanced Note
The merge idea also powers inversion counting and many range problems.
Concept Cluster: Quick Sort as a Case Study
Key concepts in this block:
- 30.3 Quick sort as a case study
Intuition
Choose a pivot, partition the array around it, then sort the two sides.
Why It Matters
Quick sort shows how the divide step itself can rearrange the data and how pivot quality affects performance.
How It Works
Partition so that:
- elements less than the pivot move left
- elements greater than or equal to the pivot move right
Then recurse on the two sides.
Java Implementation Notes
- Randomized pivot choice avoids predictable worst-case patterns.
- In-place partitioning saves memory.
- The recursion excludes the pivot's final position.
Common Mistakes
- wrong partition boundaries
- forgetting to move the pivot into place
- using a fixed bad pivot on already sorted input
Quick Example
For [4, 1, 6, 2, 5], pivot 4 can partition the array into [1, 2], 4, and [6, 5].
Debugging Tip
Print the array after every partition, not only after the full recursive call.
Advanced Note
Quick sort is fast on average but not stable and not worst-case safe without care.
Concept Cluster: Binary Search as Divide and Conquer
Key concepts in this block:
- 30.4 Binary search as divide and conquer
Intuition
Discard half the search range after one comparison.
Why It Matters
This is the simplest divide-and-conquer search algorithm and a clean reminder that the technique is broader than sorting.
How It Works
Compare the target with the middle element:
- if equal, return the index
- if smaller, recurse on the left half
- if larger, recurse on the right half
Java Implementation Notes
- Use explicit
leftandrightbounds. - Decide whether the interval is closed or half-open and keep it consistent.
- Midpoint overflow still matters in Java.
Common Mistakes
- off-by-one errors in bounds
- infinite recursion when the interval does not shrink
- using binary search on unsorted data
Quick Example
Searching for 7 in [1, 3, 5, 7, 9] compares 7 with 5, then only the right half remains.
Debugging Tip
Print the current (left, right, mid) triple on every call.
Advanced Note
Earlier chapters already used binary search as a pattern. Here the emphasis is the divide-and-conquer structure behind it.
Concept Cluster: Closest Pair Problem
Key concepts in this block:
- 30.5 Closest pair problem
Intuition
Find the best pair in the left half, the best pair in the right half, then check only a narrow strip near the middle for cross-border candidates.
Why It Matters
This is a classic example where divide and conquer beats a natural quadratic brute-force baseline.
How It Works
Sort points by x, recurse on halves, merge by y, and only compare nearby points in the vertical strip of width bestDistance.
Java Implementation Notes
- Keep the points sorted by
xinitially. - Maintain segments sorted by
yduring the recursion. - Use
Math.hypotor squared distance carefully.
Common Mistakes
- checking too many strip points and losing the
O(n log n)bound - using the midpoint after the array has already been reordered by
y - forgetting the base-case brute-force computation
Quick Example
If the best left-half distance is 3 and best right-half distance is 4, only points within 3 of the dividing line can beat the current answer.
Debugging Tip
Store the midpoint x value before recursive calls reorder anything.
Advanced Note
Closest pair is a strong example of how careful combine-step geometry changes the complexity class.
Concept Cluster: Recurrence Thinking and Solution Structure
Key concepts in this block:
- 30.6 Recurrence thinking and solution structure
Intuition
Every divide-and-conquer algorithm creates a recurrence that describes its work.
Why It Matters
If you can state the recurrence, you can usually predict the complexity before finishing the code.
How It Works
Typical examples:
- merge sort:
T(n) = 2T(n / 2) + O(n) - binary search:
T(n) = T(n / 2) + O(1) - quick sort average case:
T(n) = T(left) + T(right) + O(n)
Java Implementation Notes
- Write the split, base case, and combine step as separate logical units.
- If the combine step is expensive, it usually dominates the recurrence.
- Keep helper arrays reusable when possible.
Common Mistakes
- ignoring the combine term
- assuming balanced splits when the algorithm does not guarantee them
- analyzing average-case behavior as if it were worst-case
Quick Example
Binary search drops to one half each time, so after about log n levels, the range is size 1.
Debugging Tip
When the runtime surprises you, check whether the split is balanced and whether the combine step is really linear.
Advanced Note
The next chapter turns recurrence thinking into DP once the same states start repeating.
3. Worked Examples and Full Solutions
Worked Example 1: Merge Sort
Problem Statement
Given an integer array, sort it in nondecreasing order using merge sort.
Why This Example Matters
This is the canonical divide-and-conquer algorithm. It cleanly shows split, solve, and combine.
Constraints or Assumptions
- the input may contain duplicates
- stable output is preferred
- sorting should be done in place with one helper buffer
Brute-Force Approach
Use a simple quadratic sorting algorithm such as insertion sort or bubble sort.
That works on small arrays, but it degrades to O(n^2).
Better Approach
Use merge sort.
Why the Better Approach Works
Each recursive call solves half the array. Since both halves are sorted afterward, a linear-time merge produces one sorted whole.
Pragmatic Java Choice
Use:
- one helper buffer array
- recursive ranges
[left, right] - a stable merge that takes from the left side first on ties
Java Solution
class MergeSortCaseStudyExample {
static void mergeSort(int[] values) {
if (values.length <= 1) {
return;
}
int[] buffer = new int[values.length];
sort(values, buffer, 0, values.length - 1);
}
private static void sort(int[] values, int[] buffer, int left, int right) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
sort(values, buffer, left, mid);
sort(values, buffer, mid + 1, right);
merge(values, buffer, left, mid, right);
}
private static void merge(int[] values, int[] buffer, int left, int mid, int right) {
int first = left;
int second = mid + 1;
int index = left;
while (first <= mid && second <= right) {
if (values[first] <= values[second]) {
buffer[index++] = values[first++];
} else {
buffer[index++] = values[second++];
}
}
while (first <= mid) {
buffer[index++] = values[first++];
}
while (second <= right) {
buffer[index++] = values[second++];
}
for (int i = left; i <= right; i++) {
values[i] = buffer[i];
}
}
}
Dry Run
Input: [5, 2, 4, 1]
Split:
[5, 2]and[4, 1]- then
[5],[2],[4],[1]
Merge:
[5]and[2]->[2, 5][4]and[1]->[1, 4][2, 5]and[1, 4]->[1, 2, 4, 5]
Time and Space Complexity
Quadratic baseline:
- Time:
O(n^2) - Space:
O(1)or small auxiliary space depending on the sort
Merge sort:
- Time:
O(n log n) - Space:
O(n)
Edge Cases
- empty array
- already sorted array
- reverse-sorted array
- many duplicate values
Common Mistakes
- off-by-one merge boundaries
- not copying merged values back
- allocating new arrays at every merge without reason
Worked Example 2: In-Place Quick Sort
Problem Statement
Given an integer array, sort it using in-place quick sort.
Why This Example Matters
Quick sort shows a different divide-and-conquer shape: the divide step is a partition, and the split quality controls the runtime.
Constraints or Assumptions
- in-place mutation is allowed
- duplicate values may exist
- randomized pivot selection is preferred
Brute-Force Approach
Create new temporary arrays left, equal, and right around a pivot at every step, recursively sort the sides, then concatenate.
That is easier to explain, but it uses extra memory and more copying than necessary.
Better Approach
Use in-place partitioning with a randomized pivot.
Why the Better Approach Works
After partitioning, the pivot is already in its final position. The left and right partitions can then be sorted independently.
Pragmatic Java Choice
Use:
- randomized pivot selection
- Lomuto partition for clarity
- recursive range sorting
Java Solution
import java.util.Random;
class QuickSortCaseStudyExample {
private static final Random RANDOM = new Random(0);
static void quickSort(int[] values) {
sort(values, 0, values.length - 1);
}
private static void sort(int[] values, int left, int right) {
if (left >= right) {
return;
}
int pivotIndex = left + RANDOM.nextInt(right - left + 1);
swap(values, pivotIndex, right);
int partitionIndex = partition(values, left, right);
sort(values, left, partitionIndex - 1);
sort(values, partitionIndex + 1, right);
}
private static int partition(int[] values, int left, int right) {
int pivot = values[right];
int smallerIndex = left;
for (int current = left; current < right; current++) {
if (values[current] < pivot) {
swap(values, current, smallerIndex);
smallerIndex++;
}
}
swap(values, smallerIndex, right);
return smallerIndex;
}
private static void swap(int[] values, int first, int second) {
int temporary = values[first];
values[first] = values[second];
values[second] = temporary;
}
}
Dry Run
Input: [4, 1, 6, 2, 5]
If pivot 4 is chosen:
- partition produces
[1, 2, 4, 6, 5] - recurse on
[1, 2]and[6, 5] - final result becomes
[1, 2, 4, 5, 6]
Time and Space Complexity
Copy-heavy baseline:
- Time: average
O(n log n) - Space:
O(n log n)or more due to repeated temporary arrays
In-place quick sort:
- Average Time:
O(n log n) - Worst-Case Time:
O(n^2) - Space: average
O(log n)recursion depth
Edge Cases
- already sorted input if pivot choice is poor
- many equal values
- one-element array
- empty array
Common Mistakes
- wrong partition boundaries
- forgetting to exclude the pivot's final index from recursion
- assuming quick sort is worst-case safe without randomized or careful pivots
Worked Example 3: Recursive Binary Search
Problem Statement
Given a sorted array and a target, return the target index or -1 if it does not exist.
Why This Example Matters
This is the smallest divide-and-conquer example in the chapter and a clean way to reason about recurrence depth.
Constraints or Assumptions
- the input array is sorted in nondecreasing order
- any matching index is acceptable
- use recursive divide and conquer
Brute-Force Approach
Scan the array left to right until the target is found.
That costs O(n).
Better Approach
Use binary search to discard half the array after each comparison.
Why the Better Approach Works
Because the array is sorted, one comparison with the middle element proves that the target cannot lie in one entire half.
Pragmatic Java Choice
Use:
- closed interval bounds
[left, right] - overflow-safe midpoint
- recursion for the chapter's divide-and-conquer framing
Java Solution
class BinarySearchDivideConquerExample {
static int binarySearch(int[] values, int target) {
return search(values, target, 0, values.length - 1);
}
private static int search(int[] values, int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (values[mid] == target) {
return mid;
}
if (target < values[mid]) {
return search(values, target, left, mid - 1);
}
return search(values, target, mid + 1, right);
}
}
Dry Run
Array: [1, 3, 5, 7, 9, 11], target 9
left = 0,right = 5,mid = 2, value5- target is larger, recurse on
[3, 5] mid = 4, value9, found
Time and Space Complexity
Linear scan:
- Time:
O(n) - Space:
O(1)
Binary search:
- Time:
O(log n) - Space:
O(log n)due to recursion
Edge Cases
- empty array
- target smaller than all elements
- target larger than all elements
- duplicates, where any matching index may be returned
Common Mistakes
- wrong base case when
left > right - midpoint overflow if written carelessly
- using binary search on unsorted input
Worked Example 4: Closest Pair of Points
Problem Statement
Given points in the plane, return the minimum Euclidean distance between any two points.
Why This Example Matters
This is the chapter's advanced transfer example. It shows divide and conquer beating the obvious quadratic baseline with a carefully designed combine step.
Constraints or Assumptions
- there may be many points
- duplicate points imply distance
0 - return the distance as a
double
Brute-Force Approach
Check every pair of points and keep the minimum distance.
That is O(n^2).
Better Approach
Sort by x, split in half, recurse, then inspect only the narrow cross-border strip.
Why the Better Approach Works
Any cross-border pair that beats the current best distance must lie close to the dividing line. After sorting by y inside the strip, only a constant number of nearby points must be checked for each point.
Pragmatic Java Choice
Use:
- a
Pointclass - one array sorted by
x - a reusable buffer for merge-by-
y
Java Solution
import java.util.Arrays;
import java.util.Comparator;
class ClosestPairCaseStudyExample {
private static final Comparator<Point> BY_X =
Comparator.comparingDouble((Point point) -> point.x).thenComparingDouble(point -> point.y);
private static final Comparator<Point> BY_Y =
Comparator.comparingDouble((Point point) -> point.y).thenComparingDouble(point -> point.x);
static final class Point {
final double x;
final double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
}
static double closestPairDistance(Point[] points) {
if (points.length < 2) {
return Double.POSITIVE_INFINITY;
}
Point[] byX = points.clone();
Arrays.sort(byX, BY_X);
Point[] buffer = new Point[points.length];
return solve(byX, buffer, 0, points.length - 1);
}
private static double solve(Point[] points, Point[] buffer, int left, int right) {
if (right - left <= 3) {
double best = bruteForce(points, left, right);
Arrays.sort(points, left, right + 1, BY_Y);
return best;
}
int mid = left + (right - left) / 2;
double midX = points[mid].x;
double leftBest = solve(points, buffer, left, mid);
double rightBest = solve(points, buffer, mid + 1, right);
double best = Math.min(leftBest, rightBest);
mergeByY(points, buffer, left, mid, right);
int stripSize = 0;
for (int i = left; i <= right; i++) {
if (Math.abs(points[i].x - midX) < best) {
buffer[stripSize++] = points[i];
}
}
for (int i = 0; i < stripSize; i++) {
for (int j = i + 1; j < stripSize && (buffer[j].y - buffer[i].y) < best; j++) {
best = Math.min(best, distance(buffer[i], buffer[j]));
}
}
return best;
}
private static double bruteForce(Point[] points, int left, int right) {
double best = Double.POSITIVE_INFINITY;
for (int i = left; i <= right; i++) {
for (int j = i + 1; j <= right; j++) {
best = Math.min(best, distance(points[i], points[j]));
}
}
return best;
}
private static void mergeByY(Point[] points, Point[] buffer, int left, int mid, int right) {
int first = left;
int second = mid + 1;
int index = left;
while (first <= mid && second <= right) {
if (BY_Y.compare(points[first], points[second]) <= 0) {
buffer[index++] = points[first++];
} else {
buffer[index++] = points[second++];
}
}
while (first <= mid) {
buffer[index++] = points[first++];
}
while (second <= right) {
buffer[index++] = points[second++];
}
for (int i = left; i <= right; i++) {
points[i] = buffer[i];
}
}
private static double distance(Point first, Point second) {
return Math.hypot(first.x - second.x, first.y - second.y);
}
}
Dry Run
Points:
(0, 0)(2, 3)(3, 4)(7, 7)(8, 8)
Split around the midpoint by x.
Suppose left half best distance is about 1.41 and right half best distance is also about 1.41.
Then only points within 1.41 of the dividing line enter the strip. The combine step checks only nearby strip points, not all cross pairs.
Time and Space Complexity
Brute force:
- Time:
O(n^2) - Space:
O(1)extra
Divide and conquer:
- Time:
O(n log n) - Space:
O(n)
Edge Cases
- fewer than two points
- duplicate points with distance
0 - many points sharing the same
xory - floating-point formatting of the answer
Common Mistakes
- recomputing strip comparisons quadratically
- using the midpoint after recursive reordering changed the array
- forgetting to keep the segment sorted by
yon return
4. Complexity and Decision Guide
Main trade-offs in this chapter:
- merge sort:
O(n log n)time,O(n)space - quick sort: average
O(n log n)time, worst-caseO(n^2), low extra space - binary search:
O(log n)time - closest pair:
O(n log n)instead ofO(n^2)
When to choose divide and conquer:
- the problem splits into smaller independent pieces
- the combine step is cheaper than solving the original problem directly
- the recursive structure is clear and repeatable
Recognition signals:
- "split into halves"
- "sort or solve both sides, then merge"
- "discard half the search space"
- "cross-border interactions are limited and structured"
Signals not to force this technique:
- if the same subproblem repeats heavily, DP may be better
- if the search explores many possible decisions, backtracking may be the right model
- if the combine step is as expensive as re-solving everything, the split may not help
A practical rule:
- write the recurrence first
- if the recurrence improves meaningfully over the baseline, the divide-and-conquer design is probably worth it
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- wrong midpoint calculations
- missing or weak base cases
- bad partition boundaries in quick sort
- incorrect merge indices in merge sort
- losing sorted-by-
ystructure in closest pair
Boundary handling:
- empty arrays and one-element arrays should terminate immediately
- already sorted input can expose quick sort pivot problems
- duplicate values and duplicate points should not break correctness
- recursive intervals must shrink every time
Short debugging checklist:
- verify every recursive call reduces the problem size
- verify the base case returns immediately and correctly
- print split boundaries on small examples
- for merge sort, print arrays before and after merge
- for quick sort, print the array after each partition
- for closest pair, verify the strip is narrow and sorted by
y
6. Practice Problems
Easy
- Title: Binary Search in a Sorted Array. One-line prompt: return the index of a target in sorted data or
-1. Expected pattern or core idea: divide the interval in half each step. - Title: Sort an Array with Merge Sort. One-line prompt: implement stable
O(n log n)sorting on integers. Expected pattern or core idea: split, sort halves, merge. - Title: First Bad Version. One-line prompt: find the first failing version with as few checks as possible. Expected pattern or core idea: binary search on a monotonic predicate.
Medium
- Title: Quick Sort Implementation. One-line prompt: sort an array in place using partition-based recursion. Expected pattern or core idea: pivot partitioning.
- Title: Count Inversions. One-line prompt: count how many index pairs are out of order. Expected pattern or core idea: merge-sort-based divide and conquer.
- Title: Median of Two Sorted Arrays. One-line prompt: find the median without fully merging both arrays. Expected pattern or core idea: divide and conquer over sorted structure.
Hard
- Title: Closest Pair of Points. One-line prompt: find the smallest distance among all point pairs faster than quadratic time. Expected pattern or core idea: geometric divide and conquer.
- Title: Kth Smallest in Two Sorted Arrays. One-line prompt: discard blocks of candidates recursively until the answer remains. Expected pattern or core idea: divide and conquer on ranks.
- Title: External Merge Planning. One-line prompt: design a large-data merge workflow with predictable recursion and combine costs. Expected pattern or core idea: recurrence thinking and solution structure.
7. Short Recap
The core idea of this chapter is that divide and conquer solves smaller independent pieces and combines their answers systematically.
The most important optimization insight is that the split and combine design changes the recurrence, which changes the complexity class.
The most important implementation warning is to get the boundaries and base cases exactly right.
This chapter prepares the next chapter by turning recurrence thinking into dynamic programming when subproblems start overlapping.
8. Coverage Check
- 30.1 Divide-and-conquer strategy
- 30.2 Merge sort as a case study
- 30.3 Quick sort as a case study
- 30.4 Binary search as divide and conquer
- 30.5 Closest pair problem
- 30.6 Recurrence thinking and solution structure
Coverage Summary: 6/6 official subtopics covered
This must always be 6/6 before final output
Next: 31: Dynamic Programming Foundations
31: Dynamic Programming Foundations
Goal: Teach how dynamic programming turns repeated recursive work into reusable state transitions, and how to design states and recurrences with precision.
Outcome: By the end of this chapter, you can recognize overlapping subproblems and optimal substructure, choose between memoization and tabulation, define DP state clearly, and write correct transitions for foundational problems in Java.
1. Intuition First
This chapter matters because many brute-force recursive solutions repeat the same work again and again. Dynamic programming, usually shortened to DP, removes that waste by storing answers to smaller states and reusing them.
A simple real-world analogy is trip planning across multiple cities. If you already computed the cheapest cost from city C to the destination, you should not recompute that same suffix of the trip every time another route reaches C.
The core mental model is:
- define a state that captures exactly what still needs to be solved
- express the answer for that state using smaller states
- store results so each state is solved once
The most common beginner confusion point is thinking DP means "use an array and loop." That is too shallow. DP is really about repeated states and a correct recurrence. Arrays, maps, recursion, and loops are only implementation choices.
This chapter starts Part VI's shift from pattern recognition into formal state design. Earlier chapters trained you to see structures like trees, graphs, and divide and conquer. This chapter teaches how to model problems where many partial decisions lead back to the same smaller subproblem.
2. Core Concepts and Techniques
Concept Cluster: Repeated Work and Structural Choice
Key concepts in this block:
- 31.1 Overlapping subproblems
- 31.2 Optimal substructure
Intuition
If many recursive paths ask for the answer to the same smaller question, the problem has overlapping subproblems. If the best answer to a bigger problem can be assembled from best answers to smaller problems, the problem has optimal substructure.
Why It Matters
Without these two properties, DP is usually the wrong tool. Overlap tells you caching is useful. Optimal substructure tells you combining smaller optimal answers can still produce a larger optimal answer.
How It Works
For Fibonacci, fib(5) asks for fib(4) and fib(3), and fib(4) also asks for fib(3). That repeated fib(3) is overlap.
For shortest cost problems, if the best way to reach step i depends on the best way to reach earlier steps plus one local cost, that is optimal substructure.
Java Implementation Notes
- Use an
int[],long[], orInteger[]when the state is indexed by position. - Use a
HashMap<State, Answer>when the state is sparse or multi-dimensional. - Make the state definition explicit in method parameters before coding transitions.
Common Mistakes
- forcing DP onto a problem with no repeated states
- assuming greedy local choices imply optimal substructure
- storing answers before the state is fully defined
Quick Example
In a staircase problem, if state dp[i] means the number of ways to reach step i, then every state uses a small set of earlier states instead of recomputing the full recursion tree.
Debugging Tip
Draw the recursion tree for a tiny input. If the same state label appears many times, you probably have overlap.
Advanced Note
Optimal substructure is not enough by itself. Many graph problems have optimal substructure but still need shortest-path or matching algorithms rather than plain DP.
Concept Cluster: Two Main DP Execution Styles
Key concepts in this block:
- 31.3 Memoization
- 31.4 Tabulation
Intuition
Memoization solves states on demand with recursion and a cache. Tabulation fills states in a deliberate order, usually with loops.
Why It Matters
The recurrence may be the same, but implementation trade-offs differ:
- memoization matches the mathematical recurrence closely
- tabulation avoids recursion depth and gives tighter control over evaluation order
How It Works
Memoization pattern:
- ask for the target state
- recursively ask for smaller states
- cache the answer before returning
Tabulation pattern:
- decide an order where dependencies are already known
- initialize base states
- fill larger states from smaller ones
Java Implementation Notes
Integer[] memois convenient when0could be a valid answer and you neednullas "not computed yet."- For tabulation, define the meaning of
dp[i]in one sentence before writing the loop. - Watch recursion depth on large inputs; Java does not optimize tail recursion.
Common Mistakes
- forgetting to cache before returning in memoization
- filling the table in an order that uses uninitialized states
- mixing two different state meanings in one array
Quick Example
For Fibonacci:
- memoization computes only needed states recursively
- tabulation starts from
dp[0]anddp[1], then builds upward
Debugging Tip
For tabulation, print the dp array after each iteration for a tiny input. For memoization, log each state the first time it is computed.
Advanced Note
Memoization is often best for irregular state graphs. Tabulation is often best when the dependency order is clear and all states are likely to be needed.
Concept Cluster: Modeling the DP Correctly
Key concepts in this block:
- 31.5 Defining state correctly
- 31.6 Designing transitions
Intuition
Most DP bugs begin before the code. They begin with a vague or wrong state definition.
Why It Matters
If the state is too small, it loses information and produces wrong answers. If it is too large, the DP becomes slow, memory-heavy, or unnecessarily complicated.
How It Works
Ask these questions:
- what decision or progress marker uniquely describes the remaining problem
- what smaller states can lead into this state, or out of it
- what is the base case
- in what order can these states be computed
Then write the transition as a sentence before turning it into code.
Example sentence:
"The minimum cost to reach index i is the current cost plus the minimum of the best cost to reach i - 1 and i - 2."
Java Implementation Notes
- Use descriptive names such as
bestCostAtIndex,waysToReach, orcanBreakPrefix. - Keep base cases close to the state definition.
- If a transition depends on impossible states, use a clear sentinel like a large constant or
false.
Common Mistakes
- defining state as "the answer so far" instead of "the problem remaining"
- forgetting whether the state includes or excludes the current element
- writing a recurrence that does not shrink toward a base case
Quick Example
For word break, a useful state is: dp[end] means whether the prefix s[0..end) can be segmented. That state gives a clean transition over earlier cut positions.
Debugging Tip
For every state variable, say out loud what it means on one concrete input. If that sentence sounds ambiguous, the state is not ready.
Advanced Note
Many hard DP problems are not hard because of syntax. They are hard because the correct state is non-obvious.
3. Worked Examples and Full Solutions
Worked Example 1: Fibonacci Numbers
Problem Statement
Given n, return the nth Fibonacci number where fib(0) = 0 and fib(1) = 1.
Why This Example Matters
This is the cleanest introduction to overlapping subproblems, memoization, and tabulation.
Constraints or Assumptions
- assume
0 <= n <= 45forint - larger inputs should use
longorBigInteger - the goal is clarity, not cleverness
Brute-Force Approach
Use the direct recursive definition:
fib(n) = fib(n - 1) + fib(n - 2)
This is easy to write but repeats the same states many times.
Better Approach
Use tabulation or memoization so each fib(k) is computed once.
Why the Better Approach Works
The recurrence only depends on two smaller states. Once those answers are known, the current answer is fixed. There is no need to recompute them.
Pragmatic Java Choice
Use tabulation here because the dependency order is obvious and every state from 0 to n is needed.
Java Solution
class FibonacciDpExample {
static int fibonacci(int n) {
if (n <= 1) {
return n;
}
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int index = 2; index <= n; index++) {
dp[index] = dp[index - 1] + dp[index - 2];
}
return dp[n];
}
}
Dry Run
Input: n = 6
dp[0] = 0dp[1] = 1dp[2] = 1dp[3] = 2dp[4] = 3dp[5] = 5dp[6] = 8
Answer: 8
Time and Space Complexity
Brute-force recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP tabulation:
- Time:
O(n) - Space:
O(n)
Edge Cases
n = 0n = 1- values large enough to overflow
int
Common Mistakes
- forgetting the
n = 0base case - treating an uninitialized array cell as a computed answer in memoization
- using recursion for very large
nin Java without considering stack depth
Worked Example 2: Minimum Cost to Reach the Last Index
Problem Statement
You are given an array costs where costs[i] is the cost of landing on index i. Start at index 0, and at each move you may jump to i + 1 or i + 2. Return the minimum total cost needed to reach the last index.
Why This Example Matters
This example makes optimal substructure concrete and shows how state meaning drives a clean transition.
Constraints or Assumptions
costs.length >= 1- all costs are nonnegative integers
- you must include the landing cost for visited indices
Brute-Force Approach
From each index, recursively try both jumps and return the cheaper choice.
That explores an exponential number of repeated states.
Better Approach
Use memoization or tabulation with:
dp[i] = minimum cost to reach index i
Why the Better Approach Works
To reach index i, the previous position must be either i - 1 or i - 2. So the best answer for i depends only on the best answers for those two smaller states.
Pragmatic Java Choice
Use tabulation because the state order is strictly left to right and the transition is small.
Java Solution
class MinimumCostJumpExample {
static int minimumCost(int[] costs) {
int n = costs.length;
if (n == 1) {
return costs[0];
}
int[] dp = new int[n];
dp[0] = costs[0];
dp[1] = costs[0] + costs[1];
for (int index = 2; index < n; index++) {
dp[index] = costs[index] + Math.min(dp[index - 1], dp[index - 2]);
}
return dp[n - 1];
}
}
Dry Run
Input: costs = [1, 4, 2, 7, 3]
dp[0] = 1dp[1] = 5dp[2] = 2 + min(5, 1) = 3dp[3] = 7 + min(3, 5) = 10dp[4] = 3 + min(10, 3) = 6
Answer: 6
The cheapest route is indices 0 -> 2 -> 4.
Time and Space Complexity
Brute-force recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP tabulation:
- Time:
O(n) - Space:
O(n)
Edge Cases
- one-element array
- two-element array
- all zero costs
Common Mistakes
- defining
dp[i]as cost from indexito the end, then accidentally coding transitions for cost to reachi - forgetting the exact meaning of the starting cost
- mixing jump count with total cost in the same state
Worked Example 3: Word Break Decision
Problem Statement
Given a string text and a dictionary of valid words, return true if text can be split into a sequence of dictionary words, otherwise return false.
Why This Example Matters
This is a transfer example. The recurrence is not numeric, but the same DP ideas still apply: define the prefix state and build correct transitions.
Constraints or Assumptions
- dictionary lookup should be efficient
- exact case-sensitive matches are used
- return only whether a split exists, not the split itself
Brute-Force Approach
Try every cut position recursively. For each prefix that is a valid word, recursively solve the suffix.
That can revisit the same suffix many times.
Better Approach
Use tabulation on prefixes:
dp[end]istrueiftext[0..end)can be segmented
Why the Better Approach Works
If there exists a cut position start such that:
dp[start]istruetext[start..end)is in the dictionary
then dp[end] is also true.
Pragmatic Java Choice
Use a HashSet<String> for dictionary membership and a boolean array over prefix lengths.
Java Solution
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class WordBreakDpExample {
static boolean canSegment(String text, List<String> words) {
Set<String> dictionary = new HashSet<>(words);
boolean[] dp = new boolean[text.length() + 1];
dp[0] = true;
for (int end = 1; end <= text.length(); end++) {
for (int start = 0; start < end; start++) {
if (dp[start] && dictionary.contains(text.substring(start, end))) {
dp[end] = true;
break;
}
}
}
return dp[text.length()];
}
}
Dry Run
Input:
text = "applepenapple"words = ["apple", "pen"]
State meaning: dp[end] tells whether the prefix ending before end can be segmented.
dp[0] = trueend = 5, substringtext[0..5) = "apple", sodp[5] = trueend = 8, substringtext[5..8) = "pen"anddp[5] = true, sodp[8] = trueend = 13, substringtext[8..13) = "apple"anddp[8] = true, sodp[13] = true
Answer: true
Time and Space Complexity
Brute-force recursion:
- Time: exponential in the worst case
- Space:
O(n)recursion depth
DP tabulation:
- Time:
O(n^2)substring checks, ignoring substring-copy costs in modern Java discussions - Space:
O(n + d)wheredis dictionary storage
Edge Cases
- empty string
- dictionary with overlapping words such as
"cat"and"cats" - no valid segmentation
Common Mistakes
- confusing
dp[i]as "suffix from i works" while coding a prefix DP - not setting
dp[0] = true - forgetting that substring boundaries in Java use half-open intervals
4. Complexity and Decision Guide
The main trade-offs in this chapter are not about one specific algorithm. They are about execution style and modeling quality.
- brute-force recursion is acceptable when the state space is tiny or when you are still discovering the recurrence
- memoization is a strong first implementation when the recurrence is natural but the state graph is irregular
- tabulation is often better when the dependency order is obvious, the full state space will be used, or recursion depth could be a problem
- space optimization is worth considering only after the state transition is correct and you know exactly which earlier states are still needed
Recognition signals that DP is appropriate:
- the naive recursive tree repeats the same states
- the problem asks for best count, minimum cost, maximum value, or number of ways
- the answer for a larger instance depends on a bounded set of smaller instances
Signals that you should not force DP:
- a greedy local choice can be proven correct and simpler
- the state would need to remember too much history, making the DP explode
- the problem is really a graph traversal, shortest path, or data-structure query problem in disguise
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs in foundational DP:
- wrong state meaning written in code comments or variable names
- base cases that do not match the state definition
- transitions that accidentally use future states instead of already solved states
- using
0as both a valid answer and an "uncomputed" marker - integer overflow when counts or costs become large
Boundary risks:
- empty input
- single-element input
- first row or first column style base states
- off-by-one errors when state indexes represent prefixes of length
i
State and mutation risks:
- reusing one array slot before all consumers have read the old value
- mixing global mutable state with memoized recursion
- forgetting to clear memo structures between test cases
Short debugging checklist:
- write one sentence that defines
dp[i]ordp[state] - list the exact base cases
- verify that every transition moves toward a base case
- test the smallest nontrivial input by hand
- print the first few states or table rows to confirm the evaluation order
6. Practice Problems
Easy
Title: Fibonacci Number
Prompt: Return the nth Fibonacci number.
Expected pattern or core idea: Basic memoization or tabulation over one index.
Title: Min Cost Climb Variant
Prompt: Reach the last step with jumps of size 1 or 2 and minimum total cost.
Expected pattern or core idea: Define dp[i] as best cost for step i.
Title: Count Ways to Reach Step n
Prompt: Count how many ways exist if each move is 1 or 2 steps.
Expected pattern or core idea: Recurrence with overlapping subproblems.
Medium
Title: Word Break
Prompt: Decide whether a string can be segmented into dictionary words.
Expected pattern or core idea: Prefix state and cut-position transitions.
Title: Maximum Sum of Non-Adjacent Values
Prompt: Choose numbers from an array with no adjacent picks and maximize the total.
Expected pattern or core idea: State transition between taking and skipping.
Title: Minimum Coins for Amount
Prompt: Return the minimum number of coins needed to reach a target amount.
Expected pattern or core idea: DP state for best answer per amount.
Hard
Title: Partition Array for Minimum Difference
Prompt: Split numbers into two groups so the difference of sums is as small as possible.
Expected pattern or core idea: State design over achievable sums.
Title: Decode Message with Wildcards
Prompt: Count the number of valid decodings when some characters can represent multiple digits.
Expected pattern or core idea: Careful transition design and modular counting.
Title: Boolean Parenthesization
Prompt: Count how many ways an expression can evaluate to true.
Expected pattern or core idea: Multi-parameter state and transition composition.
7. Short Recap
The core idea is that DP solves repeated subproblems once and reuses the result through a well-defined state. The most important optimization insight is that the recurrence comes first, and memoization or tabulation is just the execution strategy. The most important implementation warning is to define the state precisely before writing any array or loop. This prepares the next chapter, where these ideas are applied to standard one-dimensional DP problems.
8. Coverage Check
- 31.1 Overlapping subproblems - Covered
- 31.2 Optimal substructure - Covered
- 31.3 Memoization - Covered
- 31.4 Tabulation - Covered
- 31.5 Defining state correctly - Covered
- 31.6 Designing transitions - Covered
Coverage Summary: 6/6 official subtopics covered
Next: One-Dimensional Dynamic Programming
32: One-Dimensional Dynamic Programming
Goal: Teach how to model and solve classic linear dynamic programming problems where each state usually depends on earlier positions in a sequence.
Outcome: By the end of this chapter, you can build one-dimensional DP recurrences, solve foundational interview problems such as climbing stairs, house robber, LIS, and decode ways, and reduce memory when only a small state window is needed.
1. Intuition First
This chapter matters because many interview problems are really sequence problems in disguise. You move left to right, and each position asks, "What is the best or total answer up to here?"
A simple real-world analogy is walking across numbered stepping stones while keeping a notebook. At each stone, you write the best information you know so far, such as the cheapest cost to get here, the number of ways to get here, or the longest valid pattern ending here.
The core mental model is:
- choose a one-dimensional index such as position, amount, or prefix length
- define what
dp[i]means in one exact sentence - compute
dp[i]from earlier states that are already known
The most common beginner confusion point is writing a recurrence that sounds right but does not match the meaning of dp[i]. If the state means "best answer ending at i" and the code treats it like "best answer up to i," the implementation quietly goes wrong.
This chapter takes the DP foundations from the previous chapter and turns them into standard one-dimensional patterns. The next chapter widens the state shape into rows, columns, and pairs of indexes.
2. Core Concepts and Techniques
Concept Cluster: Introductory Linear Recurrences
Key concepts in this block:
- 32.1 Fibonacci and introductory recurrences
- 32.2 Climbing stairs
Intuition
These are the first sequence DP problems because each new state depends on a small, fixed number of earlier states.
Why It Matters
They teach the core loop pattern for one-dimensional DP and make base cases visible.
How It Works
Fibonacci uses:
dp[i] = dp[i - 1] + dp[i - 2]
Climbing stairs uses the same recurrence if each move is either 1 or 2 steps:
- ways to reach step
icome fromi - 1andi - 2
Java Implementation Notes
- Use
int[]orlong[]depending on the size of answers. - Initialize the first two states before entering the loop.
- If only the previous two states are needed, keep two variables instead of a full array.
Common Mistakes
- wrong base cases for
n = 0orn = 1 - starting the loop at the wrong index
- forgetting whether the count includes the starting position
Quick Example
For climbing stairs with n = 4, the number of ways is:
- step
1:1 - step
2:2 - step
3:3 - step
4:5
Debugging Tip
Write out the first five states by hand. If the recurrence or base case is wrong, it usually becomes obvious immediately.
Advanced Note
Many introductory recurrences are linear recurrences. Some can later be optimized with matrix methods, but that is outside this chapter's scope.
Concept Cluster: Sequence Decisions and Best Ending States
Key concepts in this block:
- 32.3 House robber
- 32.4 Longest increasing subsequence
Intuition
These problems ask you to make a decision at each position while respecting a constraint.
Why It Matters
They teach two essential one-dimensional DP shapes:
- take-or-skip transitions
- best-answer-ending-here transitions
How It Works
House robber:
dp[i]is the maximum money from the firsti + 1houses- at house
i, either skip it or take it and adddp[i - 2]
Longest increasing subsequence:
dp[i]is the length of the LIS ending at indexi- look at every earlier
j < iwherevalues[j] < values[i]
Java Implementation Notes
- For house robber, be explicit about whether
dp[i]uses prefix length or array index. - For LIS in this chapter, use the
O(n^2)DP first because it keeps the state and transition visible. - Name transitions after decisions:
skipCurrent,takeCurrent,bestEndingHere.
Common Mistakes
- mixing "ending at
i" with "best up toi" - forgetting that LIS compares values, not indices alone
- using the wrong previous state when taking the current house
Quick Example
For houses [2, 7, 9, 3]:
- best up to house
0is2 - best up to house
1is7 - best up to house
2is11 - best up to house
3is still11
Debugging Tip
If the answer seems too large, check whether your transition accidentally allows adjacent picks or invalid subsequence extensions.
Advanced Note
LIS also has an O(n log n) method, but the O(n^2) DP version is the right learning target for this chapter.
Concept Cluster: Counting Decodings and Shrinking Memory
Key concepts in this block:
- 32.5 Decode ways
- 32.6 Space optimization techniques
Intuition
Some linear DP problems count how many valid interpretations exist rather than maximizing or minimizing a value.
Why It Matters
These problems force careful handling of invalid states, boundary conditions, and limited memory.
How It Works
Decode ways uses prefix DP:
- one-digit decode if the current character is not
'0' - two-digit decode if the last two characters form a number from
10to26
Space optimization works when dp[i] depends only on a fixed number of previous states.
Java Implementation Notes
- Keep the state meaning fixed when optimizing memory.
- Use descriptive variables such as
previousOneandpreviousTwo. - When zeros are invalid in certain positions, check them before adding counts.
Common Mistakes
- treating
'0'as a standalone valid digit - overwriting a previous state before using it
- applying space optimization before confirming the full DP is correct
Quick Example
For "226":
"2","2","6""22","6""2","26"
So the answer is 3.
Debugging Tip
For counting problems, list all valid interpretations on a tiny input and compare them with your prefix states.
Advanced Note
Space optimization reduces memory, but it can make debugging harder. Keep the full array version first if the transition is still unstable.
3. Worked Examples and Full Solutions
Worked Example 1: Climbing Stairs
Problem Statement
Given n, return how many distinct ways there are to reach step n if each move is either 1 or 2 steps.
Why This Example Matters
This is the cleanest one-dimensional DP problem. It shows how a small recurrence becomes a stable loop.
Constraints or Assumptions
n >= 0- the answer fits in
intfor the test range considered here - reaching step
0counts as one empty way
Brute-Force Approach
Use recursion from step n backward:
- ways to reach
nare ways to reachn - 1plus ways to reachn - 2
That recomputes the same states many times.
Better Approach
Use tabulation over step numbers.
Why the Better Approach Works
Each state depends only on the two earlier steps. Once those are known, the current count is fixed.
Pragmatic Java Choice
Use a full array first for clarity.
Java Solution
class ClimbingStairsDpExample {
static int countWays(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 1;
}
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int step = 2; step <= n; step++) {
dp[step] = dp[step - 1] + dp[step - 2];
}
return dp[n];
}
}
Dry Run
Input: n = 5
dp[0] = 1dp[1] = 1dp[2] = 2dp[3] = 3dp[4] = 5dp[5] = 8
Answer: 8
Time and Space Complexity
Brute-force recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP tabulation:
- Time:
O(n) - Space:
O(n)
Edge Cases
n = 0n = 1- very large
nwhereintoverflows
Common Mistakes
- returning
0forn = 0 - starting the loop at
1and overwriting base cases - forgetting that this is a count, not a minimum or maximum problem
Worked Example 2: House Robber
Problem Statement
Given an array money where money[i] is the amount in house i, return the maximum amount that can be robbed without robbing two adjacent houses.
Why This Example Matters
This is the standard take-or-skip pattern. It appears in many disguised forms.
Constraints or Assumptions
money.length >= 1- values are nonnegative
- houses are arranged in a straight line, not a circle
Brute-Force Approach
At each index, either rob the current house and skip the next, or skip the current house.
That builds an exponential recursion tree.
Better Approach
Use one-dimensional DP on prefixes.
Why the Better Approach Works
For each house, the optimal answer is the better of:
- skipping the current house and keeping the previous best
- taking the current house and adding the best answer from two houses back
Pragmatic Java Choice
Use a DP array first, then note the space-optimized form.
Java Solution
class HouseRobberDpExample {
static int maxRobbedAmount(int[] money) {
int n = money.length;
if (n == 1) {
return money[0];
}
int[] dp = new int[n];
dp[0] = money[0];
dp[1] = Math.max(money[0], money[1]);
for (int index = 2; index < n; index++) {
int skipCurrent = dp[index - 1];
int takeCurrent = money[index] + dp[index - 2];
dp[index] = Math.max(skipCurrent, takeCurrent);
}
return dp[n - 1];
}
}
Dry Run
Input: money = [2, 7, 9, 3, 1]
dp[0] = 2dp[1] = 7dp[2] = max(7, 2 + 9) = 11dp[3] = max(11, 7 + 3) = 11dp[4] = max(11, 11 + 1) = 12
Answer: 12
Time and Space Complexity
Brute-force recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP tabulation:
- Time:
O(n) - Space:
O(n)
Edge Cases
- one house
- two houses
- all zero values
Common Mistakes
- using
dp[i - 1] + money[i]for the take case, which illegally allows adjacent houses - forgetting to initialize the second state correctly
- confusing circular-house variants with the linear version
Worked Example 3: Longest Increasing Subsequence
Problem Statement
Given an integer array, return the length of the longest strictly increasing subsequence.
Why This Example Matters
This problem teaches the "best answer ending here" state, which is different from prefix-maximum DP.
Constraints or Assumptions
- duplicates do not count as increasing
- the subsequence does not need to be contiguous
- use the
O(n^2)DP approach for this chapter
Brute-Force Approach
Explore all subsequences and keep the longest increasing one.
That is exponential because each element is either taken or skipped.
Better Approach
Use:
dp[i] = length of the longest increasing subsequence ending at i
Why the Better Approach Works
Any increasing subsequence ending at i must come from some earlier index j where values[j] < values[i]. So the best answer ending at i extends the best valid earlier ending state.
Pragmatic Java Choice
Use the O(n^2) DP because it makes the state and transition explicit.
Java Solution
import java.util.Arrays;
class LisDpExample {
static int longestIncreasingSubsequenceLength(int[] values) {
int n = values.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int best = 0;
for (int current = 0; current < n; current++) {
for (int previous = 0; previous < current; previous++) {
if (values[previous] < values[current]) {
dp[current] = Math.max(dp[current], dp[previous] + 1);
}
}
best = Math.max(best, dp[current]);
}
return best;
}
}
Dry Run
Input: values = [10, 9, 2, 5, 3, 7, 101, 18]
- each
dp[i]starts at1 - at value
5, it can extend2, so length becomes2 - at value
7, it can extend5or3, so length becomes3 - at value
101, it can extend7, so length becomes4
Answer: 4
One LIS is [2, 5, 7, 101].
Time and Space Complexity
Brute-force subsequence search:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP approach:
- Time:
O(n^2) - Space:
O(n)
Edge Cases
- empty array
- all equal values
- strictly decreasing array
Common Mistakes
- treating equal values as increasing
- defining
dp[i]as best answer in the prefix but coding an ending-at-itransition - forgetting to track the global maximum across all endings
Worked Example 4: Decode Ways
Problem Statement
Given a digit string where '1' maps to 'A', '2' to 'B', up to '26' to 'Z', return how many valid decodings exist.
Why This Example Matters
This problem combines one-dimensional prefix DP with strict invalid-state handling. It is a common interview trap because '0' changes the transition rules.
Constraints or Assumptions
- the string contains only digits
- empty string handling should be explicit
- leading zeros are invalid
Brute-Force Approach
At each index, try decoding one digit and, when valid, two digits.
That revisits the same suffixes many times.
Better Approach
Use prefix DP with space optimization.
Why the Better Approach Works
The number of ways to decode up to position i depends only on:
- the number of ways up to
i - 1if the current digit is valid alone - the number of ways up to
i - 2if the last two digits form a valid letter
Pragmatic Java Choice
Use two rolling variables because only the previous two states are needed.
Java Solution
class DecodeWaysDpExample {
static int decodeWays(String digits) {
if (digits.isEmpty() || digits.charAt(0) == '0') {
return 0;
}
int previousTwo = 1;
int previousOne = 1;
for (int index = 1; index < digits.length(); index++) {
int current = 0;
if (digits.charAt(index) != '0') {
current += previousOne;
}
int twoDigitValue = (digits.charAt(index - 1) - '0') * 10 + (digits.charAt(index) - '0');
if (twoDigitValue >= 10 && twoDigitValue <= 26) {
current += previousTwo;
}
previousTwo = previousOne;
previousOne = current;
}
return previousOne;
}
}
Dry Run
Input: digits = "226"
- before the loop,
previousTwo = 1,previousOne = 1 - at index
1('2'): single-digit valid and22valid, socurrent = 2 - update:
previousTwo = 1,previousOne = 2 - at index
2('6'): single-digit valid and26valid, socurrent = 3
Answer: 3
Time and Space Complexity
Brute-force recursion:
- Time: exponential in the worst case
- Space:
O(n)recursion depth
Space-optimized DP:
- Time:
O(n) - Space:
O(1)
Edge Cases
- empty string
- leading zero
- strings like
"10"and"101" - invalid strings like
"06"
Common Mistakes
- counting
'0'as a standalone letter - allowing two-digit values outside
10to26 - updating rolling variables in the wrong order
4. Complexity and Decision Guide
One-dimensional DP usually trades a naive exponential recursion for linear or quadratic time, depending on how many earlier states each position must inspect.
- introductory recurrences such as Fibonacci and climbing stairs are usually
O(n)with constant or linear space - take-or-skip patterns such as house robber are usually
O(n)because each state inspects only a constant number of earlier states - LIS with the straightforward DP is
O(n^2)because each state compares against all previous positions - decode ways is
O(n)because each prefix only checks one-digit and two-digit extensions
When to choose brute force:
- when you are first discovering the recurrence on a tiny input
- when the input size is so small that exponential exploration is acceptable
When to optimize:
- when repeated states appear immediately in the recursion tree
- when constraints suggest
nin the thousands or higher - when the transition only depends on a small fixed window of prior states and space can be reduced safely
Recognition signals for one-dimensional DP:
- the input is a linear sequence or prefix-based string problem
- the answer for index
idepends on a bounded set of earlier indices - the problem asks for count, min, max, or best valid ending state
Signals not to force this technique:
- the problem depends on two moving boundaries and is better handled by sliding window
- the structure is really a grid, tree, or graph state space
- a greedy invariant solves the problem more simply and can be justified
5. Edge Cases, Pitfalls, and Debugging
Common one-dimensional DP bugs:
- state meaning changes halfway through the implementation
- wrong initialization for the first one or two positions
- using invalid earlier states such as
i - 2wheni < 2 - reading from an already overwritten rolling variable
- mixing contiguous subarray logic with subsequence logic
Boundary risks:
- empty arrays or strings
- single-element inputs
- inputs containing zeros or duplicates when validity rules matter
Mutation and indexing risks:
- updating
previousTwobefore using it - off-by-one mistakes when state uses prefix length rather than array index
- assuming
dp[n - 1]is the answer when the state definition says the answer is the maximum over alldp[i]
Short debugging checklist:
- state what
dp[i]means on paper - verify base states for the smallest inputs
- test a case where only one transition path is valid
- test a case where multiple transition paths combine into the answer
- only after correctness is stable, reduce memory usage
6. Practice Problems
Easy
Title: Climbing Stairs
Prompt: Count how many ways there are to reach step n using moves of 1 or 2.
Expected pattern or core idea: Introductory recurrence over one index.
Title: Min Cost Stair Climb
Prompt: Reach the top with the minimum total cost when each step has an entry cost.
Expected pattern or core idea: Linear DP with min transitions.
Title: Tribonacci Number
Prompt: Return the nth value of a three-term recurrence.
Expected pattern or core idea: Small fixed dependency window and space optimization.
Medium
Title: House Robber
Prompt: Maximize robbed value without taking adjacent houses.
Expected pattern or core idea: Take-or-skip DP.
Title: Decode Ways
Prompt: Count how many valid letter decodings exist for a digit string.
Expected pattern or core idea: Prefix DP with invalid-state checks.
Title: Longest Increasing Subsequence
Prompt: Return the length of the longest strictly increasing subsequence.
Expected pattern or core idea: Best subsequence ending at each index.
Hard
Title: House Robber II
Prompt: Maximize robbed value when houses are arranged in a circle.
Expected pattern or core idea: Split into two linear one-dimensional DP runs.
Title: Delete and Earn
Prompt: Pick values for points, but taking value x prevents taking x - 1 and x + 1.
Expected pattern or core idea: Transform the frequency map into a house robber DP.
Title: Number of Longest Increasing Subsequences
Prompt: Count how many LIS solutions exist.
Expected pattern or core idea: Track length and count states together.
7. Short Recap
The core idea is to define a linear state such as position or prefix length and compute each state from earlier ones in a valid order. The most important optimization insight is that many one-dimensional DP problems only depend on a small recent window, so memory can often be reduced after correctness is confirmed. The most important implementation warning is to keep the exact meaning of dp[i] consistent. This prepares the next chapter, where DP states expand beyond one index into grids, capacities, and pairs of strings.
8. Coverage Check
- 32.1 Fibonacci and introductory recurrences - Covered
- 32.2 Climbing stairs - Covered
- 32.3 House robber - Covered
- 32.4 Longest increasing subsequence - Covered
- 32.5 Decode ways - Covered
- 32.6 Space optimization techniques - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Two-Dimensional Dynamic Programming
33: Two-Dimensional Dynamic Programming
Goal: Teach how to design DP states with two coordinates, whether those coordinates represent grid positions, capacities, or two-string prefixes.
Outcome: By the end of this chapter, you can model two-dimensional DP tables, solve grid path problems, handle knapsack-style decisions, and reason about pairwise string DPs such as LCS and edit distance in Java.
1. Intuition First
This chapter matters because some problems cannot be described by a single index. You may need both a row and a column, an item index and a remaining capacity, or two prefix lengths from two different strings.
A simple real-world analogy is filling out a travel planner on graph paper. One axis tracks where you are in one dimension of the problem, and the second axis tracks another piece of progress. Each cell summarizes the best answer for one combination of those two choices.
The core mental model is:
- define what each axis means
- define what one cell
dp[row][col]means - fill the grid or table in an order where dependencies are already known
The most common beginner confusion point is thinking two-dimensional DP is just one-dimensional DP with extra syntax. The real challenge is not the second bracket. It is making sure both axes represent the right progress variables.
This chapter extends the previous chapter's linear state design into richer state spaces. The next chapter pushes even further into advanced DP on trees, subsets, strings, and digit constraints.
2. Core Concepts and Techniques
Concept Cluster: Grid Movement States
Key concepts in this block:
- 33.1 Grid dynamic programming
- 33.2 Unique paths
- 33.3 Minimum path sum
Intuition
In grid DP, each cell depends on neighboring cells that could reach it.
Why It Matters
This is the easiest way to learn two-dimensional state flow. It also introduces careful boundary handling for the first row and first column.
How It Works
Unique paths:
dp[row][col]is the number of ways to reach cell(row, col)- if movement is only right or down, then states come from top and left
Minimum path sum:
dp[row][col]is the minimum total cost to reach(row, col)- transition uses the smaller of the top and left costs plus the current cell value
Java Implementation Notes
- Use
rowsandcolsvariables instead of repeatinggrid.lengthexpressions. - Initialize the first row and first column carefully because they have fewer incoming states.
- Keep the state meaning fixed as either count, cost, or maximum value.
Common Mistakes
- reading from
row - 1orcol - 1when on a boundary - mixing count logic with minimum-cost logic
- forgetting whether the starting cell contributes cost
Quick Example
On a 3 x 3 grid for unique paths, the top row and left column are all 1, and interior cells become sums of top and left values.
Debugging Tip
Print the table row by row for a 3 x 3 example. Grid DP errors are usually visible immediately.
Advanced Note
Some grid problems add obstacles, diagonal moves, or state flags. The same modeling principles still apply.
Concept Cluster: Item Choice and Capacity States
Key concepts in this block:
- 33.4 0/1 knapsack
- 33.5 Longest common subsequence
Intuition
These problems use two axes that represent two different kinds of progress.
Why It Matters
They show that two-dimensional DP is broader than literal grids. One axis can represent items, and the other can represent capacity, or one axis can represent a prefix of one string while the other axis represents a prefix of another.
How It Works
0/1 knapsack:
dp[item][capacity]is the best value using the firstitemitems withincapacity
Longest common subsequence:
dp[i][j]is the LCS length for the firsticharacters of one string and the firstjcharacters of the other
Java Implementation Notes
- Use prefix lengths rather than last indices when string DP boundaries are easier that way.
- For knapsack, item-first indexing often simplifies base cases.
- Keep transition branches explicit instead of compressing them into clever one-liners.
Common Mistakes
- using the current item multiple times in 0/1 knapsack
- confusing subsequence with substring in LCS
- off-by-one errors when converting from characters to prefix lengths
Quick Example
If the last characters of two prefixes match in LCS, the state extends the diagonal cell by 1.
Debugging Tip
Label rows and columns with their prefix lengths or characters. This makes transition direction easier to inspect.
Advanced Note
Knapsack and LCS are gateway problems for many more advanced two-dimensional state designs.
Concept Cluster: Edit Operations on Two Strings
Key concepts in this block:
- 33.6 Edit distance
Intuition
Edit distance asks how many single-character changes are needed to transform one string into another.
Why It Matters
It is a classic example where each state compares prefixes and chooses among multiple operation types.
How It Works
Let dp[i][j] be the minimum edits to convert the first i characters of first into the first j characters of second.
Transitions consider:
- insert
- delete
- replace or match
Java Implementation Notes
- Initialize the first row and first column as increasing edit counts.
- If characters match, carry the diagonal value forward unchanged.
- Use
Math.mincarefully so the three operations stay readable.
Common Mistakes
- forgetting that matching characters cost
0 - mixing source and target string roles in insert and delete reasoning
- not initializing the empty-prefix row and column correctly
Quick Example
Transforming "cat" to "cut" requires one replacement, so the answer is 1.
Debugging Tip
Check a tiny example where both strings are empty or one string is empty. Most edit-distance bugs appear there first.
Advanced Note
Edit distance is closely related to LCS, but the state meaning and allowed operations are different.
3. Worked Examples and Full Solutions
Worked Example 1: Unique Paths
Problem Statement
Given rows and cols, return how many distinct paths exist from the top-left cell to the bottom-right cell if you may only move right or down.
Why This Example Matters
This is the cleanest two-dimensional DP problem. It teaches cell dependencies and boundary initialization.
Constraints or Assumptions
rows >= 1cols >= 1- no blocked cells
Brute-Force Approach
Recursively try moving right and down from each cell until the destination is reached.
That repeats many cells and grows exponentially.
Better Approach
Use a two-dimensional DP table.
Why the Better Approach Works
Every path to a cell must come from exactly one of two earlier cells: the one above or the one to the left.
Pragmatic Java Choice
Use a full int[][] table first for clarity.
Java Solution
class UniquePathsDpExample {
static int countPaths(int rows, int cols) {
int[][] dp = new int[rows][cols];
for (int row = 0; row < rows; row++) {
dp[row][0] = 1;
}
for (int col = 0; col < cols; col++) {
dp[0][col] = 1;
}
for (int row = 1; row < rows; row++) {
for (int col = 1; col < cols; col++) {
dp[row][col] = dp[row - 1][col] + dp[row][col - 1];
}
}
return dp[rows - 1][cols - 1];
}
}
Dry Run
Input: rows = 3, cols = 3
Table build:
- first row:
[1, 1, 1] - first column:
[1, 1, 1] dp[1][1] = 2dp[1][2] = 3dp[2][1] = 3dp[2][2] = 6
Answer: 6
Time and Space Complexity
Brute-force recursion:
- Time: exponential in
rows + cols - Space:
O(rows + cols)recursion depth
DP table:
- Time:
O(rows * cols) - Space:
O(rows * cols)
Edge Cases
1 x 1grid- one row only
- one column only
Common Mistakes
- forgetting to initialize the first row and column
- using subtraction or minimum instead of counting logic
- returning the wrong destination cell
Worked Example 2: Minimum Path Sum
Problem Statement
Given a nonnegative integer grid, return the minimum path sum from top-left to bottom-right if you may only move right or down.
Why This Example Matters
This uses the same grid structure as unique paths, but the transition meaning changes from counting to minimizing.
Constraints or Assumptions
- grid values are nonnegative
- the starting cell cost is included
- right and down are the only moves
Brute-Force Approach
Explore both possible directions recursively from each cell and return the cheaper path.
That repeats many suffix paths.
Better Approach
Use grid DP for minimum cost accumulation.
Why the Better Approach Works
The cheapest way to reach a cell must come from the cheaper of its two incoming states.
Pragmatic Java Choice
Use a dedicated DP table instead of mutating the input grid.
Java Solution
class MinimumPathSumDpExample {
static int minimumPathSum(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int[][] dp = new int[rows][cols];
dp[0][0] = grid[0][0];
for (int row = 1; row < rows; row++) {
dp[row][0] = dp[row - 1][0] + grid[row][0];
}
for (int col = 1; col < cols; col++) {
dp[0][col] = dp[0][col - 1] + grid[0][col];
}
for (int row = 1; row < rows; row++) {
for (int col = 1; col < cols; col++) {
dp[row][col] = grid[row][col] + Math.min(dp[row - 1][col], dp[row][col - 1]);
}
}
return dp[rows - 1][cols - 1];
}
}
Dry Run
Input:
1 3 1
1 5 1
4 2 1
dp[0][0] = 1- first row becomes
[1, 4, 5] - first column becomes
[1, 2, 6] dp[1][1] = 5 + min(4, 2) = 7dp[1][2] = 1 + min(5, 7) = 6dp[2][1] = 2 + min(7, 6) = 8dp[2][2] = 1 + min(6, 8) = 7
Answer: 7
Time and Space Complexity
Brute-force recursion:
- Time: exponential in
rows + cols - Space:
O(rows + cols)recursion depth
DP table:
- Time:
O(rows * cols) - Space:
O(rows * cols)
Edge Cases
- single cell grid
- one row or one column
- large values that may approach integer limits
Common Mistakes
- forgetting to include the starting cell's cost
- mixing path count logic with path sum logic
- using uninitialized boundary states
Worked Example 3: 0/1 Knapsack
Problem Statement
Given arrays weights and values and a maximum capacity, return the maximum total value that can fit in the knapsack when each item may be used at most once.
Why This Example Matters
This is the standard two-axis DP where one axis tracks items and the other tracks capacity.
Constraints or Assumptions
weights.length == values.length- each item may be taken at most once
- all weights are positive
Brute-Force Approach
For each item, recursively choose to include or exclude it.
That explores 2^n subsets.
Better Approach
Use a DP table over item count and capacity.
Why the Better Approach Works
For each item and capacity, the best answer is either:
- skip the current item
- take the current item, if it fits, and add the best answer for the reduced capacity using earlier items only
Pragmatic Java Choice
Use a two-dimensional table first so the one-use constraint stays visually clear.
Java Solution
class KnapsackDpExample {
static int maxValue(int[] weights, int[] values, int capacity) {
int itemCount = weights.length;
int[][] dp = new int[itemCount + 1][capacity + 1];
for (int item = 1; item <= itemCount; item++) {
int weight = weights[item - 1];
int value = values[item - 1];
for (int currentCapacity = 0; currentCapacity <= capacity; currentCapacity++) {
dp[item][currentCapacity] = dp[item - 1][currentCapacity];
if (weight <= currentCapacity) {
int take = value + dp[item - 1][currentCapacity - weight];
dp[item][currentCapacity] = Math.max(dp[item][currentCapacity], take);
}
}
}
return dp[itemCount][capacity];
}
}
Dry Run
Input:
weights = [1, 3, 4, 5]values = [1, 4, 5, 7]capacity = 7
Key idea:
- after item
1, small capacities can carry value1 - after item
3, capacity4can reach value5 - after item
4, capacity7can reach value9 - item
5gives another option, but the best at capacity7remains9
Answer: 9
Time and Space Complexity
Brute-force subset recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP table:
- Time:
O(n * capacity) - Space:
O(n * capacity)
Edge Cases
- capacity
0 - no items
- all items heavier than the capacity
Common Mistakes
- using the current row instead of the previous row and accidentally allowing repeated item use
- confusing item index with prefix length
- skipping the zero-capacity base column
Worked Example 4: Edit Distance
Problem Statement
Given two strings, return the minimum number of insertions, deletions, and replacements needed to transform the first string into the second.
Why This Example Matters
This is a classic two-string DP where each state must compare characters and choose among several operations.
Constraints or Assumptions
- all operations cost
1 - exact character matches cost
0 - empty prefixes must be handled explicitly
Brute-Force Approach
Recursively try insert, delete, and replace whenever characters differ.
That revisits the same prefix pairs many times.
Better Approach
Use a two-dimensional table over prefix lengths.
Why the Better Approach Works
Each state reduces one or both prefixes. Once smaller prefix pairs are solved, the current answer is the cheapest of the valid operations.
Pragmatic Java Choice
Use prefix lengths i and j so base cases are simple.
Java Solution
class EditDistanceDpExample {
static int editDistance(String first, String second) {
int[][] dp = new int[first.length() + 1][second.length() + 1];
for (int i = 0; i <= first.length(); i++) {
dp[i][0] = i;
}
for (int j = 0; j <= second.length(); j++) {
dp[0][j] = j;
}
for (int i = 1; i <= first.length(); i++) {
for (int j = 1; j <= second.length(); j++) {
if (first.charAt(i - 1) == second.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
int insert = dp[i][j - 1];
int delete = dp[i - 1][j];
int replace = dp[i - 1][j - 1];
dp[i][j] = 1 + Math.min(replace, Math.min(insert, delete));
}
}
}
return dp[first.length()][second.length()];
}
}
Dry Run
Input: first = "horse", second = "ros"
Key steps:
- converting an empty prefix to
"ros"costs3 - matching
"o"with"o"keeps the diagonal value - mismatches choose among insert, delete, and replace
Final answer: 3
One valid sequence is:
- replace
'h'with'r' - delete one
'r'-misaligned character later in the prefix alignment - delete
'e'
Time and Space Complexity
Brute-force recursion:
- Time: exponential in the string lengths
- Space:
O(m + n)recursion depth
DP table:
- Time:
O(m * n) - Space:
O(m * n)
Edge Cases
- one or both strings empty
- identical strings
- completely different strings
Common Mistakes
- forgetting to initialize the first row and column
- charging cost
1even when characters match - mixing up insertion and deletion reasoning
4. Complexity and Decision Guide
Two-dimensional DP usually appears when a single index cannot describe enough progress.
- grid path problems usually cost
O(rows * cols)because each cell depends on a constant number of neighbors - 0/1 knapsack costs
O(n * capacity)because each item-capacity pair is one state - LCS and edit distance cost
O(m * n)because every prefix pair is a state
When to choose brute force:
- for tiny grids or tiny strings when you are still discovering the recurrence
- when the full state space is extremely small
When to optimize:
- when repeated two-dimensional states appear in the recursion
- when constraints make exponential search impossible
- when only the previous row or previous column is needed and space can be reduced carefully
Recognition signals for two-dimensional DP:
- the problem naturally uses two progress variables
- the answer depends on combining two prefixes or one prefix plus one resource limit
- the state can be drawn as a table where earlier rows or columns feed later ones
Signals not to force this technique:
- the structure is really a graph shortest-path problem with arbitrary transitions
- a greedy sort or heap approach solves the problem more directly
- the second dimension is artificial and does not correspond to real remaining information
5. Edge Cases, Pitfalls, and Debugging
Common two-dimensional DP bugs:
- wrong state meaning for rows or columns
- first row and first column initialized incorrectly
- mismatching prefix lengths with character indices
- accidentally reusing an item multiple times in 0/1 knapsack
- updating cells in the wrong traversal order when dependencies are directional
Boundary risks:
- empty strings
- grids with one row or one column
- zero capacity in knapsack
Mutation and memory risks:
- compressing to one row too early and destroying needed previous-row data
- mutating the input grid when callers expect it to remain unchanged
- using a default value such as
0when the real state should start as infinity or an impossible marker
Short debugging checklist:
- define both axes in one sentence each
- label what
dp[row][col]means exactly - verify the first row and first column on paper
- test the smallest nontrivial grid or shortest string pair
- only then attempt row compression or other space optimizations
6. Practice Problems
Easy
Title: Unique Paths
Prompt: Count paths in a grid when moves are only right or down.
Expected pattern or core idea: Two-dimensional count DP on cells.
Title: Unique Paths with Obstacles
Prompt: Count valid paths in a grid where blocked cells cannot be visited.
Expected pattern or core idea: Grid DP with blocked-state handling.
Title: Minimum Path Sum
Prompt: Return the minimum cost path from top-left to bottom-right in a grid.
Expected pattern or core idea: Grid DP using minimum incoming cost.
Medium
Title: 0/1 Knapsack
Prompt: Maximize value without exceeding capacity when each item is used at most once.
Expected pattern or core idea: Item-and-capacity state table.
Title: Longest Common Subsequence
Prompt: Return the LCS length of two strings.
Expected pattern or core idea: Prefix-pair DP on two strings.
Title: Edit Distance
Prompt: Compute the minimum edits needed to transform one string into another.
Expected pattern or core idea: Multi-operation two-string DP.
Hard
Title: Distinct Subsequences
Prompt: Count how many ways one string can form another as a subsequence.
Expected pattern or core idea: Prefix-pair counting DP.
Title: Interleaving String
Prompt: Decide whether a third string can be formed by interleaving two others.
Expected pattern or core idea: Two-dimensional boolean DP over prefix lengths.
Title: Regular Expression Matching
Prompt: Match a string against a pattern with . and *.
Expected pattern or core idea: Careful state design over string and pattern prefixes.
7. Short Recap
The core idea is to model states with two progress variables and fill a table in dependency order. The most important optimization insight is that many two-dimensional problems become straightforward once the axes and cell meaning are written down clearly. The most important implementation warning is to get boundary initialization right before trusting any interior cell. This prepares the next chapter, where DP expands to trees, subsets, digit constraints, and harder state-recognition tasks.
8. Coverage Check
- 33.1 Grid dynamic programming - Covered
- 33.2 Unique paths - Covered
- 33.3 Minimum path sum - Covered
- 33.4 0/1 knapsack - Covered
- 33.5 Longest common subsequence - Covered
- 33.6 Edit distance - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Advanced Dynamic Programming
34: Advanced Dynamic Programming
Goal: Teach how to recognize and implement richer DP state spaces on subsequences, strings, trees, subsets, and digit constraints.
Outcome: By the end of this chapter, you can design advanced DP states, solve representative problems on subsequences, strings, trees, and bitmasks, and understand the purpose and structure of digit DP.
1. Intuition First
This chapter matters because once the easy DP patterns are stable, the real challenge becomes state design. Hard DP problems usually do not fail because the loops are long. They fail because the chosen state does not capture the right information.
A simple real-world analogy is planning a tournament bracket with notes. Sometimes you only need one number. Sometimes you need position plus budget. Sometimes you need a subset of already chosen players, or whether your current digit prefix is still tied to an upper limit. The note must match the decision context exactly.
The core mental model is:
- identify what information must be remembered and what can be forgotten
- choose a state that is just large enough to make future decisions correct
- derive transitions that shrink the remaining uncertainty
The most common beginner confusion point is assuming advanced DP means bigger tables. Often the real difference is structural: trees do not have linear order, subsets use masks, and digit DP tracks constraints imposed by a numeric bound.
This chapter closes the DP sequence in Part VI. It prepares the jump into advanced problem solving, where the main skill is recognizing state shapes rather than memorizing fixed templates.
2. Core Concepts and Techniques
Concept Cluster: Sequence and String State Design
Key concepts in this block:
- 34.1 DP on subsequences
- 34.2 DP on strings
Intuition
Subsequence DP often asks whether to include or exclude the current element. String DP often compares prefix or interval states.
Why It Matters
Many hard interview problems live here because the sequence order matters, but local greedy choices are not enough.
How It Works
DP on subsequences often uses states like:
- first
ielements with target sums - best answer ending at index
i
DP on strings often uses states like:
- prefix lengths
iandj - substring interval
(left, right)
Java Implementation Notes
- Use clear state arrays such as
boolean[][] reachableorint[][] best. - For interval string DP, be explicit about whether both ends are inclusive.
- Use memoization when the interval or branching structure is easier to describe recursively.
Common Mistakes
- confusing subsequence with substring
- choosing a state that omits necessary order information
- writing transitions that accidentally reuse elements multiple times
Quick Example
For subset sum, dp[i][sum] can mean whether the first i elements can build sum. For longest palindromic subsequence, dp[left][right] can mean the best answer inside that interval.
Debugging Tip
On small examples, list the exact state names you expect to become true or nonzero. That often exposes whether the state is missing information.
Advanced Note
When the state compares intervals or prefixes, the right traversal order matters as much as the recurrence itself.
Concept Cluster: Non-Linear and Exponential-Looking State Spaces
Key concepts in this block:
- 34.3 DP on trees
- 34.4 Bitmask DP
Intuition
Some DPs are not arranged in a flat line or rectangular grid.
Why It Matters
Tree DP teaches how parent-child structure changes state flow. Bitmask DP teaches how to represent subsets compactly when n is small.
How It Works
Tree DP often uses one or more states per node, such as:
- best answer if this node is taken
- best answer if this node is skipped
Bitmask DP usually uses a state like:
dp[mask]ordp[mask][last]
where mask encodes which items are already used.
Java Implementation Notes
- In tree DP, return a small result object or array from each recursive call.
- In bitmask DP, use
1 << ncarefully and confirm thatnis small enough. - Iterate over unset bits efficiently when expanding a mask.
Common Mistakes
- mixing parent and child constraints in tree DP without isolating the states
- using bitmask DP when
nis too large for2^nstates - forgetting whether a bit represents a chosen item or an available item
Quick Example
In a tree independent-set style problem, if you take a node, you must skip its children. That naturally creates two states per node.
Debugging Tip
For tree DP, draw a three-node tree and compute states bottom-up by hand. For bitmask DP, print masks in binary for small n.
Advanced Note
Bitmask DP is powerful but only when the small-n constraint is real. If n = 25, 2^n is already too large for many interview settings.
Concept Cluster: Constraint-Aware State Recognition
Key concepts in this block:
- 34.5 Digit DP overview
- 34.6 Recognizing DP states in hard problems
Intuition
Digit DP handles questions about all numbers up to a limit by processing digits left to right while tracking whether you are still tied to the limit.
Why It Matters
It shows that advanced DP is really about encoding constraints into state rather than guessing formulas.
How It Works
A typical digit DP state may include:
- current digit position
- whether the prefix is tight with the upper bound
- whether a non-leading digit has started the number
- some property being counted, such as digit sum, previous digit, or number of occurrences
Recognizing hard DP states usually means asking:
- what exact information must the future know
- which information can be dropped safely
- whether the state graph repeats enough to justify caching
Java Implementation Notes
- Memoize digit DP with a map or multidimensional array when state bounds are manageable.
- Store the upper bound as a string for easy digit access.
- Define every boolean dimension in words before implementing.
Common Mistakes
- forgetting the tight flag
- confusing leading zeros with actual chosen digits
- adding state dimensions that are irrelevant and make the DP explode
Quick Example
To count numbers up to N with no adjacent equal digits, the state needs position, previous digit, started flag, and tight flag.
Debugging Tip
For hard DP, write the state tuple first, then test whether two different recursive paths can arrive at the same state. If yes, caching may help.
Advanced Note
Recognizing the minimal sufficient state is often the hardest step in advanced DP and the main difference between medium and hard problems.
3. Worked Examples and Full Solutions
Worked Example 1: Subset Sum Decision
Problem Statement
Given an array values and a target sum, return true if some subsequence of the array sums exactly to the target.
Why This Example Matters
This is a clean DP-on-subsequences problem. It shows include-or-exclude state design clearly.
Constraints or Assumptions
- all values are nonnegative integers
- each element may be used at most once
- only the decision, not the subsequence itself, is required
Brute-Force Approach
For each element, recursively choose whether to include or exclude it.
That explores 2^n subsets.
Better Approach
Use DP over prefix length and target sum.
Why the Better Approach Works
At each element, a target sum is reachable either without using the element or by using it and relying on a smaller target from earlier elements.
Pragmatic Java Choice
Use a boolean table because the answer is reachability, not a numeric optimum.
Java Solution
class SubsetSumDpExample {
static boolean canReachTarget(int[] values, int target) {
boolean[][] dp = new boolean[values.length + 1][target + 1];
dp[0][0] = true;
for (int index = 1; index <= values.length; index++) {
int currentValue = values[index - 1];
for (int sum = 0; sum <= target; sum++) {
dp[index][sum] = dp[index - 1][sum];
if (sum >= currentValue && dp[index - 1][sum - currentValue]) {
dp[index][sum] = true;
}
}
}
return dp[values.length][target];
}
}
Dry Run
Input: values = [3, 4, 5, 2], target = 9
- with no elements, only sum
0is reachable - after
3, sum3becomes reachable - after
4, sum7becomes reachable - after
5, sum9becomes reachable using4 + 5
Answer: true
Time and Space Complexity
Brute-force subset recursion:
- Time:
O(2^n) - Space:
O(n)recursion depth
DP table:
- Time:
O(n * target) - Space:
O(n * target)
Edge Cases
- target
0 - empty array
- values all larger than the target
Common Mistakes
- using the current row and accidentally allowing repeated picks
- forgetting that subsequence choice here means include-or-exclude, not contiguous segment
- assuming negative numbers without redesigning the state space
Worked Example 2: Longest Palindromic Subsequence
Problem Statement
Given a string text, return the length of its longest palindromic subsequence.
Why This Example Matters
This is a classic DP-on-strings example where interval state is more natural than one-direction prefix state.
Constraints or Assumptions
- the subsequence does not need to be contiguous
- matching characters at both ends can contribute to the answer
- use bottom-up interval DP
Brute-Force Approach
Explore all subsequences and test whether they are palindromes.
That is exponential.
Better Approach
Use interval DP:
dp[left][right]is the LPS length insidetext[left..right]
Why the Better Approach Works
If the end characters match, they can contribute 2 plus the best answer of the inner interval. Otherwise, the answer must come from dropping one end or the other.
Pragmatic Java Choice
Use a bottom-up table ordered by interval length.
Java Solution
class LongestPalindromicSubsequenceExample {
static int longestPalindromicSubsequence(String text) {
int n = text.length();
int[][] dp = new int[n][n];
for (int index = 0; index < n; index++) {
dp[index][index] = 1;
}
for (int length = 2; length <= n; length++) {
for (int left = 0; left + length - 1 < n; left++) {
int right = left + length - 1;
if (text.charAt(left) == text.charAt(right)) {
dp[left][right] = (length == 2) ? 2 : 2 + dp[left + 1][right - 1];
} else {
dp[left][right] = Math.max(dp[left + 1][right], dp[left][right - 1]);
}
}
}
return dp[0][n - 1];
}
}
Dry Run
Input: text = "bbbab"
- every single character interval has value
1 - interval
"bb"has value2 - larger intervals compare end characters and combine inner answers
- final answer becomes
4
One valid longest palindromic subsequence is "bbbb".
Time and Space Complexity
Brute-force subsequence search:
- Time:
O(2^n) - Space:
O(n)recursion depth
Interval DP:
- Time:
O(n^2) - Space:
O(n^2)
Edge Cases
- empty string
- one-character string
- all distinct characters
Common Mistakes
- confusing subsequence with substring
- iterating intervals in the wrong order so inner states are unavailable
- forgetting the special handling for interval length
2
Worked Example 3: Maximum Sum of Non-Adjacent Tree Nodes
Problem Statement
Given a binary tree where each node stores a nonnegative value, return the maximum sum obtainable by choosing nodes such that no chosen node has a chosen parent.
Why This Example Matters
This is a clean tree-DP problem. It shows how each node can return multiple states upward.
Constraints or Assumptions
- node values are nonnegative
- the tree may be empty
- the answer is a maximum sum, not the chosen node set itself
Brute-Force Approach
At each node, either take the node and skip its children, or skip the node and solve the children freely.
That revisits the same subtrees many times if written naively.
Better Approach
Return two values from each node:
- best sum if this node is taken
- best sum if this node is skipped
Why the Better Approach Works
The parent only needs these two summaries from each child. That is exactly the right amount of information for future decisions.
Pragmatic Java Choice
Use a helper that returns an int[] of size 2.
Java Solution
class TreeHouseRobberDpExample {
static final class TreeNode {
final int value;
final TreeNode left;
final TreeNode right;
TreeNode(int value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
}
static int maxIndependentSum(TreeNode root) {
int[] result = solve(root);
return Math.max(result[0], result[1]);
}
private static int[] solve(TreeNode node) {
if (node == null) {
return new int[] {0, 0};
}
int[] left = solve(node.left);
int[] right = solve(node.right);
int takeNode = node.value + left[1] + right[1];
int skipNode = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[] {takeNode, skipNode};
}
}
Dry Run
For a root value 3 with children 2 and 3, and grandchildren under those children:
- leaves return
{value, 0} - each parent combines child take/skip states
- the root compares taking itself plus child-skip states against skipping itself and taking the best child states
This bottom-up summary avoids recomputing subtrees.
Time and Space Complexity
Brute-force tree recursion:
- Time: exponential in the worst case
- Space:
O(h)recursion depth, wherehis tree height
Tree DP:
- Time:
O(n) - Space:
O(h)recursion depth
Edge Cases
- empty tree
- single node
- highly skewed tree
Common Mistakes
- not separating the take and skip states
- trying to use one number per node when the parent needs more information
- forgetting that children can be chosen when the current node is skipped
Worked Example 4: Minimum Assignment Cost with Bitmask DP
Problem Statement
Given a square cost matrix where costs[worker][job] is the cost of assigning one worker to one job, return the minimum total assignment cost.
Why This Example Matters
This is a standard bitmask-DP example. It shows how subsets become states when n is small.
Constraints or Assumptions
nis small enough that2^nstates are feasible- each worker gets exactly one distinct job
- the matrix is square
Brute-Force Approach
Try every permutation of job assignments.
That takes O(n!) time.
Better Approach
Use bitmask DP where mask tells which jobs are already assigned.
Why the Better Approach Works
If bitCount(mask) jobs are already used, then the next worker index is known. The future only needs to know which jobs remain available.
Pragmatic Java Choice
Use a one-dimensional DP array over masks.
Java Solution
import java.util.Arrays;
class AssignmentBitmaskDpExample {
static int minimumAssignmentCost(int[][] costs) {
int n = costs.length;
int totalMasks = 1 << n;
int[] dp = new int[totalMasks];
Arrays.fill(dp, Integer.MAX_VALUE / 4);
dp[0] = 0;
for (int mask = 0; mask < totalMasks; mask++) {
int worker = Integer.bitCount(mask);
if (worker == n) {
continue;
}
for (int job = 0; job < n; job++) {
if ((mask & (1 << job)) == 0) {
int nextMask = mask | (1 << job);
dp[nextMask] = Math.min(dp[nextMask], dp[mask] + costs[worker][job]);
}
}
}
return dp[totalMasks - 1];
}
}
Dry Run
Input:
9 2 7
6 4 3
5 8 1
mask = 000means no jobs assigned, so assign a job to worker0- from there, each new mask increases the worker count automatically
- eventually
mask = 111represents a full assignment
The best total cost is 9 from assignments:
- worker
0-> job1with cost2 - worker
1-> job0with cost6 - worker
2-> job2with cost1
Time and Space Complexity
Brute-force permutations:
- Time:
O(n!) - Space:
O(n)recursion depth
Bitmask DP:
- Time:
O(n * 2^n) - Space:
O(2^n)
Edge Cases
n = 1- equal costs in many cells
ntoo large for bitmask DP to be practical
Common Mistakes
- computing the next worker index incorrectly
- forgetting that
maskrepresents already assigned jobs, not remaining jobs - using bitmask DP on inputs too large for
2^nstates
4. Complexity and Decision Guide
Advanced DP is less about one fixed time bound and more about choosing the correct state space.
- subsequence DP often costs
O(n * target)orO(n^2)depending on the second dimension or transition fan-out - string interval or prefix-pair DP often costs
O(n^2)orO(m * n) - tree DP is often
O(n)when each node combines a constant-size summary from children - bitmask DP is usually
O(n * 2^n)orO(n^2 * 2^n), so it only works for smalln - digit DP depends on the number of positions and bounded state dimensions, often roughly
O(numberOfStates * 10)for transitions
When to choose brute force:
- when the input size is genuinely tiny and you want to uncover the state structure
- when the recurrence is still unclear and a small recursive prototype helps
When to optimize:
- when the same subtree, interval, prefix pair, or subset appears repeatedly
- when the constraints rule out factorial or exponential search
- when a compact summary can replace large raw history
Recognition signals for advanced DP:
- future choices depend on a compressed summary of the past rather than the full raw sequence
- a problem over subsets, trees, intervals, or numeric bounds shows repeated states
- the hardest part of the problem is choosing what information a state must remember
Signals not to force this technique:
- the problem has a direct graph, greedy, or data-structure solution that is simpler and provably correct
- the state dimensions explode with no meaningful repetition
- you cannot explain in one sentence what a state means
5. Edge Cases, Pitfalls, and Debugging
Common advanced DP bugs:
- state omits essential information, causing invalid merges
- state includes irrelevant information, making the DP too large
- traversal order for interval or tree states is wrong
- bitmask meaning is inconsistent across transitions
- digit DP forgets tightness or leading-zero behavior
Boundary and modeling risks:
- empty intervals or empty trees
- single-node or single-character base cases
- impossible states that need a sentinel rather than default
0 - integer overflow in count-heavy or cost-heavy DP
Short debugging checklist:
- describe the state in one precise sentence
- list which smaller states each transition reads
- verify that different paths can actually converge to the same state
- test tiny hand-computable inputs first
- if a result is impossible or too good, inspect whether the state forgot a constraint
6. Practice Problems
Easy
Title: Partition Equal Subset Sum
Prompt: Decide whether an array can be split into two subsets with equal sum.
Expected pattern or core idea: Subsequence reachability DP.
Title: Longest Palindromic Subsequence
Prompt: Return the LPS length in a string.
Expected pattern or core idea: Interval DP on strings.
Title: Count Palindromic Subsequences Variant
Prompt: Count palindromic structures in a short string with careful interval state.
Expected pattern or core idea: String interval state design.
Medium
Title: House Robber III
Prompt: Maximize chosen value on a tree without taking parent and child together.
Expected pattern or core idea: Tree DP with take and skip states.
Title: Minimum Cost Assignment
Prompt: Assign workers to jobs with minimum total cost.
Expected pattern or core idea: Bitmask DP on used jobs.
Title: Distinct Subsequences
Prompt: Count how many ways one string appears as a subsequence of another.
Expected pattern or core idea: DP on strings with prefix-pair states.
Hard
Title: Traveling Salesperson on Small n
Prompt: Find the minimum tour cost when the city count is small enough for subset DP.
Expected pattern or core idea: Bitmask DP with (mask, last) state.
Title: Count Numbers Without Adjacent Equal Digits
Prompt: Count all numbers up to N satisfying a digit constraint.
Expected pattern or core idea: Digit DP with tight and previous-digit state.
Title: Cherry Pickup or Similar Grid State Problem
Prompt: Maximize collection value when two simultaneous positions must be tracked.
Expected pattern or core idea: Higher-dimensional state recognition.
7. Short Recap
The core idea is that advanced DP succeeds when the state remembers exactly the information future decisions need and nothing more. The most important optimization insight is that trees, subsets, intervals, and digits can all become repeatable state spaces once modeled correctly. The most important implementation warning is to prove your state meaning before coding transitions. This prepares the next chapter, where the focus shifts from DP state design to advanced range-query and offline-processing techniques.
8. Coverage Check
- 34.1 DP on subsequences - Covered
- 34.2 DP on strings - Covered
- 34.3 DP on trees - Covered
- 34.4 Bitmask DP - Covered
- 34.5 Digit DP overview - Covered
- 34.6 Recognizing DP states in hard problems - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Advanced Range and Query Techniques
35: Advanced Range and Query Techniques
Goal: Teach how to answer many range queries efficiently by choosing the right preprocessing, decomposition, or offline strategy.
Outcome: By the end of this chapter, you can use sparse tables for static idempotent queries, square root decomposition for balanced update-query trade-offs, Mo's algorithm for offline range processing, and constraint-driven reasoning to choose the right structure.
1. Intuition First
This chapter matters because many problems are not hard because a single query is hard. They are hard because there are many queries. A naive O(n) answer per query becomes too slow when the query count is large.
A simple real-world analogy is a teacher answering repeated questions about the same textbook. If students keep asking for summaries of different page ranges, the teacher should build notes once instead of rereading the full book every time.
The core mental model is:
- look at the data mutation pattern: static, point updates, or heavy query reordering
- look at the query type: min, max, sum, xor, distinct count, and so on
- pick preprocessing that matches the constraints instead of defaulting to one structure
The most common beginner confusion point is treating all range-query problems as segment-tree problems. Segment trees are flexible, but they are not always the simplest or fastest choice for the actual constraints.
This chapter begins Part VII by focusing on advanced trade-offs. The next chapters continue that theme for trees, graphs, strings, and interview problem solving.
2. Core Concepts and Techniques
Concept Cluster: Static Queries and Block Decomposition
Key concepts in this block:
- 35.1 Sparse table
- 35.2 Square root decomposition
Intuition
Sparse tables are for static arrays where the query operation can combine overlapping blocks safely. Square root decomposition splits the array into blocks to balance preprocessing and query/update time.
Why It Matters
These two techniques teach an important habit: match the query tool to the mutation pattern.
How It Works
Sparse table:
- preprocess answers for ranges of length
2^k - answer range minimum or maximum in
O(1)using two overlapping blocks
Square root decomposition:
- split the array into blocks of size about
sqrt(n) - store one summary per block
- queries scan partial edge blocks and use summaries for full blocks
Java Implementation Notes
- Precompute
log2values for sparse-table query lengths. - Keep block size as an integer near
sqrt(n). - Sparse tables are best for idempotent operations such as min or max, not general sum with overlapping blocks.
Common Mistakes
- using sparse table for operations where overlapping blocks double-count, such as sum
- picking block sizes inconsistently across build and query logic
- forgetting to rebuild or adjust the block summary after a point update
Quick Example
For RMQ on [5, 2, 7, 1, 3], a sparse table can answer min over [1, 4] by combining two length-2 blocks that cover the interval.
Debugging Tip
For square root decomposition, print block boundaries and block summaries. Many bugs are just wrong block indexing.
Advanced Note
Sparse tables trade update support for very fast queries. That trade is excellent when the array is static and the query count is large.
Concept Cluster: Offline Reordering for Faster Queries
Key concepts in this block:
- 35.3 Mo's algorithm
- 35.4 Offline query processing
Intuition
If queries do not need to be answered in their original order, you can sort them to reduce repeated work.
Why It Matters
Offline processing often turns an otherwise slow repeated-query problem into something practical.
How It Works
Mo's algorithm:
- sort range queries by left block and then by right endpoint
- maintain a sliding current range
- add and remove elements as the query window moves
General offline query processing:
- sort queries or events by some key such as right endpoint, threshold, or time
- process data and queries together in that sorted order
Java Implementation Notes
- Keep add and remove operations constant time if possible.
- Store each query's original index so answers can be restored in user order.
- For threshold-style offline processing, Fenwick trees and sorting often combine well.
Common Mistakes
- forgetting that Mo's algorithm only helps when add/remove operations are cheap
- losing the original query order
- sorting offline queries by the wrong key and breaking the invariant
Quick Example
If many queries ask for the number of distinct values in subarrays, Mo's algorithm avoids rebuilding a fresh frequency map from scratch for each query.
Debugging Tip
Log current left, current right, and the maintained summary while processing a tiny set of sorted queries.
Advanced Note
Offline processing is a broad idea. Mo's algorithm is one specific offline strategy for range queries.
Concept Cluster: Structure Choice by Constraints
Key concepts in this block:
- 35.5 Choosing the right query structure by constraints
Intuition
The best data structure depends on whether the array changes, how many queries exist, and what each query asks for.
Why It Matters
Expert-level range-query problem solving is often a structure-selection problem before it is a coding problem.
How It Works
Ask:
- is the data static or dynamic
- is the operation idempotent, associative, or something more complex
- are queries online or can they be reordered offline
- do we need point updates, range updates, or no updates
Java Implementation Notes
- Choose the simplest structure that meets the constraints.
- Static RMQ often favors sparse table.
- Moderate point updates plus range sums may favor Fenwick tree or sqrt decomposition.
- Complex dynamic queries often favor segment trees.
Common Mistakes
- choosing the most flexible tool instead of the most appropriate one
- ignoring preprocessing cost when query count is small
- overlooking that offline solutions are allowed
Quick Example
Ten million RMQ queries on a static array strongly favor sparse table over a dynamic structure.
Debugging Tip
Before coding, write expected build, query, and update costs. If they do not fit the constraints, change the structure.
Advanced Note
Many hard problems are won by recognizing that the query type is static or offline, which collapses the needed complexity.
3. Worked Examples and Full Solutions
Worked Example 1: Range Minimum Query with Sparse Table
Problem Statement
Given a static integer array and many range minimum queries, return the minimum value in each queried interval.
Why This Example Matters
This is the standard sparse-table use case and the cleanest example of preprocess-heavy, query-light cost shifting.
Constraints or Assumptions
- the array does not change after preprocessing
- many queries are expected
- the operation is minimum, which is idempotent
Brute-Force Approach
For each query [left, right], scan the interval and keep the minimum.
That costs O(length) per query.
Better Approach
Preprocess a sparse table for powers of two.
Why the Better Approach Works
Any interval length can be covered by two overlapping power-of-two blocks. For minimum, overlapping coverage is safe because taking the minimum twice does not distort the answer.
Pragmatic Java Choice
Use a table[level][index] layout and a precomputed log array.
Java Solution
class SparseTableRmExample {
static final class SparseTable {
private final int[][] table;
private final int[] log2;
SparseTable(int[] values) {
int n = values.length;
log2 = new int[n + 1];
for (int length = 2; length <= n; length++) {
log2[length] = log2[length / 2] + 1;
}
int levels = log2[n] + 1;
table = new int[levels][n];
System.arraycopy(values, 0, table[0], 0, n);
for (int level = 1; level < levels; level++) {
int blockLength = 1 << level;
int half = blockLength >> 1;
for (int index = 0; index + blockLength <= n; index++) {
table[level][index] = Math.min(table[level - 1][index], table[level - 1][index + half]);
}
}
}
int rangeMin(int left, int right) {
int length = right - left + 1;
int level = log2[length];
int blockLength = 1 << level;
return Math.min(table[level][left], table[level][right - blockLength + 1]);
}
}
}
Dry Run
Array: [5, 2, 7, 1, 3], query [1, 4]
- query length is
4 - largest power of two not exceeding
4is4 - compare the precomputed block starting at
1with the block ending at4 - both blocks cover the interval, and the answer is
1
Time and Space Complexity
Brute-force per query:
- Time:
O(n)in the worst case per query - Space:
O(1)
Sparse table:
- Build Time:
O(n log n) - Query Time:
O(1) - Space:
O(n log n)
Edge Cases
- one-element query
- duplicate minimum values
- full-array query
Common Mistakes
- using sparse table for non-idempotent queries like sum
- off-by-one errors in query length
- wrong second block start in the query method
Worked Example 2: Range Sum with Square Root Decomposition
Problem Statement
Given an integer array, support point updates and range sum queries.
Why This Example Matters
This example shows a middle ground between full segment trees and full brute force.
Constraints or Assumptions
- point updates occur, but not too aggressively
- range sum queries are common
- clarity is preferred over the most flexible possible structure
Brute-Force Approach
- update the array directly in
O(1) - answer each query by scanning the interval in
O(n)
That becomes slow when queries are frequent.
Better Approach
Split the array into blocks and store each block's sum.
Why the Better Approach Works
Full blocks contribute instantly from precomputed sums, and only the partial edge blocks need element-by-element scanning.
Pragmatic Java Choice
Use block size near sqrt(n) and separate block sums from raw values.
Java Solution
class SqrtDecompositionSumExample {
static final class SqrtDecomposition {
private final int[] values;
private final int[] blockSums;
private final int blockSize;
SqrtDecomposition(int[] input) {
values = input.clone();
blockSize = (int) Math.ceil(Math.sqrt(values.length));
blockSums = new int[(values.length + blockSize - 1) / blockSize];
for (int index = 0; index < values.length; index++) {
blockSums[index / blockSize] += values[index];
}
}
void update(int index, int newValue) {
int block = index / blockSize;
blockSums[block] += newValue - values[index];
values[index] = newValue;
}
int rangeSum(int left, int right) {
int sum = 0;
int current = left;
while (current <= right && current % blockSize != 0) {
sum += values[current++];
}
while (current + blockSize - 1 <= right) {
sum += blockSums[current / blockSize];
current += blockSize;
}
while (current <= right) {
sum += values[current++];
}
return sum;
}
}
}
Dry Run
Array: [4, 1, 7, 3, 2, 6, 5, 8, 9]
- with block size
3, block sums are[12, 11, 22] - query
[2, 7]uses part of block0, full block1, and part of block2 - update index
4from2to10adjusts its block sum by+8
Time and Space Complexity
Brute-force approach:
- Update Time:
O(1) - Query Time:
O(n) - Space:
O(1)extra
Square root decomposition:
- Build Time:
O(n) - Update Time:
O(1) - Query Time:
O(sqrt(n)) - Space:
O(sqrt(n))
Edge Cases
- updates at the first or last index
- queries inside one block only
- array length not divisible by block size
Common Mistakes
- block size mismatch between build and query logic
- not updating the block summary after a point change
- scanning past the query boundary in the middle loop
Worked Example 3: Distinct Values in Range with Mo's Algorithm
Problem Statement
Given an array and many range queries [left, right], return the number of distinct values in each range.
Why This Example Matters
This is the classic Mo's algorithm problem. It shows how query reordering reduces repeated work.
Constraints or Assumptions
- the array is static
- all queries are known in advance
- values are within a manageable range for frequency counting or can be coordinate-compressed first
Brute-Force Approach
For each query, scan the interval and build a fresh set of seen values.
That costs O(length) per query and repeats a lot of work.
Better Approach
Sort the queries with Mo's ordering and maintain one moving window.
Why the Better Approach Works
Adjacent sorted queries often differ by only a few elements, so add and remove operations can update the answer incrementally.
Pragmatic Java Choice
Use an inner Query class, store original indices, and keep a frequency array.
Java Solution
import java.util.Arrays;
class MosAlgorithmExample {
static final class Query {
final int left;
final int right;
final int index;
Query(int left, int right, int index) {
this.left = left;
this.right = right;
this.index = index;
}
}
static int[] distinctCounts(int[] values, Query[] queries, int maxValue) {
int blockSize = Math.max(1, (int) Math.sqrt(values.length));
Arrays.sort(queries, (first, second) -> {
int firstBlock = first.left / blockSize;
int secondBlock = second.left / blockSize;
if (firstBlock != secondBlock) {
return Integer.compare(firstBlock, secondBlock);
}
return Integer.compare(first.right, second.right);
});
int[] frequency = new int[maxValue + 1];
int[] answers = new int[queries.length];
int currentLeft = 0;
int currentRight = -1;
int distinct = 0;
for (Query query : queries) {
while (currentLeft > query.left) {
currentLeft--;
if (frequency[values[currentLeft]]++ == 0) {
distinct++;
}
}
while (currentRight < query.right) {
currentRight++;
if (frequency[values[currentRight]]++ == 0) {
distinct++;
}
}
while (currentLeft < query.left) {
if (--frequency[values[currentLeft]] == 0) {
distinct--;
}
currentLeft++;
}
while (currentRight > query.right) {
if (--frequency[values[currentRight]] == 0) {
distinct--;
}
currentRight--;
}
answers[query.index] = distinct;
}
return answers;
}
}
Dry Run
Array: [1, 2, 1, 3, 2]
Queries:
[0, 2][1, 4]
Mo's ordering keeps a current window. When moving from [0, 2] to [1, 4]:
- remove index
0 - add indices
3and4 - update frequencies and distinct count incrementally
Answers become:
[0, 2] -> 2[1, 4] -> 3
Time and Space Complexity
Brute-force per query:
- Time:
O(n)per query in the worst case - Space: up to
O(n)temporary set space per query
Mo's algorithm:
- Time: about
O((n + q) * sqrt(n))add/remove work, depending on implementation details - Space:
O(valueRange + q)
Edge Cases
- queries of length
1 - all values equal
- all values distinct
Common Mistakes
- forgetting to store original query indices
- using expensive add/remove operations, which cancels Mo's benefit
- not compressing large values before frequency counting
Worked Example 4: Offline Count of Values Greater Than k
Problem Statement
Given an array and many queries (left, right, k), return how many values in each interval are greater than k.
Why This Example Matters
This example shows offline query processing outside Mo's algorithm. The query key is the threshold k, not just the interval.
Constraints or Assumptions
- all queries are known beforehand
- array indices are zero-based in the explanation
- Fenwick tree support is allowed
Brute-Force Approach
For each query, scan the interval and count values greater than k.
That costs O(length) per query.
Better Approach
Sort array values and queries in descending order of threshold, activating indices whose values are already greater than the current query's k.
Why the Better Approach Works
Once all positions with value > k are marked in a Fenwick tree, each query answer becomes a range-sum query over active indices.
Pragmatic Java Choice
Use an events-style offline sweep with a Fenwick tree.
Java Solution
import java.util.Arrays;
class OfflineGreaterThanQueryExample {
static final class Entry {
final int value;
final int index;
Entry(int value, int index) {
this.value = value;
this.index = index;
}
}
static final class Query {
final int left;
final int right;
final int threshold;
final int index;
Query(int left, int right, int threshold, int index) {
this.left = left;
this.right = right;
this.threshold = threshold;
this.index = index;
}
}
static final class FenwickTree {
private final int[] tree;
FenwickTree(int size) {
tree = new int[size + 1];
}
void add(int index, int delta) {
for (int i = index + 1; i < tree.length; i += i & -i) {
tree[i] += delta;
}
}
int prefixSum(int index) {
int sum = 0;
for (int i = index + 1; i > 0; i -= i & -i) {
sum += tree[i];
}
return sum;
}
int rangeSum(int left, int right) {
if (left > right) {
return 0;
}
return prefixSum(right) - (left == 0 ? 0 : prefixSum(left - 1));
}
}
static int[] countGreaterThanK(int[] values, Query[] queries) {
Entry[] entries = new Entry[values.length];
for (int i = 0; i < values.length; i++) {
entries[i] = new Entry(values[i], i);
}
Arrays.sort(entries, (first, second) -> Integer.compare(second.value, first.value));
Arrays.sort(queries, (first, second) -> Integer.compare(second.threshold, first.threshold));
FenwickTree fenwickTree = new FenwickTree(values.length);
int[] answers = new int[queries.length];
int entryIndex = 0;
for (Query query : queries) {
while (entryIndex < entries.length && entries[entryIndex].value > query.threshold) {
fenwickTree.add(entries[entryIndex].index, 1);
entryIndex++;
}
answers[query.index] = fenwickTree.rangeSum(query.left, query.right);
}
return answers;
}
}
Dry Run
Array: [5, 1, 7, 3, 6]
Query: (1, 4, 4)
- activate all values greater than
4: indices with5,7, and6 - the Fenwick tree marks those active positions
- range sum over
[1, 4]counts indices2and4
Answer: 2
Time and Space Complexity
Brute-force per query:
- Time:
O(n)per query in the worst case - Space:
O(1)
Offline sweep with Fenwick tree:
- Sorting Time:
O((n + q) log(n + q)) - Processing Time:
O((n + q) log n) - Space:
O(n + q)
Edge Cases
- no values greater than
k - all values greater than
k - interval of length
1
Common Mistakes
- sorting thresholds in the wrong direction
- forgetting to restore original query order
- mixing zero-based array indices with one-based Fenwick tree internals
4. Complexity and Decision Guide
The main trade-off in this chapter is where the work happens.
- sparse table pays
O(n log n)up front to getO(1)static RMQ queries - square root decomposition pays small build cost and gives balanced
O(sqrt(n))queries with simple point updates - Mo's algorithm avoids rebuilding query state and works well when add/remove operations are cheap and queries are offline
- general offline sweeps combine sorting with a structure such as Fenwick tree when the query key includes thresholds or event order
When to choose brute force:
- very small query count
- very short intervals
- when preprocessing cost would dominate the total work
When to optimize:
- query count is large relative to array size
- the data is static, making preprocess-heavy tools attractive
- queries can be reordered without changing correctness
Recognition signals for each technique:
- sparse table: static array plus idempotent range queries like min or max
- square root decomposition: moderate updates and queries with simple summaries
- Mo's algorithm: offline range queries where one movable window can maintain the answer
- offline sweep: queries include an orderable threshold, endpoint, or time dimension
Signals not to force these techniques:
- frequent complex range updates that need lazy propagation instead
- online queries that must be answered in arrival order when the chosen method depends on reordering
- expensive add/remove logic that makes Mo's algorithm too slow in practice
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- off-by-one errors in interval boundaries
- wrong block numbering in sqrt decomposition or Mo's ordering
- using overlapping sparse-table blocks for an operation that is not idempotent
- losing original query order in offline methods
- forgetting coordinate compression when values are too large for direct frequency arrays
Mutation and consistency risks:
- block summaries not updated after point changes
- Fenwick tree using one-based indexing internally while callers use zero-based indices
- comparing thresholds with the wrong strictness in offline sweeps
Short debugging checklist:
- write the expected build, update, and query complexities before coding
- test single-element intervals first
- test intervals that begin or end exactly on block boundaries
- log query ordering for offline methods
- confirm answer restoration into original query order
6. Practice Problems
Easy
Title: Static Range Minimum Query
Prompt: Answer many minimum queries on an unchanging array.
Expected pattern or core idea: Sparse table for idempotent static queries.
Title: Range Sum with Point Updates
Prompt: Support updates and sum queries on an array of manageable size.
Expected pattern or core idea: Square root decomposition or Fenwick tree trade-off.
Title: Prefix XOR Query Variant
Prompt: Answer many static xor queries quickly.
Expected pattern or core idea: Recognize when prefix preprocessing beats heavier structures.
Medium
Title: Distinct Values in Range
Prompt: Return the number of distinct values for many offline interval queries.
Expected pattern or core idea: Mo's algorithm with add/remove frequency maintenance.
Title: Count Values Greater Than k
Prompt: Answer interval queries with a threshold condition.
Expected pattern or core idea: Offline sweep plus Fenwick tree.
Title: Static GCD Range Queries
Prompt: Answer many GCD queries on a fixed array.
Expected pattern or core idea: Constraint-driven selection of a static query structure.
Hard
Title: Powerful Array
Prompt: Maintain a custom frequency-based score over many offline subarray queries.
Expected pattern or core idea: Mo's algorithm with nontrivial add/remove updates.
Title: K-th Number in a Range Offline Variant
Prompt: Answer order-statistic queries over intervals with offline processing.
Expected pattern or core idea: Query reordering and auxiliary data structures.
Title: Dynamic Range Mode Approximation Discussion
Prompt: Explore why some query types are much harder than sum or minimum.
Expected pattern or core idea: Choosing structures by operation complexity, not habit.
7. Short Recap
The core idea is that range-query performance depends on whether data is static, partially dynamic, or fully offline. The most important optimization insight is to shift work into preprocessing or query reordering when constraints allow it. The most important implementation warning is to keep interval boundaries, block boundaries, and original query order consistent. This prepares the next chapter, where tree-specific advanced query techniques become the main focus.
8. Coverage Check
- 35.1 Sparse table - Covered
- 35.2 Square root decomposition - Covered
- 35.3 Mo's algorithm - Covered
- 35.4 Offline query processing - Covered
- 35.5 Choosing the right query structure by constraints - Covered
Coverage Summary: 5/5 official subtopics covered
Next: Advanced Trees
36: Advanced Trees
Goal: Teach how to answer advanced tree queries and reason about global tree properties using ancestor jumps, Euler tours, diameter methods, and heavy-path ideas.
Outcome: By the end of this chapter, you can solve LCA problems with binary lifting, flatten trees with Euler tour technique, compute tree diameter efficiently, and recognize when heavy-light decomposition is the right next tool.
1. Intuition First
This chapter matters because tree problems stop being simple once the question is no longer just "traverse the tree." You may need to compare ancestors, answer subtree queries, or reason about long paths quickly across many operations.
A simple real-world analogy is an organizational chart. If two employees ask for their closest shared manager, or if you want the total budget of one department, you should not walk the entire chart from scratch every time.
The core mental model is:
- preprocess the tree once
- map complex tree questions into simpler representations such as ancestor jumps or subtree intervals
- answer many queries faster than a fresh full traversal each time
The most common beginner confusion point is thinking tree queries always stay tree-shaped. In advanced problems, the right move is often to flatten the tree or jump through powers of two.
This chapter builds directly on the tree, BST, and range-query foundations from earlier chapters. The next chapter applies a similar expert-level mindset to advanced graph algorithms.
2. Core Concepts and Techniques
Concept Cluster: Ancestor Queries
Key concepts in this block:
- 36.1 Lowest common ancestor
- 36.2 Binary lifting
Intuition
The lowest common ancestor, or LCA, of two nodes is the deepest node that is an ancestor of both.
Why It Matters
LCA appears in path queries, distance calculations, genealogical problems, and many advanced tree tasks.
How It Works
Binary lifting preprocesses up[node][jump], meaning the 2^jumpth ancestor of node.
To answer LCA:
- lift the deeper node until both nodes are at the same depth
- lift both nodes from large jumps down to small jumps until their ancestors diverge
- the parent just above the divergence is the LCA
Java Implementation Notes
- Store depths from a root chosen during preprocessing.
- Use
-1as a missing ancestor sentinel. - Compute the number of jump levels from
log2(n).
Common Mistakes
- forgetting to equalize depths before the simultaneous lift
- wrong ancestor table initialization for the root
- mixing one-based and zero-based node numbering inconsistently
Quick Example
If node 9 is deeper than node 5, first lift 9 until both are at the same depth. Then lift both together until they just stop matching.
Debugging Tip
Print the ancestor table for a tiny tree and manually verify a few jump pointers before trusting the query method.
Advanced Note
Binary lifting also supports k-th ancestor queries and often helps with path aggregations.
Concept Cluster: Flattening and Longest Paths
Key concepts in this block:
- 36.3 Euler tour technique
- 36.4 Tree diameter
Intuition
Euler tours turn subtree regions into contiguous array intervals. Tree diameter asks for the longest simple path in the tree.
Why It Matters
Flattening is the bridge between tree problems and array/range-query techniques. Diameter is a common global-property problem with elegant linear solutions.
How It Works
Euler tour technique:
- run DFS and record each node's entry time
- if the traversal is designed correctly, every subtree becomes one continuous segment in the Euler order
Tree diameter:
- run DFS or BFS from any node to find a farthest node
A - run again from
Ato find a farthest nodeB - the path from
AtoBis the diameter
Java Implementation Notes
- Keep
tin[node]andsubtreeSize[node]for subtree interval mapping. - For weighted trees, diameter needs distance sums, not just edge counts.
- Use iterative DFS if recursion depth is a concern on very deep trees.
Common Mistakes
- using a flattening order that does not preserve subtree contiguity
- forgetting to reset visited arrays between diameter traversals
- assuming the longest path must pass through the root
Quick Example
If a subtree rooted at node u occupies Euler-order positions [tin[u], tin[u] + subtreeSize[u] - 1], subtree-sum queries can become interval-sum queries.
Debugging Tip
Print tin, subtreeSize, and flattened order for a small tree. If one subtree is not contiguous, the flattening logic is wrong.
Advanced Note
Euler tours are often the first step before Fenwick trees, segment trees, or heavy-light decomposition on trees.
Concept Cluster: Heavy Paths and Query Recognition
Key concepts in this block:
- 36.5 Heavy-light decomposition overview
- 36.6 Tree query problem patterns
Intuition
Heavy-light decomposition breaks a tree into a small number of chain segments so path queries can be answered with array-based structures.
Why It Matters
It is the right next tool when subtree tricks are not enough and the problem asks for repeated path queries with updates.
How It Works
Heavy-light decomposition:
- choose one heavy child per node, usually the child with the largest subtree
- heavy edges form chains
- any root-to-node path crosses only
O(log n)light edges
Tree query recognition patterns:
- ancestor query
- subtree aggregate query
- path query between two nodes
- update plus repeated query scenario
Java Implementation Notes
- Heavy-light decomposition is an engineering-heavy technique, so keep arrays for parent, depth, heavy child, head, and position clearly separated.
- Map the decomposed chains into one base array.
- Use segment tree or Fenwick tree on that base array depending on the query type.
Common Mistakes
- using HLD when simple Euler-tour subtree intervals already solve the problem
- confusing path queries with subtree queries
- losing track of chain heads during decomposition
Quick Example
A path query from u to v can be broken into a small number of chain segments by repeatedly moving the deeper chain head upward.
Debugging Tip
Classify the query before coding: ancestor, subtree, or general path. The right tool often becomes obvious from that one step.
Advanced Note
Many hard tree problems are solved not by a new algorithmic trick, but by recognizing which tree-to-array reduction fits the query pattern.
3. Worked Examples and Full Solutions
Worked Example 1: Lowest Common Ancestor with Binary Lifting
Problem Statement
Given a rooted tree and many pairs of nodes, return the lowest common ancestor for each pair.
Why This Example Matters
This is the standard advanced-tree query. It combines preprocessing with fast repeated queries.
Constraints or Assumptions
- nodes are labeled from
0ton - 1 - the tree is connected and rooted at node
0 - many LCA queries are expected
Brute-Force Approach
For each query:
- walk the deeper node upward until both nodes are at the same depth
- then move both upward one parent at a time
That can take O(height) per query.
Better Approach
Preprocess binary-lifting ancestors.
Why the Better Approach Works
Jumping by powers of two reduces the number of upward steps dramatically. Each query uses only O(log n) jumps.
Pragmatic Java Choice
Use DFS preprocessing plus an up[node][level] table.
Java Solution
import java.util.ArrayList;
import java.util.List;
class BinaryLiftingLcaExample {
static final class LcaSolver {
private final List<Integer>[] graph;
private final int[][] up;
private final int[] depth;
private final int levels;
LcaSolver(List<Integer>[] graph, int root) {
this.graph = graph;
int n = graph.length;
levels = 1;
while ((1 << levels) <= n) {
levels++;
}
up = new int[n][levels];
depth = new int[n];
dfs(root, -1);
}
private void dfs(int node, int parent) {
up[node][0] = parent;
for (int level = 1; level < levels; level++) {
int middleAncestor = up[node][level - 1];
up[node][level] = middleAncestor == -1 ? -1 : up[middleAncestor][level - 1];
}
for (int next : graph[node]) {
if (next == parent) {
continue;
}
depth[next] = depth[node] + 1;
dfs(next, node);
}
}
int lca(int first, int second) {
if (depth[first] < depth[second]) {
int temporary = first;
first = second;
second = temporary;
}
int depthDifference = depth[first] - depth[second];
for (int level = levels - 1; level >= 0; level--) {
if (((depthDifference >> level) & 1) == 1) {
first = up[first][level];
}
}
if (first == second) {
return first;
}
for (int level = levels - 1; level >= 0; level--) {
if (up[first][level] != up[second][level]) {
first = up[first][level];
second = up[second][level];
}
}
return up[first][0];
}
}
static List<Integer>[] buildGraph(int nodeCount, int[][] edges) {
List<Integer>[] graph = new ArrayList[nodeCount];
for (int node = 0; node < nodeCount; node++) {
graph[node] = new ArrayList<>();
}
for (int[] edge : edges) {
int first = edge[0];
int second = edge[1];
graph[first].add(second);
graph[second].add(first);
}
return graph;
}
}
Dry Run
Suppose the tree has root 0, and query nodes are 8 and 11.
- first equalize depths by lifting the deeper node with binary jumps
- then compare large ancestor jumps downward from the largest level
- once the nodes are just below their common ancestor, return the parent one level up
Time and Space Complexity
Brute-force parent climbing:
- Preprocessing Time:
O(n) - Query Time:
O(height) - Space:
O(n)
Binary lifting:
- Preprocessing Time:
O(n log n) - Query Time:
O(log n) - Space:
O(n log n)
Edge Cases
- one node is the ancestor of the other
- query with the same node twice
- root involved in the query
Common Mistakes
- not equalizing depths first
- wrong jump-table initialization for missing ancestors
- off-by-one mistakes in the number of levels
Worked Example 2: Tree Diameter
Problem Statement
Given an undirected tree, return the number of edges on its diameter, meaning the longest simple path in the tree.
Why This Example Matters
Diameter is a classic global tree property. The optimal method is elegant and much faster than checking all node pairs.
Constraints or Assumptions
- the input graph is a tree
- edges are unweighted in this example
- returning the path length in edges is enough
Brute-Force Approach
Run BFS or DFS from every node and keep the largest distance found.
That costs O(n^2) on a tree.
Better Approach
Use two BFS traversals.
Why the Better Approach Works
From any node, one farthest node is guaranteed to be an endpoint of some diameter. Starting from that endpoint and searching again reaches the other endpoint.
Pragmatic Java Choice
Use iterative BFS to avoid recursion concerns.
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
class TreeDiameterExample {
static final class SearchResult {
final int node;
final int distance;
SearchResult(int node, int distance) {
this.node = node;
this.distance = distance;
}
}
static int diameterLength(List<Integer>[] graph) {
SearchResult first = farthestFrom(0, graph);
SearchResult second = farthestFrom(first.node, graph);
return second.distance;
}
private static SearchResult farthestFrom(int start, List<Integer>[] graph) {
boolean[] visited = new boolean[graph.length];
int[] distance = new int[graph.length];
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
visited[start] = true;
int farthestNode = start;
while (!queue.isEmpty()) {
int node = queue.remove();
farthestNode = node;
for (int next : graph[node]) {
if (!visited[next]) {
visited[next] = true;
distance[next] = distance[node] + 1;
queue.add(next);
}
}
}
return new SearchResult(farthestNode, distance[farthestNode]);
}
static List<Integer>[] buildGraph(int nodeCount, int[][] edges) {
List<Integer>[] graph = new ArrayList[nodeCount];
for (int node = 0; node < nodeCount; node++) {
graph[node] = new ArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
return graph;
}
}
Dry Run
If the tree path 4 - 2 - 0 - 1 - 3 - 7 is the longest:
- BFS from an arbitrary start may find
4as a farthest node - BFS from
4then reaches7at maximum distance - that distance is the diameter length
Time and Space Complexity
Brute-force all-start BFS:
- Time:
O(n^2) - Space:
O(n)
Two-BFS diameter method:
- Time:
O(n) - Space:
O(n)
Edge Cases
- one-node tree
- chain-shaped tree
- star-shaped tree
Common Mistakes
- not clearing visited state between searches
- assuming the first BFS distance is the diameter directly
- applying the method to a general graph instead of a tree without extra care
Worked Example 3: Subtree Sum Queries with Euler Tour Technique
Problem Statement
Given a rooted tree with values on nodes, answer many queries asking for the sum of all values in a node's subtree.
Why This Example Matters
This example shows how a tree can be flattened into an array interval so ordinary prefix sums or range structures can answer subtree queries.
Constraints or Assumptions
- the tree is rooted at node
0 - node values are static in this version
- many subtree queries are expected
Brute-Force Approach
For each query, run DFS from the node and sum its entire subtree.
That costs O(subtreeSize) per query.
Better Approach
Run one Euler tour, flatten node values into entry order, and answer each subtree query as an array interval sum.
Why the Better Approach Works
In a preorder-style Euler flattening, all nodes in a subtree appear contiguously. That turns a tree query into a range-sum query.
Pragmatic Java Choice
Use tin, subtreeSize, and a prefix-sum array over the flattened node values.
Java Solution
import java.util.ArrayList;
import java.util.List;
class EulerTourSubtreeSumExample {
static final class Solver {
private final List<Integer>[] graph;
private final int[] nodeValues;
private final int[] tin;
private final int[] subtreeSize;
private final int[] order;
private final long[] prefixSums;
private int timer;
Solver(List<Integer>[] graph, int[] nodeValues, int root) {
this.graph = graph;
this.nodeValues = nodeValues;
int n = graph.length;
tin = new int[n];
subtreeSize = new int[n];
order = new int[n];
prefixSums = new long[n + 1];
dfs(root, -1);
for (int index = 0; index < n; index++) {
prefixSums[index + 1] = prefixSums[index] + nodeValues[order[index]];
}
}
private void dfs(int node, int parent) {
tin[node] = timer;
order[timer] = node;
timer++;
subtreeSize[node] = 1;
for (int next : graph[node]) {
if (next == parent) {
continue;
}
dfs(next, node);
subtreeSize[node] += subtreeSize[next];
}
}
long subtreeSum(int node) {
int left = tin[node];
int right = tin[node] + subtreeSize[node] - 1;
return prefixSums[right + 1] - prefixSums[left];
}
}
static List<Integer>[] buildGraph(int nodeCount, int[][] edges) {
List<Integer>[] graph = new ArrayList[nodeCount];
for (int node = 0; node < nodeCount; node++) {
graph[node] = new ArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
return graph;
}
}
Dry Run
Suppose the Euler order is [0, 1, 3, 4, 2, 5].
- if
tin[1] = 1andsubtreeSize[1] = 3 - then subtree of node
1maps to flat interval[1, 3] - a prefix-sum query over that interval returns the subtree total immediately
Time and Space Complexity
Brute-force per query:
- Time:
O(subtreeSize)per query - Space:
O(h)recursion depth for each query
Euler tour with prefix sums:
- Preprocessing Time:
O(n) - Query Time:
O(1) - Space:
O(n)
Edge Cases
- querying the root subtree
- querying a leaf
- highly unbalanced tree
Common Mistakes
- using a traversal order that does not make subtrees contiguous
- off-by-one errors in the flattened interval
- forgetting that this static version does not support updates without an extra structure
4. Complexity and Decision Guide
Advanced tree techniques are mostly about turning repeated queries into fast jumps or intervals.
- LCA with binary lifting costs
O(n log n)preprocessing andO(log n)per query - Euler-tour subtree queries often cost
O(n)preprocessing and thenO(1)orO(log n)per query depending on the backing structure - tree diameter can be solved in
O(n)rather thanO(n^2)with the right global insight - heavy-light decomposition usually gives path queries in about
O(log^2 n)with a segment tree, or better with more refinement
When to choose brute force:
- very small tree and very few queries
- one-off analysis rather than repeated online queries
When to optimize:
- many ancestor queries
- many subtree or path queries
- updates mixed with repeated queries on large trees
Recognition signals:
- LCA or k-th ancestor wording suggests binary lifting
- subtree aggregate wording suggests Euler tour flattening
- repeated path queries with updates suggest heavy-light decomposition
- global longest-path wording suggests tree diameter logic
Signals not to force these techniques:
- a single DFS solves the whole problem once
- the query volume is tiny
- the tree is actually dynamic in topology, which changes the tool choice significantly
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- wrong root assumptions during preprocessing
- ancestor table entries not initialized correctly for the root
- Euler intervals off by one
- forgetting to reset traversal state between multiple passes
- mixing path queries and subtree queries under the same flattening logic
Short debugging checklist:
- verify depth values on a tiny tree
- check a few known ancestor jumps manually
- print Euler entry times and subtree sizes
- test leaf, root, and ancestor-of-self queries
- classify the query type before choosing the technique
6. Practice Problems
Easy
Title: K-th Ancestor of a Tree Node
Prompt: Return the k-th ancestor for many queries on a rooted tree.
Expected pattern or core idea: Binary lifting jump table.
Title: Subtree Size Queries
Prompt: Return the number of nodes in each queried subtree.
Expected pattern or core idea: Euler tour flattening with subtree intervals.
Title: Tree Diameter
Prompt: Return the longest simple path length in a tree.
Expected pattern or core idea: Two BFS or DFS passes.
Medium
Title: Lowest Common Ancestor
Prompt: Answer many LCA queries on a rooted tree.
Expected pattern or core idea: Binary lifting plus depth equalization.
Title: Subtree Sum with Updates
Prompt: Support value updates on nodes and subtree sum queries.
Expected pattern or core idea: Euler tour plus Fenwick tree or segment tree.
Title: Distance Between Two Nodes
Prompt: Return the distance between many node pairs.
Expected pattern or core idea: LCA plus depth information.
Hard
Title: Path Sum Query with Updates
Prompt: Support repeated path aggregate queries and point updates on a tree.
Expected pattern or core idea: Heavy-light decomposition overview applied to path segments.
Title: Tree Path Maximum
Prompt: Return the maximum value on arbitrary node-to-node paths with updates.
Expected pattern or core idea: Path decomposition into array intervals.
Title: Dynamic Root Query Variant
Prompt: Answer subtree or ancestor-style queries when the root may change.
Expected pattern or core idea: Careful tree-query classification and preprocessing.
7. Short Recap
The core idea is to preprocess trees into jump tables or flat intervals so repeated queries avoid full traversals. The most important optimization insight is that many advanced tree questions become easy after the right reduction: ancestors to binary jumps, subtrees to intervals, and long paths to diameter logic. The most important implementation warning is to keep roots, depths, and flattened intervals consistent. This prepares the next chapter, where advanced graph algorithms require similar modeling discipline on more general structures.
8. Coverage Check
- 36.1 Lowest common ancestor - Covered
- 36.2 Binary lifting - Covered
- 36.3 Euler tour technique - Covered
- 36.4 Tree diameter - Covered
- 36.5 Heavy-light decomposition overview - Covered
- 36.6 Tree query problem patterns - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Advanced Graph Algorithms
37: Advanced Graph Algorithms
Goal: Teach how to reason about flows, cuts, state-expanded shortest paths, and richer graph models beyond standard traversal and shortest-path templates.
Outcome: By the end of this chapter, you can model max-flow problems, implement Edmonds-Karp, explain the max flow min cut relationship, solve shortest-path problems with additional state, and recognize advanced graph modeling patterns.
1. Intuition First
This chapter matters because some graph problems are not just about reaching nodes. They are about how much can move through a network, how constraints change what a node means, or how a real-world scenario should be modeled before any algorithm makes sense.
A simple real-world analogy is shipping goods through a network of pipes. Each pipe has a capacity. Sending more through one route may block what can still travel elsewhere. That is different from ordinary shortest-path thinking.
The core mental model is:
- choose the correct graph model first
- ask whether the task is about path length, path count, capacity, or a state-constrained journey
- run the algorithm that matches that model
The most common beginner confusion point is trying to force all advanced graph problems into plain BFS or Dijkstra. When capacities or extra state dimensions matter, the graph itself must be expanded or reinterpreted.
This chapter continues the Part VII focus on trade-offs and modeling discipline. The next chapter applies the same idea to advanced string algorithms.
2. Core Concepts and Techniques
Concept Cluster: Flow Networks and Augmenting Paths
Key concepts in this block:
- 37.1 Flow network basics
- 37.2 Ford-Fulkerson
- 37.3 Edmonds-Karp
Intuition
A flow network has capacities on directed edges, a source where flow starts, and a sink where flow ends.
Why It Matters
Flow models solve transport, assignment, matching, and cut problems that ordinary shortest paths cannot express.
How It Works
Ford-Fulkerson repeatedly finds an augmenting path in the residual graph and pushes additional flow through it.
Edmonds-Karp is a specific Ford-Fulkerson strategy that always uses BFS to find the shortest augmenting path in edge count.
Residual graph idea:
- forward edges show remaining capacity
- backward edges show how much previous flow can be canceled or rerouted
Java Implementation Notes
- Maintain a residual-capacity matrix or adjacency lists with reverse edges.
- Always update both forward and backward capacities after augmentation.
- Use BFS parent tracking for Edmonds-Karp.
Common Mistakes
- forgetting reverse edges in the residual graph
- adding flow directly to the original graph without maintaining residual capacities
- assuming any path choice gives the same runtime behavior
Quick Example
If path source -> A -> sink has bottleneck capacity 3, pushing 3 units reduces those forward capacities and increases reverse capacities by 3.
Debugging Tip
After each augmentation, print the chosen path and bottleneck. Most max-flow bugs are residual-graph bugs.
Advanced Note
Edmonds-Karp improves the path-choice rule of Ford-Fulkerson to guarantee polynomial time.
Concept Cluster: Cuts and State-Expanded Paths
Key concepts in this block:
- 37.4 Max flow min cut
- 37.5 Shortest path with state
Intuition
Max flow min cut says the maximum transport possible equals the minimum total capacity that separates source from sink. Shortest path with state treats each logical condition as part of the node identity.
Why It Matters
These ideas connect algorithmic results to modeling power. They let you solve problems with constraints like one coupon, one wall break, or limited special moves.
How It Works
Max flow min cut:
- after max flow finishes, nodes still reachable from the source in the residual graph form one side of the minimum cut
Shortest path with state:
- expand node identity from
nodeto something like(node, usedSpecialMove)or(row, col, breaksUsed) - run BFS or Dijkstra on that expanded graph
Java Implementation Notes
- The expanded-state graph is usually implicit, not fully materialized beforehand.
- Choose BFS for unweighted state transitions and Dijkstra for weighted ones.
- Keep state objects simple and hashable if using maps or sets.
Common Mistakes
- forgetting that visiting the same node with different state values is not the same state
- marking a physical node visited globally instead of by full state
- misunderstanding the cut after max-flow completion
Quick Example
In a grid where you may break one wall, (2, 3, 0) and (2, 3, 1) are different states because future options differ.
Debugging Tip
When the path result looks impossible, inspect whether the visited structure is keyed by full state rather than just raw node index.
Advanced Note
Many hard shortest-path problems become standard once the state expansion is modeled correctly.
Concept Cluster: Richer Problem Modeling
Key concepts in this block:
- 37.6 Advanced graph modeling
Intuition
The hardest part of some graph problems is deciding what the graph should be.
Why It Matters
A correct model can turn a confusing real-world description into a clean matching, flow, or shortest-path problem.
How It Works
Common modeling moves:
- split one entity type into two sides to form bipartite graphs
- add source and sink to convert matching into max flow
- expand state to encode limited resources or mode changes
- create edges based on dependency, reachability, or compatibility rules
Java Implementation Notes
- Name node groups clearly when building modeled graphs.
- Keep conversion code separate from the chosen algorithm implementation.
- Verify the model on a tiny example before running the full solver.
Common Mistakes
- building too many edges because the compatibility rule is vague
- using weighted shortest path when the problem is actually a capacity problem
- losing the original problem meaning during modeling
Quick Example
Job assignment can be modeled as source -> worker -> job -> sink, with capacity 1 edges.
Debugging Tip
Draw the modeled graph for a three-entity example. If the graph does not reflect the rules exactly, the algorithm choice is irrelevant.
Advanced Note
Advanced graph problems are often won or lost at the modeling stage, not the implementation stage.
3. Worked Examples and Full Solutions
Worked Example 1: Maximum Flow with Edmonds-Karp
Problem Statement
Given a directed network with capacities, return the maximum flow from source to sink.
Why This Example Matters
This is the standard entry point to flow algorithms and residual reasoning.
Constraints or Assumptions
- capacities are nonnegative integers
- the graph is directed
- multiple augmenting paths may exist
Brute-Force Approach
Try to reason about all source-to-sink path combinations manually and guess how to split the flow.
That is not scalable and ignores residual rerouting.
Better Approach
Use Edmonds-Karp, the BFS-based version of Ford-Fulkerson.
Why the Better Approach Works
Each augmentation increases the total flow while respecting capacity and conservation rules. The residual graph makes rerouting possible when earlier choices need adjustment.
Pragmatic Java Choice
Use an adjacency list plus a residual-capacity matrix for clarity.
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class EdmondsKarpExample {
static int maxFlow(int nodeCount, int[][] edges, int source, int sink) {
int[][] residual = new int[nodeCount][nodeCount];
List<Integer>[] graph = new ArrayList[nodeCount];
for (int node = 0; node < nodeCount; node++) {
graph[node] = new ArrayList<>();
}
for (int[] edge : edges) {
int from = edge[0];
int to = edge[1];
int capacity = edge[2];
residual[from][to] += capacity;
graph[from].add(to);
graph[to].add(from);
}
int totalFlow = 0;
int[] parent = new int[nodeCount];
while (bfs(graph, residual, source, sink, parent)) {
int pathFlow = Integer.MAX_VALUE;
for (int node = sink; node != source; node = parent[node]) {
pathFlow = Math.min(pathFlow, residual[parent[node]][node]);
}
for (int node = sink; node != source; node = parent[node]) {
int previous = parent[node];
residual[previous][node] -= pathFlow;
residual[node][previous] += pathFlow;
}
totalFlow += pathFlow;
}
return totalFlow;
}
private static boolean bfs(List<Integer>[] graph, int[][] residual, int source, int sink, int[] parent) {
Arrays.fill(parent, -1);
parent[source] = source;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(source);
while (!queue.isEmpty()) {
int node = queue.remove();
for (int next : graph[node]) {
if (parent[next] == -1 && residual[node][next] > 0) {
parent[next] = node;
if (next == sink) {
return true;
}
queue.add(next);
}
}
}
return false;
}
}
Dry Run
If BFS finds path source -> 1 -> 3 -> sink with bottleneck 4:
- add
4to total flow - reduce each forward residual capacity on that path by
4 - increase each reverse residual capacity by
4
The algorithm repeats until no augmenting path remains.
Time and Space Complexity
Naive manual path reasoning:
- Time: not practical as a general algorithm
- Space: not meaningful as a reusable method
Edmonds-Karp:
- Time:
O(V * E^2) - Space:
O(V^2)with a residual matrix in this implementation, plus adjacency storage
Edge Cases
- no path from source to sink
- multiple edges between the same nodes
- already saturated critical edge
Common Mistakes
- forgetting reverse-capacity updates
- not combining parallel edge capacities correctly
- treating the residual graph as the original graph
Worked Example 2: Maximum Bipartite Matching via Max Flow
Problem Statement
Given workers and jobs, where each worker can perform certain jobs, return the maximum number of worker-job assignments such that each worker and job is used at most once.
Why This Example Matters
This is a strong modeling example. It shows how a matching problem becomes a max-flow problem.
Constraints or Assumptions
- each worker can take at most one job
- each job can be assigned to at most one worker
- compatibility pairs are given
Brute-Force Approach
Try all compatible assignment combinations recursively.
That grows combinatorially.
Better Approach
Build a flow network:
- source -> each worker with capacity
1 - compatible worker -> job edges with capacity
1 - each job -> sink with capacity
1
Why the Better Approach Works
Any unit of flow corresponds to one valid assignment, and capacities enforce the one-worker-one-job rule.
Pragmatic Java Choice
Reuse the max-flow solver after building the modeled graph.
Java Solution
class BipartiteMatchingFlowExample {
static int maximumMatching(int workerCount, int jobCount, int[][] compatiblePairs) {
int source = 0;
int workerOffset = 1;
int jobOffset = workerOffset + workerCount;
int sink = jobOffset + jobCount;
int[][] edges = new int[workerCount + jobCount + compatiblePairs.length][3];
int edgeIndex = 0;
for (int worker = 0; worker < workerCount; worker++) {
edges[edgeIndex++] = new int[] {source, workerOffset + worker, 1};
}
for (int[] pair : compatiblePairs) {
int worker = pair[0];
int job = pair[1];
edges[edgeIndex++] = new int[] {workerOffset + worker, jobOffset + job, 1};
}
for (int job = 0; job < jobCount; job++) {
edges[edgeIndex++] = new int[] {jobOffset + job, sink, 1};
}
return EdmondsKarpExample.maxFlow(sink + 1, edges, source, sink);
}
}
Dry Run
Suppose:
- worker
0can do jobs0and1 - worker
1can do job1
Then each successful unit of flow from source to sink passes through one worker and one job. If two units of flow reach the sink, two assignments exist.
Time and Space Complexity
Brute-force assignment search:
- Time: exponential in the worst case
- Space:
O(workerCount)recursion depth
Flow-based solution with Edmonds-Karp:
- Time: polynomial in the constructed graph size, using the underlying max-flow bound
- Space: polynomial in node and edge count
Edge Cases
- no compatible edges
- more workers than jobs
- duplicate compatibility pairs
Common Mistakes
- forgetting source or sink capacity edges
- giving worker-job edges capacity greater than
1without justification - mixing worker and job index ranges in the modeled graph
Worked Example 3: Shortest Path with One Wall Break
Problem Statement
Given a grid of 0s and 1s, where 1 means wall, return the shortest path length from top-left to bottom-right if you may break at most one wall.
Why This Example Matters
This is a clean shortest-path-with-state problem. The key difficulty is not BFS itself, but modeling (row, col, wallBreakUsed) as the node.
Constraints or Assumptions
- moving up, down, left, or right costs
1 - at most one wall may be broken
- return
-1if no valid path exists
Brute-Force Approach
Try all paths while tracking whether a wall has already been broken.
That is exponential and repeats many states.
Better Approach
Run BFS on expanded states.
Why the Better Approach Works
The graph is still unweighted, but each physical cell now has two logical versions:
- not yet used the wall break
- already used the wall break
Pragmatic Java Choice
Use a queue of state arrays and a three-dimensional visited array.
Java Solution
import java.util.ArrayDeque;
class GridWallBreakBfsExample {
static int shortestPath(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
boolean[][][] visited = new boolean[rows][cols][2];
ArrayDeque<int[]> queue = new ArrayDeque<>();
queue.add(new int[] {0, 0, 0, 0});
visited[0][0][0] = true;
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
int[] current = queue.remove();
int row = current[0];
int col = current[1];
int usedBreak = current[2];
int distance = current[3];
if (row == rows - 1 && col == cols - 1) {
return distance;
}
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (nextRow < 0 || nextRow >= rows || nextCol < 0 || nextCol >= cols) {
continue;
}
int nextUsedBreak = usedBreak;
if (grid[nextRow][nextCol] == 1) {
if (usedBreak == 1) {
continue;
}
nextUsedBreak = 1;
}
if (!visited[nextRow][nextCol][nextUsedBreak]) {
visited[nextRow][nextCol][nextUsedBreak] = true;
queue.add(new int[] {nextRow, nextCol, nextUsedBreak, distance + 1});
}
}
}
return -1;
}
}
Dry Run
If the first promising path hits one wall:
- move into that wall cell using the one allowed break
- continue BFS from state
(row, col, 1) - later revisiting the same cell with break state
0would still be different and potentially useful
That distinction is the whole reason ordinary BFS on plain cells is insufficient.
Time and Space Complexity
Brute-force path search:
- Time: exponential in the worst case
- Space: depends on recursion depth and visited-path tracking
Expanded-state BFS:
- Time:
O(rows * cols)because each cell-state pair is processed at most once - Space:
O(rows * cols)
Edge Cases
- start or end cell handling when one is a wall
- no path even after one break
- shortest path that never uses the break
Common Mistakes
- using a two-dimensional visited array instead of tracking the break state
- marking a cell visited too aggressively across both states
- forgetting to stop wall-breaking after the first use
4. Complexity and Decision Guide
Advanced graph problems split mainly by what the graph represents.
- max flow algorithms solve capacity and assignment problems, not shortest-distance problems
- state-expanded BFS or Dijkstra solves constrained movement problems where the node identity includes extra information
- advanced graph modeling is often the real bottleneck, because a poor model leads to the wrong algorithm
When to choose brute force:
- tiny networks or tiny compatibility sets while discovering the model
- small constrained-state examples used only to verify correctness reasoning
When to optimize:
- capacities or assignments make plain traversal meaningless
- the same node must be revisited under different resource states
- the problem naturally describes conservation, blocking, or matching
Recognition signals:
- source, sink, capacity, assignment, or throughput suggests flow
- one coupon, one wall break, one mode switch, or limited resource suggests shortest path with state
- bipartite choices or one-to-one assignments often suggest flow-based modeling or matching
Signals not to force these techniques:
- a plain unweighted reachability problem that BFS already solves
- a standard weighted graph problem with no extra state, where Dijkstra is sufficient
- a problem where the modeled graph size explodes because the state is not compressed properly
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- residual graph updates missing reverse capacity
- treating revisited stateful nodes as duplicates when their state differs
- forgetting to preserve original problem constraints in the graph model
- mixing capacity problems with distance problems
Short debugging checklist:
- draw the graph model for a tiny example
- for flow, print each augmenting path and bottleneck
- for state-expanded shortest paths, print the full state tuple being visited
- verify that the visited structure matches the full logical state
- after max flow, inspect residual reachability if a cut interpretation is needed
6. Practice Problems
Easy
Title: Basic Max Flow Network
Prompt: Compute the maximum flow in a small directed capacity network.
Expected pattern or core idea: Residual graph and Edmonds-Karp.
Title: One Special Move Grid
Prompt: Reach the destination in a grid when one blocked cell may be bypassed.
Expected pattern or core idea: BFS on expanded state.
Title: Bipartite Matching Starter
Prompt: Match people to tasks with one-to-one constraints.
Expected pattern or core idea: Graph modeling into a matching or flow problem.
Medium
Title: Max Flow Min Cut Interpretation
Prompt: Find the minimum cut edges after computing a maximum flow.
Expected pattern or core idea: Residual reachability after max flow.
Title: Shortest Path with Discount Coupon
Prompt: Reach a destination where one edge may be taken at reduced cost.
Expected pattern or core idea: Dijkstra or BFS with extra state dimension.
Title: Course Assignment Variant
Prompt: Assign students to courses under one-seat and compatibility constraints.
Expected pattern or core idea: Advanced graph modeling into flow.
Hard
Title: Multiple Resource Constrained Path
Prompt: Find a shortest path while tracking fuel, coupons, or permissions.
Expected pattern or core idea: State-expanded shortest path with careful compression.
Title: Minimum Edge Cut Construction
Prompt: Identify a minimum-capacity cut separating source and sink.
Expected pattern or core idea: Max flow min cut theorem in practice.
Title: Scheduling as Flow Network
Prompt: Model a richer allocation problem with capacities across multiple layers.
Expected pattern or core idea: Multi-layer graph modeling and flow reasoning.
7. Short Recap
The core idea is that advanced graph algorithms depend on choosing the right graph meaning before coding anything. The most important optimization insight is that capacities call for flow, while constrained movement often calls for state-expanded shortest paths. The most important implementation warning is to keep residual or state information faithful to the real constraints. This prepares the next chapter, where string problems demand the same modeling care with prefixes, hashes, and automaton-style matching.
8. Coverage Check
- 37.1 Flow network basics - Covered
- 37.2 Ford-Fulkerson - Covered
- 37.3 Edmonds-Karp - Covered
- 37.4 Max flow min cut - Covered
- 37.5 Shortest path with state - Covered
- 37.6 Advanced graph modeling - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Advanced String Algorithms
38: Advanced String Algorithms
Goal: Teach how to solve string-matching problems efficiently with linear-time prefix methods, rolling hashes, and trie-based matching strategies.
Outcome: By the end of this chapter, you can implement KMP, Z algorithm, and Rabin-Karp in Java, explain rolling hash mechanics, use trie-based prefix matching, and choose the right string-matching tool by constraints.
1. Intuition First
This chapter matters because brute-force string matching wastes work. When you shift a pattern by one character and compare almost the same prefix again, a good algorithm should reuse what is already known.
A simple real-world analogy is searching a long document for a phrase. If the phrase almost matches and then fails near the end, you should not restart from zero if part of that failed attempt still gives information about the next possible alignment.
The core mental model is:
- preprocess the pattern, the text, or both
- reuse structural information instead of restarting full comparisons
- choose the algorithm based on whether you need exact one-pattern search, hash-based filtering, or many-prefix matching
The most common beginner confusion point is treating all string-matching algorithms as interchangeable. They solve related problems, but their trade-offs differ in preprocessing, collision risk, multiple-pattern support, and implementation complexity.
This chapter continues the advanced-pattern mindset of Part VII. The next chapter shifts from strings to monotonic structures and interval reasoning.
2. Core Concepts and Techniques
Concept Cluster: Linear Prefix-Based Matching
Key concepts in this block:
- 38.1 KMP algorithm
- 38.2 Z algorithm
Intuition
Both KMP and Z algorithm avoid recomparing known matching prefixes.
Why It Matters
They give linear-time exact pattern matching without probabilistic hashing.
How It Works
KMP:
- preprocess the pattern's longest proper prefix that is also a suffix, often called LPS
- when a mismatch happens, jump within the pattern instead of restarting from the next text index blindly
Z algorithm:
- compute, for each position, the length of the longest substring starting there that matches the overall string prefix
- for pattern search, run Z on
pattern + separator + text
Java Implementation Notes
- KMP code is easier to maintain if LPS construction is separate from search.
- Use a separator character in Z concatenation that does not appear in either input.
- Keep index movement explicit to avoid infinite loops after mismatch handling.
Common Mistakes
- incorrect LPS fallback on mismatch
- using a separator that appears in the pattern or text for Z algorithm
- forgetting to record full matches when the matched length equals the pattern length
Quick Example
If the pattern prefix "abab" already matched and a mismatch occurs next, KMP can often resume with the shorter border "ab" instead of starting from zero.
Debugging Tip
Print the LPS or Z array for a tiny pattern first. If preprocessing is wrong, the search phase will be wrong too.
Advanced Note
KMP and Z are both linear, but some developers find one preprocessing array easier to reason about than the other. Learn both so you can choose the cleaner explanation in an interview.
Concept Cluster: Hash-Based Matching
Key concepts in this block:
- 38.3 Rabin-Karp
- 38.4 Rolling hash
Intuition
Instead of comparing whole substrings character by character, compare compact numeric fingerprints that update in constant time as the window slides.
Why It Matters
Hashing can be simple and fast in practice, especially for repeated window checks or multiple patterns of the same length.
How It Works
Rolling hash:
- represent a string window as a polynomial-like hash
- remove the outgoing character contribution
- shift by the base and add the incoming character contribution
Rabin-Karp:
- compare the hash of the pattern with each text-window hash
- when hashes match, verify the actual substring to guard against collisions
Java Implementation Notes
- Use
longand a modulus to reduce overflow. - Precompute powers of the base when needed.
- Always keep the collision-check verification step in exact matching code.
Common Mistakes
- forgetting modulus normalization after subtraction
- assuming equal hashes always mean equal substrings
- inconsistent character encoding in the hash formula
Quick Example
When moving from window "abc" to "bcd", rolling hash removes 'a', shifts the remaining contribution, and adds 'd'.
Debugging Tip
On a short text, print the window substring and its hash together to verify the rolling update logic.
Advanced Note
Double hashing can reduce collision risk further, but the conceptual model is the same.
Concept Cluster: Trie Matching and Algorithm Choice
Key concepts in this block:
- 38.5 Trie-based string matching
- 38.6 Choosing the right string-matching approach
Intuition
Tries are useful when many patterns share prefixes. Algorithm choice depends on whether the main cost comes from one pattern, many patterns, or repeated substring comparisons.
Why It Matters
Choosing the wrong matcher is a frequent interview mistake. The best method depends on the exact query pattern and constraints.
How It Works
Trie-based string matching:
- build a trie from patterns or dictionary words
- walk characters from each relevant text position or query prefix
- report matches whenever a terminal trie node is reached
Choosing the right approach:
- KMP for deterministic one-pattern search
- Z algorithm for elegant prefix-based matching setups
- Rabin-Karp for rolling-window hashing and repeated equal-length checks
- trie-based matching for many shared-prefix patterns or dictionary-driven prefix matching
Java Implementation Notes
- Use array children for lowercase letters when the alphabet is fixed and small.
- Store terminal markers or counts at trie nodes.
- Separate the trie build phase from the text scan phase.
Common Mistakes
- building a trie when one pattern is enough and KMP would be simpler
- forgetting to reset the trie walk when scanning from a new start position
- choosing hashing without thinking about collisions or pattern lengths
Quick Example
If the dictionary contains "cat", "car", and "care", then all three share the path for prefix "ca" in the trie.
Debugging Tip
Before coding the full matcher, verify the trie insert and one simple prefix walk with a hand-built dictionary.
Advanced Note
More advanced multiple-pattern matching structures build on trie ideas, but the core prefix-sharing intuition starts here.
3. Worked Examples and Full Solutions
Worked Example 1: KMP Exact Pattern Search
Problem Statement
Given a text and a pattern, return all starting indices where the pattern appears in the text.
Why This Example Matters
This is the canonical exact pattern-matching problem for KMP.
Constraints or Assumptions
- exact case-sensitive matching
- overlapping matches should be reported
- empty pattern handling should be explicit
Brute-Force Approach
Try every starting index in the text and compare the pattern character by character.
That costs O(textLength * patternLength) in the worst case.
Better Approach
Precompute the LPS array and run KMP.
Why the Better Approach Works
The LPS array tells how much matched-prefix information can be reused after a mismatch, so the text index never moves backward.
Pragmatic Java Choice
Split the solution into LPS construction and search.
Java Solution
import java.util.ArrayList;
import java.util.List;
class KmpSearchExample {
static List<Integer> search(String text, String pattern) {
List<Integer> matches = new ArrayList<>();
if (pattern.isEmpty()) {
return matches;
}
int[] lps = buildLps(pattern);
int textIndex = 0;
int patternIndex = 0;
while (textIndex < text.length()) {
if (text.charAt(textIndex) == pattern.charAt(patternIndex)) {
textIndex++;
patternIndex++;
if (patternIndex == pattern.length()) {
matches.add(textIndex - pattern.length());
patternIndex = lps[patternIndex - 1];
}
} else if (patternIndex > 0) {
patternIndex = lps[patternIndex - 1];
} else {
textIndex++;
}
}
return matches;
}
private static int[] buildLps(String pattern) {
int[] lps = new int[pattern.length()];
int length = 0;
for (int index = 1; index < pattern.length(); ) {
if (pattern.charAt(index) == pattern.charAt(length)) {
length++;
lps[index] = length;
index++;
} else if (length > 0) {
length = lps[length - 1];
} else {
lps[index] = 0;
index++;
}
}
return lps;
}
}
Dry Run
Text: "ababcabcabababd", pattern: "ababd"
- KMP matches several prefix characters
- after a mismatch, the LPS array says how far the pattern index can fall back
- the search continues without restarting full text comparisons
- final match occurs at index
10
Time and Space Complexity
Brute-force matching:
- Time:
O(n * m) - Space:
O(1)
KMP:
- Time:
O(n + m) - Space:
O(m)
Edge Cases
- empty pattern
- pattern longer than text
- repeated-prefix patterns such as
"aaaa"
Common Mistakes
- wrong LPS fallback logic
- failing to allow overlapping matches
- moving both indices incorrectly after mismatch
Worked Example 2: Pattern Search with Z Algorithm
Problem Statement
Given a text and a pattern, return all starting indices where the pattern appears in the text using the Z algorithm.
Why This Example Matters
This example shows a different linear-time view of the same matching problem through prefix matches.
Constraints or Assumptions
- choose a separator not present in the inputs
- exact pattern matching only
- overlapping matches should be reported
Brute-Force Approach
Try every starting index in the text and compare character by character.
That is again O(n * m) in the worst case.
Better Approach
Build the Z array on pattern + separator + text.
Why the Better Approach Works
If the Z value at a position inside the text portion equals the pattern length, then the pattern matches starting there.
Pragmatic Java Choice
Keep the concatenated string and one reusable Z-array builder.
Java Solution
import java.util.ArrayList;
import java.util.List;
class ZAlgorithmSearchExample {
static List<Integer> search(String text, String pattern) {
List<Integer> matches = new ArrayList<>();
if (pattern.isEmpty()) {
return matches;
}
String combined = pattern + "#" + text;
int[] z = buildZ(combined);
int patternLength = pattern.length();
for (int index = patternLength + 1; index < combined.length(); index++) {
if (z[index] == patternLength) {
matches.add(index - patternLength - 1);
}
}
return matches;
}
private static int[] buildZ(String text) {
int[] z = new int[text.length()];
int left = 0;
int right = 0;
for (int index = 1; index < text.length(); index++) {
if (index <= right) {
z[index] = Math.min(right - index + 1, z[index - left]);
}
while (index + z[index] < text.length()
&& text.charAt(z[index]) == text.charAt(index + z[index])) {
z[index]++;
}
if (index + z[index] - 1 > right) {
left = index;
right = index + z[index] - 1;
}
}
return z;
}
}
Dry Run
Pattern "ana", text "bananas"
- combined string is
"ana#bananas" - when a text position produces
z[index] = 3, the pattern matches there - matches occur at original text indices
1and3
Time and Space Complexity
Brute-force matching:
- Time:
O(n * m) - Space:
O(1)
Z algorithm:
- Time:
O(n + m) - Space:
O(n + m)for the combined string and Z array
Edge Cases
- separator accidentally present in input
- pattern of length
1 - repeated characters leading to large Z boxes
Common Mistakes
- wrong offset when converting a combined-string index back to a text index
- not shrinking Z reuse to the current box boundary
- misplacing the separator
Worked Example 3: Rabin-Karp with Rolling Hash
Problem Statement
Given a text and a pattern, return all starting indices where the pattern appears in the text using Rabin-Karp.
Why This Example Matters
This example teaches rolling hash directly and shows where probabilistic filtering is useful.
Constraints or Assumptions
- exact case-sensitive matching
- collisions are handled by verification
- lowercase English letters are used in this implementation for simplicity
Brute-Force Approach
Compare each length-m text window directly with the pattern.
That costs O(n * m) in the worst case.
Better Approach
Use rolling hash to compare hashes first, then verify only on hash matches.
Why the Better Approach Works
The rolling hash updates a window in constant time, so most positions avoid full substring comparison.
Pragmatic Java Choice
Use long, a base, a modulus, and a verification step.
Java Solution
import java.util.ArrayList;
import java.util.List;
class RabinKarpExample {
private static final long BASE = 911382323L;
private static final long MOD = 1_000_000_007L;
static List<Integer> search(String text, String pattern) {
List<Integer> matches = new ArrayList<>();
int n = text.length();
int m = pattern.length();
if (m == 0 || m > n) {
return matches;
}
long highestPower = 1;
for (int index = 1; index < m; index++) {
highestPower = (highestPower * BASE) % MOD;
}
long patternHash = 0;
long windowHash = 0;
for (int index = 0; index < m; index++) {
patternHash = (patternHash * BASE + pattern.charAt(index)) % MOD;
windowHash = (windowHash * BASE + text.charAt(index)) % MOD;
}
for (int start = 0; start <= n - m; start++) {
if (patternHash == windowHash && text.regionMatches(start, pattern, 0, m)) {
matches.add(start);
}
if (start < n - m) {
long outgoing = (text.charAt(start) * highestPower) % MOD;
windowHash = (windowHash - outgoing + MOD) % MOD;
windowHash = (windowHash * BASE + text.charAt(start + m)) % MOD;
}
}
return matches;
}
}
Dry Run
Text "abracadabra", pattern "abra"
- compute the initial pattern and window hashes
- compare them at index
0, verify the actual substring, and record a match - roll the window one step at a time
- another verified match appears at index
7
Time and Space Complexity
Brute-force matching:
- Time:
O(n * m) - Space:
O(1)
Rabin-Karp:
- Average Time:
O(n + m)plus verification on hash matches - Worst-Case Time:
O(n * m)if many collisions trigger verification - Space:
O(1)extra beyond output
Edge Cases
- pattern longer than text
- repeated-character windows
- collision-heavy adversarial cases
Common Mistakes
- forgetting modulus normalization after removing the outgoing character
- skipping substring verification after a hash match
- computing the wrong highest power
Worked Example 4: Trie-Based Dictionary Matching in Text
Problem Statement
Given a dictionary of lowercase words and a text, return all starting indices where at least one dictionary word matches as a prefix of the text from that index.
Why This Example Matters
This example shows how trie-based string matching helps when many patterns share prefixes.
Constraints or Assumptions
- dictionary words and text use lowercase English letters
- matching any dictionary word from a start index is enough to report that start index
- overlapping matches are allowed
Brute-Force Approach
At each text position, compare every dictionary word character by character.
That repeats prefix work heavily.
Better Approach
Insert all dictionary words into a trie, then walk the trie from each start position.
Why the Better Approach Works
Shared prefixes are stored once. From a given start index, the trie walk explores only prefixes that actually exist in the dictionary.
Pragmatic Java Choice
Use fixed-size child arrays for lowercase letters.
Java Solution
import java.util.ArrayList;
import java.util.List;
class TrieTextMatchingExample {
static final class TrieNode {
final TrieNode[] children = new TrieNode[26];
boolean isWord;
}
static List<Integer> matchStarts(String text, List<String> dictionary) {
TrieNode root = new TrieNode();
for (String word : dictionary) {
insert(root, word);
}
List<Integer> starts = new ArrayList<>();
for (int start = 0; start < text.length(); start++) {
TrieNode current = root;
for (int index = start; index < text.length(); index++) {
int childIndex = text.charAt(index) - 'a';
if (childIndex < 0 || childIndex >= 26 || current.children[childIndex] == null) {
break;
}
current = current.children[childIndex];
if (current.isWord) {
starts.add(start);
break;
}
}
}
return starts;
}
private static void insert(TrieNode root, String word) {
TrieNode current = root;
for (int index = 0; index < word.length(); index++) {
int childIndex = word.charAt(index) - 'a';
if (current.children[childIndex] == null) {
current.children[childIndex] = new TrieNode();
}
current = current.children[childIndex];
}
current.isWord = true;
}
}
Dry Run
Text: "cartoon", dictionary: ["car", "toon", "art"]
- start
0: trie walk matches"car", so record0 - start
1: trie walk matches"art", so record1 - later start positions may match
"toon"
The trie avoids restarting comparisons separately for every dictionary word.
Time and Space Complexity
Brute-force dictionary scan:
- Time: up to
O(textLength * dictionarySize * averageWordLength) - Space:
O(1)extra beyond dictionary storage
Trie-based matching:
- Build Time:
O(totalDictionaryCharacters) - Query Time: depends on traversed prefixes, often much better when prefixes are shared
- Space:
O(totalDictionaryCharacters * alphabetFactor)in this array-child implementation
Edge Cases
- empty dictionary
- text shorter than every word
- multiple dictionary words sharing one start index
Common Mistakes
- not resetting the trie walk for each start position
- assuming trie-based matching is always better for one pattern
- failing on characters outside the assumed alphabet
4. Complexity and Decision Guide
The main trade-off in this chapter is what kind of reuse the problem allows.
- KMP and Z algorithm give deterministic linear-time exact matching for one pattern
- Rabin-Karp gives rolling-window efficiency and is especially convenient for repeated equal-length checks or hash-based filtering
- trie-based matching helps when many patterns share prefixes or the queries are prefix-oriented
When to choose brute force:
- one very short pattern and one short text
- a one-off check where preprocessing would dominate
When to optimize:
- long texts with repetitive mismatch structure
- many search requests over shared-prefix dictionaries
- repeated same-length window comparisons
Recognition signals:
- exact one-pattern search with deterministic linear time desired: KMP or Z
- natural rolling window or many equal-length comparisons: Rabin-Karp with rolling hash
- many shared-prefix patterns or prefix lookup: trie-based matching
Signals not to force a technique:
- building a trie for one short pattern
- using Rabin-Karp without collision verification in exact matching
- choosing KMP or Z when the task is really dictionary/prefix search rather than single-pattern search
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- wrong preprocessing array values for LPS or Z
- off-by-one errors when translating combined-string indices back to text positions
- incorrect rolling-hash subtraction or modulus handling
- trie alphabet assumptions not matching the real input
Short debugging checklist:
- print the preprocessing array for a small example
- test overlapping matches explicitly
- verify rolling hash against direct substring hashing on tiny inputs
- test trie insert and one prefix walk before scanning the full text
- choose the algorithm only after clarifying whether the problem is one-pattern, hash-window, or dictionary-driven
6. Practice Problems
Easy
Title: Implement KMP Search
Prompt: Return all match positions of a pattern inside a text.
Expected pattern or core idea: LPS preprocessing and deterministic linear scan.
Title: Pattern Search with Z Algorithm
Prompt: Find pattern occurrences by computing a Z array on a combined string.
Expected pattern or core idea: Prefix-length reuse across positions.
Title: Rolling Hash Window Check
Prompt: Compare many equal-length substrings efficiently.
Expected pattern or core idea: Constant-time rolling hash updates.
Medium
Title: Rabin-Karp Pattern Search
Prompt: Find all pattern matches with rolling hash and collision verification.
Expected pattern or core idea: Hash-first, verify-on-match search.
Title: Trie Dictionary Prefix Matching
Prompt: Detect dictionary words while scanning a text or answering prefix queries.
Expected pattern or core idea: Shared-prefix trie traversal.
Title: Repeated String Match Variant
Prompt: Determine whether one string appears inside repeated copies of another.
Expected pattern or core idea: Choose a matcher by constraints and text construction.
Hard
Title: Multiple Pattern Search Overview
Prompt: Search for many dictionary words in one large text.
Expected pattern or core idea: Trie-based matching direction and prefix reuse.
Title: Longest Duplicate Substring Discussion
Prompt: Find repeated substrings in a large text using hashing and binary search ideas.
Expected pattern or core idea: Rolling hash under stronger constraints.
Title: String Matching Strategy Comparison
Prompt: Pick the right matcher for several different input scenarios.
Expected pattern or core idea: Constraint-driven choice among KMP, Z, hashing, and trie-based matching.
7. Short Recap
The core idea is to reuse structure in strings instead of restarting full comparisons after every mismatch or shift. The most important optimization insight is that different matchers reuse different information: borders for KMP, prefix boxes for Z, rolling fingerprints for Rabin-Karp, and shared prefixes for tries. The most important implementation warning is to keep preprocessing and index translation exact. This prepares the next chapter, where monotonic structures and interval patterns shift focus from strings to ordered ranges and event reasoning.
8. Coverage Check
- 38.1 KMP algorithm - Covered
- 38.2 Z algorithm - Covered
- 38.3 Rabin-Karp - Covered
- 38.4 Rolling hash - Covered
- 38.5 Trie-based string matching - Covered
- 38.6 Choosing the right string-matching approach - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Monotonic Structures and Interval Patterns
39: Monotonic Structures and Interval Patterns
Goal: Teach how to use monotonic stacks, monotonic queues, interval merging, and sweep-line reasoning to solve order-sensitive problems efficiently.
Outcome: By the end of this chapter, you can recognize monotonic stack and queue signals, solve next-greater and histogram problems, merge intervals correctly, and explain when sweep-line thinking is the right abstraction.
1. Intuition First
This chapter matters because many array and interval problems are really about preserving the right order information while elements enter and leave consideration. A plain stack or queue is not enough unless it keeps a useful order invariant.
A simple real-world analogy is standing in a line of buildings and asking which taller building appears next for each one. You do not need every previous building forever. You only need the candidates that could still matter.
The core mental model is:
- maintain only the candidates that are still useful
- remove dominated elements as soon as they can never matter again
- sort interval endpoints or events when the problem is about overlapping time or space
The most common beginner confusion point is using a monotonic structure without being able to say what is monotonic. If you cannot state the invariant, the structure will feel like a memorized trick rather than a reasoning tool.
This chapter is the last major algorithm-pattern chapter before the final problem-solving chapter. It connects sequence order, interval order, and event order in one toolkit.
2. Core Concepts and Techniques
Concept Cluster: Order-Maintaining Linear Structures
Key concepts in this block:
- 39.1 Monotonic stack
- 39.2 Monotonic queue
- 39.3 Next greater element
Intuition
A monotonic stack or queue keeps elements in increasing or decreasing order so dominated elements are removed immediately.
Why It Matters
These structures turn many repeated scans into linear-time passes.
How It Works
Monotonic stack:
- often stores indices
- pops while the current value breaks the chosen monotonic order
- the popped element has just found its answer or has become useless
Monotonic queue:
- supports a sliding window
- removes expired indices from the front
- removes dominated values from the back
Next greater element:
- scan while maintaining a decreasing stack of unresolved indices
- when a larger value appears, resolve all smaller ones on top
Java Implementation Notes
- Store indices rather than raw values when window bounds or answer positions matter.
- Use
ArrayDeque<Integer>for both stack and queue roles. - Decide whether equal values should stay or be removed based on the exact problem statement.
Common Mistakes
- forgetting to remove expired indices in a window problem
- storing values when the index is needed later
- using the wrong strictness with equal values and breaking the invariant
Quick Example
For next greater element, a decreasing stack of unresolved values collapses as soon as a larger number appears.
Debugging Tip
Write the invariant as a sentence, for example: "indices in the deque are inside the current window and their values are in decreasing order."
Advanced Note
Many monotonic-structure problems are really "nearest previous/next element satisfying a relation" problems.
Concept Cluster: Area and Interval Consolidation
Key concepts in this block:
- 39.4 Histogram problems
- 39.5 Merge intervals
Intuition
Histogram and interval problems both depend on correctly identifying spans.
Why It Matters
They appear constantly in interviews and reward strong invariant-based thinking.
How It Works
Histogram problems:
- for each bar, find how far it can extend left and right while remaining the minimum height
- monotonic stacks reveal those boundaries efficiently
Merge intervals:
- sort intervals by start time
- walk left to right, merging overlaps into one growing current interval
Java Implementation Notes
- Add a sentinel height or one final cleanup pass in histogram solutions.
- Sort intervals by start, then by end when needed.
- Treat touching intervals according to the problem's overlap definition.
Common Mistakes
- forgetting to flush the remaining histogram stack at the end
- not sorting before merging intervals
- mixing closed and half-open interval semantics
Quick Example
If intervals [1, 4] and [2, 5] overlap, the merged interval becomes [1, 5].
Debugging Tip
For histogram problems, print each popped index with the computed width. For interval problems, print the current merged interval after each step.
Advanced Note
The same span-finding intuition behind histogram problems also appears in matrix and subarray optimization variants.
Concept Cluster: Event-Ordered Reasoning
Key concepts in this block:
- 39.6 Sweep line overview
Intuition
Sweep line processes starts, ends, or other events in sorted order while maintaining active information.
Why It Matters
It turns many geometric, interval, and scheduling problems into ordered event processing.
How It Works
Typical sweep-line steps:
- convert each object into one or more events
- sort events by position or time
- update an active set or counter while walking through the events
Java Implementation Notes
- Represent events as simple objects or arrays and sort with a comparator.
- Be explicit about tie-breaking when start and end events share the same coordinate.
- Choose the active structure based on the query: count, min, max, or set membership.
Common Mistakes
- wrong event ordering on ties
- forgetting to remove expired events from the active structure
- using sweep line when a simpler sort-and-merge is enough
Quick Example
To count the maximum number of overlapping meetings, create a +1 event at each start and a -1 event at each end, then sweep through sorted events.
Debugging Tip
Write out the event list after sorting. Many sweep-line bugs come from incorrect event ordering rather than the active-set logic.
Advanced Note
Sweep line is an approach, not one fixed data structure. The active information determines the final implementation.
3. Worked Examples and Full Solutions
Worked Example 1: Next Greater Element
Problem Statement
Given an integer array, return an array where each position stores the next greater value to its right, or -1 if none exists.
Why This Example Matters
This is the standard monotonic-stack problem and the cleanest place to learn the invariant.
Constraints or Assumptions
- the next greater value must be strictly greater
- only the first greater value to the right counts
- duplicates may appear
Brute-Force Approach
For each index, scan rightward until a larger value is found.
That costs O(n^2) in the worst case.
Better Approach
Use a decreasing monotonic stack of indices.
Why the Better Approach Works
When the current value is greater than the value at the stack top, it is the answer for that unresolved index and possibly others below it.
Pragmatic Java Choice
Use ArrayDeque<Integer> and store indices.
Java Solution
import java.util.ArrayDeque;
import java.util.Arrays;
class NextGreaterElementExample {
static int[] nextGreater(int[] values) {
int[] answer = new int[values.length];
Arrays.fill(answer, -1);
ArrayDeque<Integer> stack = new ArrayDeque<>();
for (int index = 0; index < values.length; index++) {
while (!stack.isEmpty() && values[stack.peek()] < values[index]) {
answer[stack.pop()] = values[index];
}
stack.push(index);
}
return answer;
}
}
Dry Run
Input: [2, 1, 2, 4, 3]
- stack starts with index
0 - index
2resolves index1 - value
4resolves both earlier2values waiting on the stack - remaining unresolved indices keep
-1
Answer: [4, 2, 4, -1, -1]
Time and Space Complexity
Brute-force scan:
- Time:
O(n^2) - Space:
O(1)extra
Monotonic stack:
- Time:
O(n) - Space:
O(n)
Edge Cases
- strictly decreasing array
- strictly increasing array
- duplicate values
Common Mistakes
- storing values instead of indices when positions matter
- using
<=instead of<without checking the problem's strictness - forgetting unresolved entries should remain
-1
Worked Example 2: Sliding Window Maximum
Problem Statement
Given an integer array and a window size k, return the maximum value in every contiguous window of length k.
Why This Example Matters
This is the standard monotonic-queue problem. It shows how to maintain the best window candidate while indices expire.
Constraints or Assumptions
1 <= k <= n- windows move one step at a time
- duplicates are allowed
Brute-Force Approach
For each window, scan all k elements and compute the maximum.
That costs O(nk).
Better Approach
Use a decreasing deque of indices.
Why the Better Approach Works
The deque front always holds the largest valid element in the current window. Smaller trailing elements are removed because they can never become the maximum while the larger newer element remains.
Pragmatic Java Choice
Use ArrayDeque<Integer> and expire indices from the front.
Java Solution
import java.util.ArrayDeque;
class SlidingWindowMaximumExample {
static int[] maxInWindows(int[] values, int k) {
int[] answer = new int[values.length - k + 1];
ArrayDeque<Integer> deque = new ArrayDeque<>();
for (int index = 0; index < values.length; index++) {
while (!deque.isEmpty() && deque.peekFirst() <= index - k) {
deque.removeFirst();
}
while (!deque.isEmpty() && values[deque.peekLast()] <= values[index]) {
deque.removeLast();
}
deque.addLast(index);
if (index >= k - 1) {
answer[index - k + 1] = values[deque.peekFirst()];
}
}
return answer;
}
}
Dry Run
Input: values = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
- first full window
[1, 3, -1]has max3 - when
5enters, smaller trailing elements are removed - the deque front always represents the current window maximum
Answer: [3, 3, 5, 5, 6, 7]
Time and Space Complexity
Brute-force per window:
- Time:
O(nk) - Space:
O(1)extra
Monotonic queue:
- Time:
O(n) - Space:
O(k)up toO(n)in general analysis
Edge Cases
k = 1- all equal values
- window maximum leaving the window boundary
Common Mistakes
- forgetting to remove expired indices from the front
- removing from the wrong end
- using raw values without positions, making expiration impossible
Worked Example 3: Largest Rectangle in Histogram
Problem Statement
Given an array of bar heights, return the area of the largest rectangle that can be formed in the histogram.
Why This Example Matters
This is the standard histogram problem and a high-value monotonic-stack pattern.
Constraints or Assumptions
- heights are nonnegative integers
- rectangle width spans contiguous bars
- use a stack-based linear solution
Brute-Force Approach
For every bar, expand left and right until a smaller bar appears, then compute the area.
That costs O(n^2) in the worst case.
Better Approach
Use an increasing monotonic stack of indices.
Why the Better Approach Works
When a shorter bar appears, any taller bar on top of the stack has just found its right boundary. The new stack top gives its left boundary.
Pragmatic Java Choice
Append a sentinel iteration with height 0 to flush the stack.
Java Solution
import java.util.ArrayDeque;
class HistogramRectangleExample {
static int largestRectangle(int[] heights) {
ArrayDeque<Integer> stack = new ArrayDeque<>();
int best = 0;
for (int index = 0; index <= heights.length; index++) {
int currentHeight = index == heights.length ? 0 : heights[index];
while (!stack.isEmpty() && heights[stack.peek()] > currentHeight) {
int height = heights[stack.pop()];
int leftBoundary = stack.isEmpty() ? -1 : stack.peek();
int width = index - leftBoundary - 1;
best = Math.max(best, height * width);
}
stack.push(index);
}
return best;
}
}
Dry Run
Input: [2, 1, 5, 6, 2, 3]
- bars
5and6stay on the stack while heights increase - when height
2appears, both are popped and evaluated - the best rectangle area becomes
10
Time and Space Complexity
Brute-force span expansion:
- Time:
O(n^2) - Space:
O(1)
Monotonic stack:
- Time:
O(n) - Space:
O(n)
Edge Cases
- all bars equal
- strictly increasing heights
- strictly decreasing heights
- zero-height bars
Common Mistakes
- forgetting the final stack flush
- computing width from the wrong left boundary after a pop
- using
>=or>incorrectly and changing span behavior for equal heights
Worked Example 4: Merge Intervals
Problem Statement
Given a list of intervals, merge all overlapping intervals and return the merged list.
Why This Example Matters
This is a foundational interval pattern. It appears in scheduling, calendars, memory ranges, and event consolidation problems.
Constraints or Assumptions
- intervals are closed in this explanation
- intervals may be unsorted
- touching intervals should be merged if they overlap under the chosen definition
Brute-Force Approach
Repeatedly compare every pair of intervals, merging overlaps until no changes remain.
That is unnecessarily slow and awkward.
Better Approach
Sort by start time, then sweep once.
Why the Better Approach Works
After sorting, any interval that can overlap the current merged interval must appear next. No earlier interval can surprise you later.
Pragmatic Java Choice
Use a simple int[][] sort and a result list.
Java Solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class MergeIntervalsExample {
static int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (first, second) -> Integer.compare(first[0], second[0]));
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) {
merged.add(new int[] {interval[0], interval[1]});
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
}
}
return merged.toArray(new int[merged.size()][]);
}
}
Dry Run
Input: [[1, 3], [2, 6], [8, 10], [9, 12]]
- after sorting, start with
[1, 3] [2, 6]overlaps, so merge to[1, 6][8, 10]starts a new interval[9, 12]overlaps the current interval, so merge to[8, 12]
Answer: [[1, 6], [8, 12]]
Time and Space Complexity
Repeated pairwise merging:
- Time: worse than
O(n log n), oftenO(n^2)or more depending on implementation - Space: depends on repeated merge bookkeeping
Sort and merge:
- Time:
O(n log n)due to sorting - Space:
O(n)for the output list
Edge Cases
- empty input
- one interval only
- already disjoint intervals
- one interval fully containing another
Common Mistakes
- forgetting to sort first
- merging non-overlapping intervals by using the wrong comparison
- not clarifying whether touching endpoints count as overlap
4. Complexity and Decision Guide
The main trade-off in this chapter is between repeated rescanning and maintaining the right invariant once.
- monotonic stacks and queues are usually linear because each index enters and leaves once
- merge-interval patterns are usually dominated by sorting cost, then a linear sweep
- sweep-line approaches usually cost
O(n log n)from event sorting, plus active-structure updates
When to choose brute force:
- tiny arrays or interval counts
- first-pass reasoning to expose the nearest-greater or overlap structure
When to optimize:
- repeated nearest-greater or span-finding logic appears
- windows slide one step at a time
- intervals or events need consolidation after sorting
Recognition signals:
- next greater, previous smaller, or span wording suggests a monotonic stack
- sliding window min or max suggests a monotonic queue
- intervals that need combining suggest sort and merge
- active overlap counting or event boundary reasoning suggests sweep line
Signals not to force these techniques:
- the problem only needs one pass with a simpler counter or prefix sum
- the invariant cannot be stated clearly
- interval queries are dynamic rather than one-time sorted processing
5. Edge Cases, Pitfalls, and Debugging
Common implementation bugs:
- wrong monotonic invariant for equal values
- forgetting to expire indices in window problems
- missing the final cleanup pass in stack problems
- merging intervals without sorting
- tie-breaking events incorrectly in sweep-line solutions
Short debugging checklist:
- write the monotonic invariant in one sentence
- test strictly increasing and strictly decreasing cases
- test duplicate values explicitly
- print the sorted intervals or event list before processing
- verify whether interval endpoints are closed, open, or half-open
6. Practice Problems
Easy
Title: Next Greater Element
Prompt: Return the first greater value to the right for every position.
Expected pattern or core idea: Decreasing monotonic stack.
Title: Daily Temperatures
Prompt: Return how many days each temperature waits for a warmer day.
Expected pattern or core idea: Monotonic stack on unresolved indices.
Title: Merge Intervals
Prompt: Merge overlapping intervals after sorting.
Expected pattern or core idea: Interval consolidation sweep.
Medium
Title: Sliding Window Maximum
Prompt: Return the maximum in every window of size k.
Expected pattern or core idea: Monotonic queue with expiring indices.
Title: Largest Rectangle in Histogram
Prompt: Return the largest rectangle area in a histogram.
Expected pattern or core idea: Increasing monotonic stack for boundaries.
Title: Meeting Rooms II
Prompt: Return the minimum number of meeting rooms needed.
Expected pattern or core idea: Sweep line or sorted starts/ends reasoning.
Hard
Title: Maximal Rectangle
Prompt: Find the largest rectangle of ones in a binary matrix.
Expected pattern or core idea: Histogram reduction plus monotonic stack.
Title: Trapping Rain Water II Discussion
Prompt: Extend boundary reasoning to a harder two-dimensional setting.
Expected pattern or core idea: Recognize when monotonic ideas do and do not transfer directly.
Title: Skyline Problem Overview
Prompt: Compute the outer skyline of buildings from interval events.
Expected pattern or core idea: Sweep line with active heights.
7. Short Recap
The core idea is to maintain only the candidates or events that can still affect future answers. The most important optimization insight is that monotonic structures and interval sweeps remove dominated elements immediately instead of rescanning them later. The most important implementation warning is to define the invariant and boundary rules before coding. This prepares the next chapter, which turns all the earlier patterns into a disciplined interview and contest problem-solving workflow.
8. Coverage Check
- 39.1 Monotonic stack - Covered
- 39.2 Monotonic queue - Covered
- 39.3 Next greater element - Covered
- 39.4 Histogram problems - Covered
- 39.5 Merge intervals - Covered
- 39.6 Sweep line overview - Covered
Coverage Summary: 6/6 official subtopics covered
Next: Problem Solving for Interviews and Contests
40: Problem Solving for Interviews and Contests
Goal: Teach a repeatable workflow for turning unfamiliar problems into correct, explainable, bug-resistant Java solutions under interview or contest pressure.
Outcome: By the end of this chapter, you can move from brute force to optimization methodically, classify problems by pattern and constraints, write cleaner Java under time pressure, explain your reasoning clearly, and build a sustainable long-term practice system.
1. Intuition First
This chapter matters because knowing many algorithms is not enough. Interviews and contests reward the ability to identify the right tool, justify it quickly, implement it reliably, and recover when the first idea is not good enough.
A simple real-world analogy is diagnosing a machine failure. An expert does not randomly replace parts. They observe symptoms, form a baseline explanation, test the next most likely cause, and only then choose the repair.
The core mental model is:
- understand the problem completely before optimizing
- produce a correct brute-force baseline first when possible
- use constraints and patterns to choose the next improvement
- implement in a bug-resistant order and explain the final reasoning clearly
The most common beginner confusion point is jumping straight to a memorized optimal technique before the baseline is even correct. That leads to fragile code and weak explanations.
This chapter closes the DSA roadmap. It converts the previous thirty-nine chapters from isolated techniques into a reusable working system.
2. Core Concepts and Techniques
Concept Cluster: Structured Discovery
Key concepts in this block:
- 40.1 Brute force to optimal workflow
- 40.2 Pattern recognition checklist
- 40.3 Constraint-driven thinking
Intuition
Strong problem solving is a sequence of disciplined choices, not a flash of intuition.
Why It Matters
This workflow keeps you moving even when the final algorithm is not obvious immediately.
How It Works
Brute force to optimal workflow:
- restate the problem in plain language
- write or describe the simplest correct solution
- identify its bottleneck
- ask which earlier pattern removes that bottleneck
Pattern recognition checklist:
- does order matter
- is the structure a sequence, tree, graph, interval set, or string
- is the problem asking for min, max, count, existence, or construction
- are states repeating, suggesting DP
- are queries repeated, suggesting preprocessing
Constraint-driven thinking:
n <= 20may allow bitmask or subset searchnin the hundreds of thousands usually rules out quadratic solutions- weighted edges change BFS into Dijkstra or related tools
Java Implementation Notes
- Translate the chosen pattern into a named helper method or data structure quickly.
- Keep the baseline solution small so it helps reasoning rather than causing noise.
- Let constraints decide data types, recursion safety, and auxiliary structure sizes.
Common Mistakes
- guessing the pattern before identifying the bottleneck
- ignoring input-size limits
- optimizing a wrong baseline instead of fixing correctness first
Quick Example
If a brute-force nested loop is O(n^2) and the bottleneck is repeated prefix sums, hashing or prefix preprocessing may be the next step.
Debugging Tip
Before coding the optimized solution, say out loud: "My baseline is slow because of X, and this pattern removes X by doing Y once instead of repeatedly."
Advanced Note
In contests, the fastest route to the final solution is often a clean baseline plus one correct optimization step, not a leap to the deepest possible trick.
Concept Cluster: Reliable Delivery
Key concepts in this block:
- 40.4 Writing bug-resistant Java code
- 40.5 Explaining solutions clearly
Intuition
A correct idea still fails if the code is fragile or the explanation is vague.
Why It Matters
Interviewers evaluate reasoning quality, not just final output. Contests punish tiny implementation mistakes.
How It Works
Writing bug-resistant Java code:
- choose clear names
- define invariants and base cases first
- test boundary conditions early
- isolate complex logic into helpers
Explaining solutions clearly:
- start with the core observation
- define the chosen data structure or state
- explain why the transition or invariant is correct
- finish with time and space complexity
Java Implementation Notes
- Prefer small helper methods over one long
main-style block. - Use
longwhen sums or counts may exceedint. - Keep indexing and interval conventions consistent throughout the solution.
Common Mistakes
- one-letter names in nontrivial logic
- skipping edge-case discussion because the main idea feels obvious
- giving a complexity number without tying it to actual loops or operations
Quick Example
Instead of saying "I use a map and it works," say: "I store the earliest index for each prefix sum so I can detect the longest subarray reaching target k in constant time per position."
Debugging Tip
After coding, read the solution as if you are the interviewer. If you cannot explain one loop's invariant in one sentence, the code probably needs cleanup.
Advanced Note
Clear explanation often reveals missing correctness arguments before the bug shows up in testing.
Concept Cluster: Sustainable Improvement
Key concepts in this block:
- 40.6 Building a long-term practice system
Intuition
Skill does not come from random problem volume alone. It comes from repeated feedback loops.
Why It Matters
Without a system, solved problems fade quickly and weak areas keep repeating.
How It Works
A strong practice system includes:
- pattern-tagged problem logs
- short written notes on mistakes and corrected ideas
- spaced review of failed or slow problems
- balanced sets of easy, medium, and hard problems
Java Implementation Notes
- Keep a reusable Java template for input, output, graphs, trees, and common helpers.
- Save well-tested snippets for binary search, BFS, DFS, union-find, Fenwick tree, and DP skeletons.
- Record bug patterns such as off-by-one errors or wrong hash-map initialization.
Common Mistakes
- tracking only solved count, not error type or speed
- repeating favorite patterns while avoiding weak topics
- copying solutions without writing your own recap
Quick Example
After solving a graph problem, note not just "used BFS" but also why BFS was chosen over DFS or Dijkstra.
Debugging Tip
If the same bug appears three times across weeks, make it a named checklist item in your practice notes.
Advanced Note
Long-term growth comes from building a retrieval system for ideas and mistakes, not from depending on short-term memory.
3. Worked Examples and Full Solutions
Worked Example 1: Longest Subarray with Sum k
Problem Statement
Given an integer array and a target k, return the length of the longest subarray whose sum is exactly k.
Why This Example Matters
This example demonstrates the full brute-force-to-optimal workflow and shows how a bottleneck leads naturally to prefix sums plus hashing.
Constraints or Assumptions
- values may be positive, zero, or negative
- only the length is required, not the subarray itself
- prefix sums fit in
long
Brute-Force Approach
Try every start and end index and compute each subarray sum.
That is O(n^2) if sums are accumulated incrementally inside the inner loop.
Better Approach
Use prefix sums and store the earliest index for each prefix sum.
Why the Better Approach Works
If the current prefix sum is current, then a previous prefix sum of current - k means the subarray between those positions sums to k. Keeping the earliest index gives the longest such subarray.
Pragmatic Java Choice
Use HashMap<Long, Integer> and store the first occurrence only.
Java Solution
import java.util.HashMap;
import java.util.Map;
class LongestSubarraySumKExample {
static int longestLength(int[] values, int target) {
Map<Long, Integer> earliestIndex = new HashMap<>();
earliestIndex.put(0L, -1);
long prefixSum = 0;
int best = 0;
for (int index = 0; index < values.length; index++) {
prefixSum += values[index];
long needed = prefixSum - target;
if (earliestIndex.containsKey(needed)) {
best = Math.max(best, index - earliestIndex.get(needed));
}
earliestIndex.putIfAbsent(prefixSum, index);
}
return best;
}
}
Dry Run
Input: values = [1, -1, 5, -2, 3], k = 3
- prefix
1at index0 - prefix
0at index1 - prefix
5at index2 - prefix
3at index3, soneeded = 0, earliest index is-1, length is4
Answer: 4
Time and Space Complexity
Brute-force nested loops:
- Time:
O(n^2) - Space:
O(1)
Prefix sum plus hashing:
- Time:
O(n)average - Space:
O(n)
Edge Cases
- no valid subarray
- whole array sums to
k - negative values, which break simple sliding-window logic
Common Mistakes
- overwriting the earliest prefix index and losing longer answers
- using sliding window even though negative values are allowed
- forgetting the initial prefix sum
0at index-1
Worked Example 2: Top K Frequent Elements
Problem Statement
Given an integer array and an integer k, return the k most frequent elements.
Why This Example Matters
This example shows constraint-driven thinking. After counting frequencies, you must choose between sorting all keys, using a heap, or using buckets depending on constraints.
Constraints or Assumptions
1 <= k <= number of distinct values- order of the returned values is not important
- average-case hash-map performance is acceptable
Brute-Force Approach
Count frequencies, sort all distinct values by frequency, and take the first k.
That works, but sorting all keys may be unnecessary.
Better Approach
Use a min-heap of size k after frequency counting.
Why the Better Approach Works
The heap keeps only the best k candidates seen so far. Smaller-frequency entries are removed immediately.
Pragmatic Java Choice
Use HashMap<Integer, Integer> for counts and PriorityQueue<int[]> for the heap.
Java Solution
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
class TopKFrequentElementsExample {
static int[] topKFrequent(int[] values, int k) {
Map<Integer, Integer> frequency = new HashMap<>();
for (int value : values) {
frequency.merge(value, 1, Integer::sum);
}
PriorityQueue<int[]> minHeap = new PriorityQueue<>((first, second) -> Integer.compare(first[1], second[1]));
for (Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
minHeap.offer(new int[] {entry.getKey(), entry.getValue()});
if (minHeap.size() > k) {
minHeap.poll();
}
}
int[] answer = new int[k];
for (int index = k - 1; index >= 0; index--) {
answer[index] = minHeap.poll()[0];
}
return answer;
}
}
Dry Run
Input: values = [1, 1, 1, 2, 2, 3], k = 2
- frequency map becomes
{1=3, 2=2, 3=1} - heap keeps only the top
2frequency entries - value
3is removed because it is the least frequent
Answer contains 1 and 2.
Time and Space Complexity
Count and full sort:
- Time:
O(n + u log u), whereuis distinct value count - Space:
O(u)
Count and min-heap:
- Time:
O(n + u log k) - Space:
O(u + k)
Edge Cases
k = 1- all values equally frequent
- only one distinct value
Common Mistakes
- forgetting that sorting all keys is not always necessary
- writing a max-heap when a bounded min-heap is simpler here
- assuming the final output must be frequency-sorted when the problem does not require it
Worked Example 3: Course Schedule Feasibility
Problem Statement
Given numCourses and prerequisite pairs, return true if all courses can be finished.
Why This Example Matters
This example shows pattern recognition and explanation discipline. The real task is to notice that prerequisites form a directed graph and the question is asking whether a cycle exists.
Constraints or Assumptions
- courses are labeled from
0tonumCourses - 1 - prerequisite pair
[a, b]meansbmust be completed beforea - only a boolean answer is required
Brute-Force Approach
Repeatedly scan all prerequisites, remove any course that currently has no unmet prerequisite, and keep looping until progress stops.
That is clumsy and inefficient.
Better Approach
Model the courses as a directed graph and use Kahn's algorithm for topological sorting.
Why the Better Approach Works
If the graph is acyclic, at least one node has indegree 0, and repeated removal eventually processes every course. If a cycle exists, some nodes never drop to indegree 0.
Pragmatic Java Choice
Use an adjacency list, indegree array, and queue.
Java Solution
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
class CourseScheduleExample {
static boolean canFinish(int numCourses, int[][] prerequisites) {
List<Integer>[] graph = new ArrayList[numCourses];
for (int course = 0; course < numCourses; course++) {
graph[course] = new ArrayList<>();
}
int[] indegree = new int[numCourses];
for (int[] edge : prerequisites) {
int course = edge[0];
int prerequisite = edge[1];
graph[prerequisite].add(course);
indegree[course]++;
}
ArrayDeque<Integer> queue = new ArrayDeque<>();
for (int course = 0; course < numCourses; course++) {
if (indegree[course] == 0) {
queue.add(course);
}
}
int processed = 0;
while (!queue.isEmpty()) {
int course = queue.remove();
processed++;
for (int next : graph[course]) {
indegree[next]--;
if (indegree[next] == 0) {
queue.add(next);
}
}
}
return processed == numCourses;
}
}
Dry Run
Input: numCourses = 4, prerequisites [[1, 0], [2, 1], [3, 2]]
- indegree
0starts with course0 - processing
0frees1 - processing
1frees2 - processing
2frees3
All courses are processed, so the answer is true.
If the prerequisites formed a cycle, the queue would become empty early.
Time and Space Complexity
Repeated scan removal:
- Time: worse than
O(V + E)due to repeated rescans - Space: depends on the bookkeeping approach
Kahn's algorithm:
- Time:
O(V + E) - Space:
O(V + E)
Edge Cases
- no prerequisites
- self-dependency
- disconnected prerequisite graph
Common Mistakes
- reversing edge direction incorrectly
- forgetting to enqueue all zero-indegree nodes initially
- mistaking topological processing count for graph size without checking equality
4. Complexity and Decision Guide
This chapter is about choosing the right optimization path, not one fixed algorithm family.
- start with the simplest correct baseline so the bottleneck is visible
- let constraints rule out impossible complexities early
- choose the smallest correct data structure that eliminates the bottleneck
- keep the final implementation explainable in one or two clear observations
When to stay close to brute force:
- tiny constraints
- debugging the logic of a new problem type
- verifying an optimized idea against a trusted small-input baseline
When to optimize aggressively:
- quadratic or exponential time clearly violates constraints
- repeated queries, repeated states, or repeated comparisons dominate runtime
- a known earlier pattern directly targets the identified bottleneck
Recognition signals:
- repeated prefix or subarray work suggests prefix preprocessing or hashing
- top
kwording suggests heap or partial ordering - dependencies suggest DAG reasoning or cycle detection
- dynamic best/count/min/max over prefixes or states suggests DP
Signals not to force a technique:
- choosing a pattern because it is familiar rather than because it matches the bottleneck
- adding unnecessary abstractions under time pressure
- ignoring edge cases while chasing the optimal asymptotic bound
5. Edge Cases, Pitfalls, and Debugging
Common interview and contest bugs:
- misreading the problem statement and optimizing the wrong target
- choosing a pattern before verifying the brute-force reasoning
- off-by-one errors in boundaries, especially in prefixes and windows
- integer overflow in sums, products, or counts
- failing to test empty, singleton, and fully constrained cases
Short debugging checklist:
- restate the exact output requirement
- verify the baseline answer on a tiny hand-built input
- name the bottleneck before switching patterns
- test the final solution on one boundary case and one adversarial case
- be ready to explain why the chosen algorithm matches the constraints
6. Practice Problems
Easy
Title: Two Sum
Prompt: Find two numbers adding to a target.
Expected pattern or core idea: Baseline to hashing optimization and clear explanation.
Title: Valid Parentheses
Prompt: Decide whether brackets are balanced.
Expected pattern or core idea: Fast pattern recognition for stack usage.
Title: Best Time to Buy and Sell Stock
Prompt: Maximize profit from one transaction.
Expected pattern or core idea: Identify the bottleneck and reduce to a one-pass invariant.
Medium
Title: Longest Subarray with Sum k
Prompt: Return the longest subarray whose sum is exactly k.
Expected pattern or core idea: Constraint-aware choice of prefix sum plus hashing.
Title: Top K Frequent Elements
Prompt: Return the k most frequent values efficiently.
Expected pattern or core idea: Frequency counting plus heap or bucket choice.
Title: Course Schedule
Prompt: Decide whether all courses can be completed under prerequisites.
Expected pattern or core idea: Graph modeling and topological reasoning.
Hard
Title: Design a Weekly Revision Loop
Prompt: Build a study system that revisits mistakes and weak patterns deliberately.
Expected pattern or core idea: Long-term practice system rather than random volume.
Title: Mixed-Pattern Mock Interview Set
Prompt: Solve a small set where each problem must be classified before coding.
Expected pattern or core idea: Pattern-recognition checklist under time pressure.
Title: Explain an Optimized Solution End-to-End
Prompt: Present the observation, structure, correctness idea, and complexity for a hard problem.
Expected pattern or core idea: Solution communication as a first-class skill.
7. Short Recap
The core idea is that strong problem solving is a repeatable workflow: baseline, bottleneck, pattern, careful implementation, and clear explanation. The most important optimization insight is that constraints should drive the choice of pattern, not habit. The most important implementation warning is to keep correctness and edge cases visible even under time pressure. This prepares the next step after the roadmap: sustained deliberate practice using the patterns you now know.
8. Coverage Check
- 40.1 Brute force to optimal workflow - Covered
- 40.2 Pattern recognition checklist - Covered
- 40.3 Constraint-driven thinking - Covered
- 40.4 Writing bug-resistant Java code - Covered
- 40.5 Explaining solutions clearly - Covered
- 40.6 Building a long-term practice system - Covered
Coverage Summary: 6/6 official subtopics covered
Next: None. This is the final chapter of the roadmap.