Java DSA, Coding Patterns, and Design Patterns Tutorial

A Java-only learning path covering foundations, linear data structures, problem-solving patterns, and reusable design patterns with intuition, dry runs, and trade-off analysis.

1: Java Foundations for Problem Solving

Introduction and Context

Java problem solving is mostly about representing state clearly enough that the algorithm can stay simple. In Java, small choices have large effects: whether a value is primitive or reference-based, whether a string is rebuilt or appended, whether lookup is linear or hashed, and whether logic is packed into one giant method or organized into small reusable pieces.

This chapter builds the operational habits behind later algorithms. You learn how Java stores and mutates data, which standard containers keep specific operations cheap, how classes and interfaces organize behavior, and why debugging and input handling matter once problems become large. The recurring beginner failures here are off-by-one loops, accidental quadratic string building, wrong equality or comparator behavior, null-state mistakes, and choosing a collection that makes the critical operation slow.

Core Intuition and Mechanics

Think of Java problem solving as running a workshop where every tool has both a purpose and a cost model.

  • Variables and types define what state exists and what operations are legal.
  • Loops and conditions control how that state changes over time.
  • Arrays and strings give compact sequential storage, but their mutability rules are different.
  • Collections trade raw simplicity for fast lookup, queue behavior, or priority-based access.
  • Classes, interfaces, and comparators let you package behavior so larger solutions stay readable.

The practical question behind almost every beginner problem is the same: where should the state live, how will it change, and which operations must stay cheap? When those answers are clear, helper methods, custom classes, fast I/O, and debugging traces stop feeling like ceremony and start feeling like problem-solving tools.

A strong Java solution therefore has two layers. The first layer is mechanical correctness: correct indexes, safe mutation, valid equality and ordering rules, and no hidden overflow. The second layer is structure: code that makes the chosen state and operations obvious enough to extend, test, and debug.

Core Concepts and Subtopics

Concept Cluster: Core Syntax and Control Flow

Topics in this cluster:

  • Variables, data types, and operators
  • Conditions, loops, and methods
Definition

These are the absolute fundamentals of programming, the grammar of the language.

  • Variables: Named containers that store data. Think of them as labeled boxes where you can keep a value to use later.
  • Data Types: The classification that tells the computer what kind of data a variable can hold (e.g., a number, a piece of text, a true/false value).
  • Operators: Special symbols used to perform operations on variables and values. They include arithmetic (+, -, *, /), comparison (==, >), and logical (&&, ||) operators.
  • Conditions: Statements that allow your program to make decisions. They control whether a block of code runs based on whether a certain condition is true or false (e.g., if, else if, else).
  • Loops: Structures that repeat a block of code multiple times. They are essential for automating repetitive tasks (e.g., for, while).
  • Methods: Named, reusable blocks of code that perform a specific task. They are the building blocks of a well-organized program, allowing you to package up logic and call it whenever you need it.
Why It Matters

Think of these concepts as the foundational notes and scales in music. You can’t compose a symphony or even play a simple tune without mastering them first. In the same way, every single algorithm, data structure, and design pattern you will ever learn is expressed using these core components.

A weak foundation here makes everything else exponentially harder. If you’re constantly fighting with syntax—forgetting a semicolon, using the wrong loop, or struggling to define a method—you can't focus your mental energy on the real challenge: solving the actual problem.

Mastery of these fundamentals is what enables coding fluency. It’s the point where the language gets out of your way and you can begin to think directly about the logic and creativity of your solution. It's the difference between trying to remember how to spell words and actually writing a story.

How It Works
  • Static Typing: Java is a statically-typed language. This means you must declare the data type of a variable before you can use it (e.g., int count = 0;). This acts as a safety net, catching many potential errors at compile time and making the code's intent clearer.
  • Decision Making: Conditions use boolean expressions—statements that evaluate to either true or false—to direct the flow of your program. An if block runs only if its condition is true.
  • Repetition: Loops execute a block of code as long as their condition holds. A for loop is typically used when you know the number of repetitions in advance (e.g., iterating through an array), while a while loop is used when the repetition depends on a changing state (e.g., reading from a file until you reach the end).
  • Abstraction: Methods are your first and most important tool for abstraction. Instead of writing the same five lines of code in three different places, you can extract them into a method. This makes your code cleaner, easier to debug, and more maintainable.
Internal Mechanics
  • Value vs. Reference: This is one of the most crucial concepts in Java.

    • Primitive types (int, long, double, char, boolean, etc.) are the raw materials. When you assign a primitive to a variable, that variable holds the actual, literal value. Think of it like a small box holding the number 5.
    • Reference types (String, ArrayList, any Object) are more complex. The variable doesn't hold the object itself, but rather a pointer or memory address that tells the JVM where to find the object in a large area of memory called the heap. Think of it as a slip of paper with the address of a much larger box.
  • The == Trap: This distinction is the source of a classic beginner mistake.

    • For primitives, == does what you expect: it compares the actual values. 5 == 5 is true.
    • For objects, == compares the memory addresses—the information on the slip of paper. If you have two different ArrayList objects, == will be false even if they contain the exact same elements, because they live at different memory addresses.
    • To compare the actual contents of two objects, you must use the .equals() method (e.g., list1.equals(list2)). A well-behaved .equals() method, like the one for String and ArrayList, will check if the internal contents are the same.
Java Implementation Notes
  • Integer Overflow: Be mindful of the limits of int. If you are working with numbers that could exceed roughly 2 billion (e.g., summing up large populations, calculating milliseconds), use long to prevent silent overflow errors where the number wraps around to be negative.
  • Descriptive Method Names: A method's name is its primary documentation. calculateAverageScore() is infinitely better than processData() or doStuff().
  • DRY Principle (Don't Repeat Yourself): If you copy and paste a block of code, you've likely found an opportunity to create a method. Duplicated logic is a maintenance nightmare; fixing a bug in one place means you have to remember to fix it everywhere else.
Clean Code Rules
  • Meaningful Variable Names: Name variables for the role they play, not their data type. userCount is better than myInt. For loop counters, i is acceptable for short, generic loops, but rowIndex is better if the loop is traversing a grid.
  • Single Responsibility Principle for Methods: Each method should be responsible for one single, well-defined task. If your method description includes the word "and," it might be a sign that it's doing too much and should be split.
  • Prefer Early Returns: Instead of deeply nested if-else structures, use "guard clauses" to handle edge cases at the beginning of a method. This flattens the code and makes the "happy path" logic easier to read.
Mini Example & Dry Run

This example demonstrates a simple method with a clear name, parameters, and early returns (guard clauses) to handle different cases cleanly.

java
/**
 * Classifies an integer as "positive", "negative", or "zero".
 */
static String classifyNumber(int value) {
    // Guard clause for the positive case
    if (value > 0) {
        return "positive";
    }
    // Guard clause for the negative case
    if (value < 0) {
        return "negative";
    }
    // The only remaining case is zero
    return "zero";
}

Dry Run: How classifyNumber(0) Executes

  1. Call: The method classifyNumber is called with value = 0.
  2. First Check: The first if condition, value > 0, is checked. 0 > 0 is false, so the code inside this block is skipped.
  3. Second Check: The second if condition, value < 0, is checked. 0 < 0 is false, so this block is also skipped.
  4. Final Return: The method proceeds to the final line and returns the string "zero".

This structure is clean because it handles specific cases one by one and exits immediately, making the logic easy to follow.

Common Mistakes
  • Assignment vs. Comparison: Using a single equals sign (=), which is for assignment, inside an if condition instead of the double equals sign (==) for comparison. This is a classic error that most modern IDEs will warn you about, but it's crucial to understand the difference.
  • Infinite Loops: Forgetting to update the variable that controls the loop's exit condition. For example, in a while loop, if you forget to increment your counter, the condition will never become false and the loop will run forever, crashing your program.
  • The "God Method": Writing one enormous main method that does everything. This is a terrible habit. Good code is like a well-organized workshop, with a specific tool for each job. Break your logic down into smaller, more manageable helper methods.
  • Integer Overflow: Multiplying two int variables and expecting the result to fit in an int, when the product could be large enough to require a long. For example, int big = 2_000_000_000 * 2; will not give you 4 billion; it will overflow and give you a seemingly random negative number.
  • Floating-Point Inaccuracy: Using == to compare double or float values. Because of how these numbers are stored, small precision errors can accumulate. 0.1 + 0.2 == 0.3 is famously false in many languages. Instead, check if the absolute difference is smaller than a tiny threshold (epsilon).
Debugging Tips
  • "Rubber Duck" Your Code: Explain your code, line by line, to an imaginary person (or a rubber duck). You'll be amazed at how often you spot the logical flaw yourself just by verbalizing it.
  • Trace Your Loop with Print Statements: Inside a loop, print the loop counter and any key variables that change with each iteration (System.out.println("i=" + i + ", state=" + myVar);). This is a low-tech but incredibly effective way to see exactly how the state is evolving.
  • Use Your Debugger: A debugger is one of the fastest ways to locate state bugs. Set a breakpoint to pause execution, step through the code line by line, inspect variable values, and confirm exactly where the logic diverges from your expectation.
  • Isolate Conditions: If a complex if statement like if (a && !b || c) isn't working, break it down. Create temporary boolean variables for each part and print their values to see which one isn't evaluating as you expect.
Practical Note

Weak foundations show up quickly in any real coding task. If simple loops are error-prone, helper methods are missing, or types and collections are chosen carelessly, larger algorithmic ideas become much harder to express correctly.

A candidate who writes a classifyNumber method with clean guard clauses is demonstrating a level of code maturity that is far more impressive than someone who just nests a messy if-else block, even if both produce the correct output. Show them you think about readability and maintainability.

Deeper Note

Expert engineers don't just write code that works; they write code that clearly communicates its intent. The way they structure conditions and loops reveals the underlying state machine of their logic. This makes the code not only easier for others to read but also safer to optimize or refactor later.

Complexity analysis, invariants, state transitions, recursion base cases, functional programming.

Concept Cluster: Arrays and Strings

Topics in this cluster:

  • Arrays and strings in Java
  • Arrays, strings, and collections used in pattern problems
Definition
  • An Array is a fundamental data structure that stores a collection of elements of the same type in a contiguous block of memory. Its size is fixed when it is created. Each element has a unique numerical index, starting from 0, which allows for direct access.
  • A String in Java is an object that represents a sequence of characters. Unlike in some other languages, Java strings are immutable, meaning once a string object is created, its contents cannot be changed.
Why It Matters

Arrays and strings are the bread and butter of programming and coding interviews. They are the default containers for data. Think of them as the equivalent of lists and sentences in human language—they are how we organize sequential information.

A vast number of algorithmic problems, from simple to complex, are based on manipulating or analyzing data stored in these two structures. Whether you're sorting data, searching for a pattern, or calculating statistics, you will almost certainly be doing it over an array or a string.

A solid understanding of their properties—like an array's fixed size and a string's immutability—is not just academic. It's practical knowledge that prevents common bugs and performance bottlenecks. Mastering them is the first major step toward tackling more advanced data structures and algorithms, as many of them (like stacks or queues) are often built using arrays internally.

How It Works
  • Arrays: The power of an array lies in its constant-time indexed access. Because the computer knows the memory address of the start of the array and the size of each element, it can instantly calculate the exact location of any element arr[i]. This makes reading from any position extremely fast. However, its fixed size means you must know how much space you need upfront, and adding or removing elements from the middle is inefficient as it requires shifting subsequent elements.
  • Strings: The immutability of strings is a crucial concept. When you "modify" a string (e.g., by concatenating another string to it), you are not changing the original string. Instead, you are creating a new string object that contains the modified sequence. Doing this repeatedly in a loop is highly inefficient because it generates a lot of temporary, discarded objects. For efficient string building, Java provides the StringBuilder class.
Internal Mechanics
  • Array Access: An array in memory is like a city block where all the houses are the same size and numbered consecutively. The operation arr[i] is O(1) because it's a simple arithmetic calculation: memory_address = start_address + (index * element_size). The computer doesn't need to search for the element; it can jump directly to its location. This is why array lookups are lightning-fast.

  • String Immutability & The String Pool: When you write String s = "hello";, Java is smart. It looks in a special memory area called the String Pool. If "hello" is already there, s just points to the existing string. If not, it creates it, places it in the pool, and then s points to it.
    Now, if you write s = s + " world";, the original "hello" string is not touched. Instead, a completely new string, "hello world", is created in memory. The variable s is then updated to point to this new string. The old "hello" string (if no other variable is pointing to it) becomes garbage, waiting to be cleaned up. This design choice makes strings inherently thread-safe and allows for the memory-saving optimizations of the String Pool, but it's also why repeated concatenation with + is slow—it creates a lot of temporary garbage.

  • String to Char Array: Converting a string to a character array using text.toCharArray() is a powerful and common technique. It's like taking a read-only book and transcribing it onto a whiteboard. The char[] is your mutable copy. This allows you to perform in-place algorithms, like reversing the sequence or swapping characters, which is impossible with an immutable String. After you're done, you can convert it back to a string with new String(charArray).

Java Implementation Notes
  • Bounds Checking: Always be vigilant about array indices. The valid range is from 0 to length - 1. Accessing arr[arr.length] is one of the most common runtime errors (ArrayIndexOutOfBoundsException).
  • Choosing the Right Loop:
    • Use an enhanced for-loop (for (int value : values)) when you only need to iterate through the elements and don't care about their positions. It's cleaner and less error-prone.
    • Use a traditional indexed for-loop (for (int i = 0; i < ...) ) when you need the index itself, such as for making comparisons with other elements, modifying the array in-place, or traversing backwards.
Clean Code Rules
  • Separate Traversal Logic: A loop that iterates through an array should have a single, clear purpose. Avoid mixing complex business logic, I/O operations, and data transformations within the same loop. Extract them into helper methods.
  • Use StringBuilder for Construction: If you are building a string inside a loop, always use StringBuilder. The intent is clearer ("I am building a string") and the performance is vastly superior to repeated + concatenation.
  • Name Indices Meaningfully: If an index has a specific role, give it a descriptive name. For example, in a two-pointer algorithm, left and right are much better than i and j.
Mini Example & Dry Run
java
/**
 * Calculates the sum of all values in an integer array.
 * This demonstrates a simple, clean traversal using an enhanced for-loop.
 */
static int sumArray(int[] values) {
    // A guard clause for null or empty arrays prevents errors.
    if (values == null || values.length == 0) {
        return 0;
    }

    int sum = 0;
    // Use an enhanced for-loop because we only need the value, not the index.
    // It's cleaner and less prone to off-by-one errors.
    for (int value : values) {
        sum += value;
    }
    return sum;
}

Dry Run: How sumArray(new int[]{10, 20, 30}) Executes

  1. Call: The method is called with an array [10, 20, 30].
  2. Initialization: A variable sum is initialized to 0.
  3. Loop Start: The enhanced for-loop begins.
    • Iteration 1: value is assigned the first element, 10. sum becomes 0 + 10 = 10.
    • Iteration 2: value is assigned the second element, 20. sum becomes 10 + 20 = 30.
    • Iteration 3: value is assigned the third element, 30. sum becomes 30 + 30 = 60.
  4. Loop End: The loop finishes as there are no more elements in the array.
  5. Return: The method returns the final sum, which is 60.
Common Mistakes
  • Off-by-One Errors: The classic fencepost problem. Starting or ending a loop at the wrong index (e.g., i <= values.length instead of i < values.length). This is the most frequent bug when working with arrays. Always double-check your < vs. <= and your 0 vs. 1.
  • Treating Strings as Mutable: Trying to change a character in a string directly (e.g., myString[i] = 'a'). This is impossible in Java. You must create a char[] array or use StringBuilder if you need to modify the contents.
  • Forgetting Edge Cases: Not considering what happens if the input array or string is null or empty (length == 0). A robust method always checks for these cases at the beginning to avoid a NullPointerException or other unexpected behavior.
  • Inefficient String Concatenation: Using the + operator to build a string inside a loop. This creates a new String object on every single iteration, which is incredibly wasteful. StringBuilder is the correct tool for this job.
Debugging Tips
  • Print Index and Value: When debugging a loop, don't just print the value; print the index alongside it (System.out.println("i=" + i + ", value=" + arr[i])). This helps you spot when your logic is off by one or if you're accessing the wrong element.
  • Visualize the Array: For small examples, draw the array on paper. Cross out elements, draw arrows for your pointers (left, right), and manually trace what your code is doing. This physical act can make logical errors obvious.
  • Test Boundary Cases Explicitly: Don't just hope your code works for edge cases. Write specific tests for:
    • A null array/string.
    • An empty array/string.
    • An array/string with one element.
    • An array where all elements are the same.
    • A case where the element you're looking for is at the very beginning or very end.
Practical Note

Many array problems that seem "hard" are actually just about carefully managing state during a linear scan. An interviewer will look for strong habits:

  1. Clarifying Questions: Do you ask about the range of values? Can the array be empty? Are the elements sorted?
  2. Defensive Coding: Do you immediately write a check for null or empty inputs?
  3. Clean Loops: Do you use the correct loop boundaries without fumbling?
  4. Edge Case Handling: Do you talk through how your algorithm would handle an array of size 1 or an array where no solution exists?

Demonstrating these habits shows you are a careful, methodical programmer, which is often more important than just getting the "trick" to the problem.

Deeper Note

Mastering array and string traversals is the gateway to more advanced coding patterns. The Two Pointers and Sliding Window techniques, which are fundamental to solving a huge class of problems, are essentially just highly disciplined ways of moving indices through an array or string.

Prefix sums, two pointers, sliding window, string matching algorithms (KMP), dynamic programming on strings.

Concept Cluster: Core Collections Toolbox

Topics in this cluster:

  • ArrayList, HashMap, and HashSet basics
  • HashMap, HashSet, ArrayDeque, and PriorityQueue workflows
Definition

Collections are a set of powerful, ready-to-use data structures provided by the Java standard library. They are engineered for common programming tasks, offering efficient and reliable ways to store and manage groups of objects. Think of them as specialized containers, each designed for a different kind of job.

  • ArrayList: A dynamic, resizable array. It grows automatically as you add more items, combining the fast indexed access of an array with greater flexibility.
  • HashMap: A high-speed lookup table that stores key-value pairs. It's like a dictionary where you can find a definition (value) almost instantly if you know the word (key).
  • HashSet: A container for storing unique items. It enforces uniqueness, automatically discarding any duplicates, and provides a very fast way to check if an item is already present.
  • ArrayDeque: A double-ended queue that lets you add or remove items from both the front and the back efficiently. It's a versatile tool commonly used to implement stacks (Last-In, First-Out) and queues (First-In, First-Out).
  • PriorityQueue: A specialized queue that keeps items organized based on their natural order or a custom-defined priority. It always provides instant access to the "most important" item, making it ideal for tasks like scheduling or finding the top k elements.
Why It Matters

If arrays are like a fixed-length rack, collections are like a set of smart, specialized containers. You wouldn't store soup in a filing cabinet or screws in a paper bag. In the same way, your choice of data structure is a critical decision that shapes your entire solution.

Selecting the right collection can transform a slow, convoluted algorithm into one that is fast, elegant, and easy to understand. For example:

  • Trying to find if an item exists in an ArrayList can be slow (O(n)). Doing the same with a HashSet is incredibly fast (O(1)).
  • Trying to manage a waiting line with a simple array would be a nightmare of shifting elements. An ArrayDeque (as a queue) makes it trivial.

Mastery of these core collections is non-negotiable for any serious Java programmer. They are the vocabulary you use to describe the state and logic of your program. Using the right one not only makes your code perform better but also makes your intent clearer to anyone reading it. They form the backbone of countless algorithms and system designs.

How It Works

The key is to match the problem's requirements to the strengths of a collection:

  • Use ArrayList when you need a dynamic list of items and will frequently access them by their position (index). It's perfect for storing a sequence of elements when you don't know the exact count beforehand.
  • Use HashMap when you need to associate data together, like mapping usernames to user profiles or counting the frequency of characters in a string. It's all about fast lookups by a unique identifier.
  • Use HashSet when your main concern is checking for the existence of an item or maintaining a collection of unique elements. It's the best tool for deduplication and "seen before" checks.
  • Use ArrayDeque for processing items in a specific order, such as the structured exploration of a maze (queue for BFS) or managing function calls in a recursive algorithm (stack for DFS).
  • Use PriorityQueue when you constantly need to retrieve the item with the highest (or lowest) priority. This is common in scheduling algorithms, pathfinding (like Dijkstra's), and finding the "Top K" items from a large dataset.
Internal Mechanics
  • Hash-Based Collections (HashMap, HashSet): Imagine a large library with 100 numbered shelves. To store a book, you don't search for a spot; you look at the book's title, calculate a special number (its hashCode()), and that number tells you exactly which shelf to put it on. This is how HashMap and HashSet work. An object's hashCode() determines which "bucket" (shelf) it belongs to in an internal array. This allows for average-case constant-time O(1) performance for adds, removes, and lookups. The trade-off? In the rare worst-case scenario where many different books all hash to the same shelf number (a "hash collision"), you have to search through that one crowded shelf, and performance can degrade to O(n).

  • ArrayList: This is simply an array that knows how to grow. It starts with a certain capacity. When it runs out of space, it doesn't just add one more slot. It performs a "resize" operation: it creates a brand new, larger array (typically 1.5x the original size) and painstakingly copies all the elements from the old array to the new one. This is why appending is called amortized O(1). Most of the time, adding an element is a fast O(1) operation. But every so often, you'll have to pay the O(n) cost of a resize. Over many additions, the average cost is still constant.

  • PriorityQueue: This is implemented using a binary heap, which is a clever tree-like structure that maintains a specific ordering property. For a min-heap (the default), every parent node is smaller than its children. This guarantees that the smallest element in the entire structure is always at the very top (the root), ready for O(1) access via peek(). When you add or remove an element, the heap performs a few swaps to restore this property, which takes O(log n) time. It's like a self-organizing tournament bracket where the winner is always at the top.

  • ArrayDeque: This is implemented using a resizable circular array. Think of an array bent into a circle. It maintains pointers to the "head" and "tail" of the queue. To add to the front, it just moves the head pointer one step counter-clockwise. To add to the back, it moves the tail pointer one step clockwise. This ingenious design allows it to add or remove elements from either end in O(1) time without ever needing to shift elements, which would be an O(n) operation in a standard array.

Java Implementation Notes
  • Frequency Counting: map.getOrDefault(key, 0) is your best friend. It simplifies the code for counting items by safely handling cases where a key hasn't been seen yet.
  • Detecting Duplicates: The set.add(x) method returns a boolean: true if the item was added successfully (it was new), and false if the item was already in the set. This is a clean way to detect the first time you encounter an element.
  • Max-Heap Behavior: By default, PriorityQueue is a min-heap. To make it a max-heap, you can provide a reverse-order comparator: new PriorityQueue<>(Comparator.reverseOrder()).
  • Interfaces vs. Implementations: It's good practice to declare variables using the interface type (e.g., List<String> list = new ArrayList<>(); or Map<String, Integer> map = new HashMap<>();). This makes your code more flexible if you ever need to change the underlying implementation.
Clean Code Rules
  • Choose for Intent: Select the collection that best communicates your algorithm's intent. If you need a stack, use ArrayDeque and its stack methods (push/pop) to make that intent clear.
  • Encapsulate State: Keep the logic that modifies a collection close to the collection itself. This makes it easier to reason about state changes and prevent bugs.
  • Avoid Hidden Side Effects: A method called getStudents() should not secretly modify the student list unless that is its explicit, well-documented purpose (e.g., getAndSortStudents()).
Mini Example & Dry Run
java
/**
 * Builds a map to count the frequency of each character in a string.
 * This is a classic use case for HashMap.
 */
static Map<Character, Integer> buildFrequencyMap(String text) {
    // A guard clause for null or empty strings is good practice.
    if (text == null || text.isEmpty()) {
        return new HashMap<>(); // Return an empty map.
    }

    // We declare the map using its interface (Map) but instantiate the concrete class (HashMap).
    // This is a flexible design pattern.
    Map<Character, Integer> frequencyMap = new HashMap<>();
    
    // We convert the string to a character array to iterate through it.
    for (char ch : text.toCharArray()) {
        // The getOrDefault method is perfect for frequency counting.
        // 1. It tries to get the current count for the character `ch`.
        // 2. If `ch` is not in the map yet, it uses the default value `0`.
        // 3. It then adds 1 to that value and puts the result back into the map.
        frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
    }
    
    return frequencyMap;
}

Dry Run: How buildFrequencyMap("hello") Executes

  1. Call: The method is called with the string "hello".
  2. Initialization: An empty HashMap named frequencyMap is created. frequencyMap is {}.
  3. Loop Start: The code begins to loop through the characters of "hello".
    • Iteration 1 (h): getOrDefault('h', 0) returns 0. The code calculates 0 + 1. put('h', 1) is called. frequencyMap is now {'h'=1}.
    • Iteration 2 (e): getOrDefault('e', 0) returns 0. The code calculates 0 + 1. put('e', 1) is called. frequencyMap is now {'h'=1, 'e'=1}.
    • Iteration 3 (l): getOrDefault('l', 0) returns 0. The code calculates 0 + 1. put('l', 1) is called. frequencyMap is now {'h'=1, 'e'=1, 'l'=1}.
    • Iteration 4 (l): getOrDefault('l', 0) returns 1 (the current count). The code calculates 1 + 1. put('l', 2) is called. frequencyMap is now {'h'=1, 'e'=1, 'l'=2}.
    • Iteration 5 (o): getOrDefault('o', 0) returns 0. The code calculates 0 + 1. put('o', 1) is called. frequencyMap is now {'h'=1, 'e'=1, 'l'=2, 'o'=1}.
  4. Loop End: The loop finishes.
  5. Return: The method returns the final frequencyMap: {'h'=1, 'e'=1, 'l'=2, 'o'=1}.
Common Mistakes
  • Assuming Order in HashMap: A standard HashMap makes absolutely no guarantee about iteration order. It might change between Java versions or even between runs. If you need predictable order, use LinkedHashMap (which remembers insertion order) or TreeMap (which keeps keys sorted).
  • Treating PriorityQueue as a Sorted List: A PriorityQueue is not a sorted list; it's a heap. It only guarantees that the head element is the minimum (or maximum). The rest of the elements are only partially ordered. If you iterate over it with a for-each loop, you will get elements in a seemingly random order. To get a sorted sequence, you must repeatedly call poll().
  • Using Legacy Stack: The java.util.Stack class is a synchronized, legacy collection from Java 1.0. It's slower than its modern replacement. For any stack-like behavior (LIFO), you should always prefer using the ArrayDeque class.
  • Modifying a Collection While Iterating: Using a standard for-each loop to add or remove items from a collection will cause a ConcurrentModificationException. If you need to modify a collection during traversal, you must use an Iterator and call its remove() method.
  • Forgetting to Implement hashCode() and equals(): If you put custom objects into a HashMap or HashSet, you must provide a correct implementation for both hashCode() and equals(). If you don't, the collection won't be able to find your objects correctly, leading to bizarre and frustrating bugs.
Debugging Tips
  • Print the Whole Collection: For small test cases, print the entire collection after each significant operation (add, remove, put). This gives you a step-by-step snapshot of how its state is changing. System.out.println("Map state: " + myMap);
  • Use the Debugger's Data Views: Modern IDEs have powerful debugger views that let you inspect the live contents of any collection while your program is paused. You can expand maps, view lists, and see the internal state of your data structures, which is far more efficient than adding print statements everywhere.
  • Verify Ordering Assumptions: If your algorithm depends on a certain order, add assertions or print statements to confirm that the collection is behaving as you expect. For example, print the peek() of a PriorityQueue at each step to ensure the minimum element is always what you think it is.
Practical Note

A strong candidate doesn't just say, "I'll use a HashMap." They explain why by connecting it to the problem's constraints:

  • "I'll use a HashMap because the problem requires fast lookups to count frequencies, and a HashMap provides average O(1) time for insertions and retrievals. This is more efficient than a linear scan."
  • "A HashSet is perfect here to track which nodes we've already visited, because it gives us an O(1) 'contains' check, preventing us from getting stuck in cycles."
  • "To find the top K largest elements, I'll use a PriorityQueue as a min-heap of size K. This is more memory-efficient than sorting the entire input, as it only requires O(K) space."

This level of justification shows you aren't just reciting facts; you're making deliberate, well-reasoned design choices.

Deeper Note

While Big-O complexity is crucial, real-world performance is also affected by factors like memory layout, cache-friendliness, and the overhead of object creation. For instance, an ArrayList is often faster for iteration than a LinkedList because its elements are stored contiguously in memory, which is better for modern CPUs.

Frequency counting, heaps, Breadth-First Search (BFS) queues, monotonic structures, graph traversal.

Concept Cluster: Object-Oriented Building Blocks

Topics in this cluster:

  • Classes and objects
  • Interfaces and abstract classes
  • Classes, objects, and comparators
Definition

Object-Oriented Programming (OOP) is a way of thinking about and organizing code. Instead of writing long scripts of instructions, you create self-contained "objects" that model parts of the problem.

  • A Class is a blueprint or template for creating objects. It defines a set of properties (fields) and behaviors (methods) that all objects of that type will have. For example, a Student class could define that every student has a name and a score.
  • An Object is a concrete instance created from a class blueprint. If Student is the blueprint, then a specific student like "Alice" with a score of 95 is an object. You can create many objects from a single class.
  • An Interface is a contract. It defines a set of methods that a class must implement, but it doesn't provide any of the implementation details. It specifies what a class should be able to do, not how it does it. For example, an Sortable interface might require a compareWith() method.
  • An Abstract Class is a hybrid between a class and an interface. It's a blueprint that provides some default implementation (shared code) but leaves other parts as "abstract" for its subclasses to define. It's a way to share common behavior while still enforcing a contract.
  • A Comparator is a specialized object that defines a custom ordering for another type of object. It's a set of instructions for how to sort objects, which is essential when the default order isn't sufficient.
Why It Matters

Even in algorithm-focused problems, organizing data and logic into well-defined objects reduces tangled conditionals and duplicated state handling. Clear object boundaries make code easier to test, debug, and extend when the data model becomes more complex.

How It Works
  • Use Classes to model real-world or conceptual entities from your problem domain. If you're dealing with Students, Tasks, Intervals, or GraphNodes, a class is the natural way to bundle their data and related functionality together.
  • Use Interfaces when you want to define a common capability that can be shared by different, unrelated classes. For example, List, Set, and Queue are all different, but they all share the Collection interface's contract.
  • Use Abstract Classes when you have a group of related classes that share a significant amount of code. You can put the shared code in the abstract class and have the subclasses provide only the unique parts.
  • Use Comparators whenever you need to sort a collection of objects based on rules other than their natural order. This is extremely common for leaderboards, custom rankings, and priority queues.
Internal Mechanics
  • Sorting with Comparators: The Collections.sort(list, comparator) method (or the more modern list.sort(comparator)) uses the provided comparator's compare(o1, o2) method to determine the relative order of elements. This method must return a negative integer, zero, or a positive integer if o1 is less than, equal to, or greater than o2, respectively.
  • Comparator Contract: A valid comparator must be transitive. This means if A > B and B > C, then A must be greater than C. If this rule is violated, sorting behavior becomes unpredictable and may even lead to exceptions.
Java Implementation Notes
  • Immutability: For simple data-holding classes (like Student or Point), prefer making fields final. This makes the objects immutable (their state cannot change after creation), which simplifies reasoning and makes them safer to use in collections.
  • Comparator Chaining: Java's Comparator interface provides powerful chaining methods like thenComparing() that make it easy to build complex, multi-level sorting logic in a readable way.
Clean Code Rules
  • Single Responsibility: A class should have one primary responsibility. A Student class should represent student data; it shouldn't also be responsible for reading student data from a file and writing it to a database.
  • Composition Over Inheritance: This is a famous design principle. Before using inheritance ("is-a" relationship), consider if you can achieve the same goal by having one class contain an instance of another ("has-a" relationship). Composition is often more flexible and less brittle.
  • Meaningful Comparator Names: Name your comparators based on the business logic they represent. BY_SCORE_DESC_THEN_NAME_ASC is far more descriptive and less error-prone than a generic name like myComp1.
Mini Example
java
// A simple, immutable class to model a Student.
static class Student {
    final String name;
    final int score;

    Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

// A descriptive, chained comparator for sorting students.
// Sorts by score descending, then by name ascending as a tie-breaker.
static final Comparator<Student> BY_SCORE_DESC_THEN_NAME =
        Comparator.comparingInt((Student s) -> s.score).reversed() // Primary sort: score descending
                .thenComparing(s -> s.name);                      // Secondary sort: name ascending
Common Mistakes
  • "God Objects": Creating one massive class that tries to do everything, mixing data storage, business logic, and I/O.
  • Violating the Comparator Contract: Writing a comparator where the logic isn't transitive, leading to unpredictable sorting.
  • Inheritance for Code Reuse Only: Using inheritance just to share a few helper methods, when a separate utility class or composition would be a cleaner design.
  • Mutable Data Classes: Creating simple data objects with public setters, which can lead to their state being changed unexpectedly in different parts of the program.
Debugging Tips
  • Test Comparators in Isolation: When sorting doesn't work, create a tiny list of 3-4 items and sort it. Print the result and manually verify if it matches the expected order. This helps isolate bugs in the comparator logic.
  • Test equals() and hashCode() Together: If you override the equals() method to define custom equality, you must also override hashCode() to be consistent. HashMap and HashSet rely on this contract.
Practical Note

In an interview, creating a small, clean class to model the data (e.g., a Pair or Point class) shows engineering maturity beyond just solving the algorithm. It signals that you think about structure, readability, and maintainability, not just getting to the right answer.

Deeper Note

Well-designed domain objects are the foundation of many advanced design patterns. A Student object might start as a simple data holder, but in a larger system, it could be managed by a Repository, transformed by a Factory, or decorated with additional behaviors. Getting the simple model right makes these advanced patterns easier to apply later.

Design patterns (Strategy, Factory, Decorator), clean architecture, repository objects, comparator-based heaps.

Concept Cluster: Reusable Templates and Safe Iteration

Topics in this cluster:

  • Reusable loop templates and index-safe coding habits
  • Sorting, comparators, and helper classes in Java
Definition

Reusable templates are reliable, battle-tested code skeletons for common, recurring tasks. Think of them as blueprints for operations like traversing a list, counting items, sorting data, or parsing input. Index-safe coding is the practice of writing loops and array-access code in a way that systematically prevents common errors like going out of bounds.

Why It Matters

Programming is as much about managing complexity as it is about writing code. When you're solving a problem under pressure, your brainpower is a finite resource. Reusable templates free up mental energy. Instead of reinventing the basic mechanics of a for loop for the hundredth time, you can focus on the unique logic of the problem at hand. This dramatically reduces the chance of introducing subtle bugs (like off-by-one errors) and allows you to write correct code faster and more confidently.

How It Works

The goal is not to memorize dozens of random code snippets. The real skill is to recognize that many problems are built from a few fundamental patterns. Once you internalize these patterns, they become second nature.

Common structural patterns include:

  • Forward Scan: The classic for (int i = 0; i < n; i++). Used for most left-to-right traversals.
  • Backward Scan: for (int i = n - 1; i >= 0; i--). Essential for problems where processing from the end is more natural.
  • Frequency Map Construction: A standard loop to populate a HashMap with counts.
  • Comparator-Based Sorting: The pattern of creating a copy of a list and sorting it with a custom Comparator.
  • Test Case Processing: A while loop for competitive programming that reads the number of test cases and calls a solve() method for each one.
Internal Mechanics
  • Index-Safe Code: This practice is about being deliberate with loop boundaries. Always ask: What is the first valid index? What is the last valid index? The condition i < arr.length is safe because the last valid index is arr.length - 1. The condition i <= arr.length is a classic off-by-one error waiting to happen.
  • Helper Classes and Methods: Using helpers like Comparator.comparingInt() or extracting logic into a small method is part of this philosophy. These helpers are pre-built, tested templates that reduce boilerplate, making your code both cleaner and more correct.
Java Implementation Notes

These loop structures should become automatic.

java
// The standard, index-safe forward scan.
// It correctly handles arrays of any size, including empty ones.
for (int i = 0; i < arr.length; i++) {
    // Process arr[i]
}

// The standard, index-safe backward scan.
// Starts at the last valid index and stops at index 0.
for (int i = arr.length - 1; i >= 0; i--) {
    // Process arr[i]
}
Clean Code Rules
  • Embrace Proven Patterns: Don't improvise loop boundaries unless the problem absolutely requires a non-standard traversal. Stick to the templates that are known to be correct.
  • Explicitly Copy for Safety: If a method receives a list but shouldn't modify it, the first step should be to create an explicit copy. Name it copy to make your intent clear to other developers. This prevents accidental "side effect" mutations.
  • Extract, Don't Repeat: If you find yourself writing the exact same loop structure in two different places, extract it into a private helper method. A short, well-named method like findFirstNegative(values) is much clearer than a repeated for loop.
Mini Example

This template demonstrates creating a sorted copy of a list, a very common and reusable pattern. It's safe because it doesn't alter the original data.

java
/**
 * Returns a new list containing the elements of the original list,
 * sorted in natural order. The original list is not modified.
 */
static List<Integer> sortedCopy(List<Integer> values) {
    // 1. Create an explicit, safe copy.
    List<Integer> copy = new ArrayList<>(values);
    
    // 2. Sort the copy using a standard, reliable method.
    copy.sort(Comparator.naturalOrder());
    
    // 3. Return the result.
    return copy;
}
Common Mistakes
  • Off-by-One Errors: Using <= instead of < in a forward loop, or > instead of >= in a backward loop.
  • Accidental Mutation: Sorting an input list in-place when the caller of the method expected the original list to remain unchanged.
  • Incorrect Comparator Logic: Applying the wrong sorting order (e.g., ascending instead of descending) or mixing up the fields in a multi-level sort.
  • Reinventing the Wheel: Writing a custom sorting algorithm when list.sort() would be simpler, faster, and more reliable.
Debugging Tips
  • State the Invariant: Before you even write a loop, say in plain English what should be true at the start and end of each iteration. This is called a "loop invariant" and it helps clarify your logic.
  • Verify In-Place vs. Copy: Double-check the problem requirements. Does it ask you to modify the input "in-place," or should you return a new, modified version? This is a common source of failed test cases.
Practical Note

Using standard, safe templates during an interview is a strong positive signal. It shows that you are a disciplined coder who values correctness and clarity. It makes you appear faster and more confident because you're not fumbling with the basics.

Deeper Note

Many advanced algorithms are simply clever combinations of these basic templates. A binary search is a disciplined loop over a sorted range. A sliding window is just two pointers moving through an array according to specific rules. Mastering the simple templates is the first step to mastering the complex algorithms.

Two pointers, binary search templates, DFS/BFS traversal templates, sliding window.

Concept Cluster: Fast I/O and Debugging Discipline

Topics in this cluster:

  • Fast input/output and a reusable coding template
  • Fast input/output and a contest-ready Java template
  • Debugging with traces, assertions, and dry runs
Definition
  • Fast I/O: The practice of reading input and writing output as efficiently as possible. This is critical when dealing with very large amounts of data, where standard I/O methods can be too slow and cause a correct algorithm to time out.
  • Reusable Template: A standardized, pre-written code structure that you can use as a starting point for solving problems. It typically includes boilerplate code for fast I/O, test case handling, and a clean separation of concerns, allowing you to focus immediately on the core logic.
  • Debugging Discipline: A systematic and professional approach to finding and fixing bugs. It's the difference between randomly changing code and hoping for the best, versus methodically tracing program state, validating your assumptions, and logically narrowing down the source of an error.
Why It Matters

In the world of competitive programming and technical interviews, a correct algorithm is only half the battle.

  1. Performance: If your solution is too slow at reading the input, it might fail a test case before your brilliant algorithm even gets a chance to run. Fast I/O is a prerequisite for success on problems with large datasets.
  2. Speed and Reliability: A good template saves you precious minutes and reduces the risk of making silly mistakes in the setup phase. It's about building a reliable, efficient workflow.
  3. Effectiveness: Sloppy debugging is a massive time sink. A disciplined approach helps you find the root cause of a bug quickly and confidently, which is a skill highly valued in any professional engineering environment.
How It Works
  • Fast I/O: The standard Scanner class in Java is convenient but has significant overhead because it does a lot of complex parsing. For speed, the common practice is to use BufferedReader (for text) or BufferedInputStream (for bytes) to read large chunks of data from the input stream into a memory buffer at once. You then parse this buffered data manually (e.g., using String.split() or Integer.parseInt()), which is much faster than Scanner's token-by-token processing. For output, collecting all results in a StringBuilder and printing everything in a single operation at the end is far more efficient than making many separate System.out.println() calls.
  • Debugging Discipline:
    • Dry Runs: Before writing a single line of code, take a small example and trace it on paper or a whiteboard. Manually track the state of your variables through each step of the algorithm. This often reveals logical flaws before they ever become bugs.
    • Traces (Debug Prints): Strategically insert print statements to see the state of key variables at critical points in your code (e.g., inside a loop or after a state change).
    • Assertions: Use Java's assert keyword to programmatically check your assumptions. For example, assert count >= 0;. If the condition is false, the program will crash with an error, immediately pointing you to the broken invariant.
Internal Mechanics
  • Buffering: BufferedReader and BufferedInputStream work by minimizing the number of expensive system calls to the operating system. Instead of asking for one byte or character at a time, they ask for a large block (e.g., 8KB), which is much more efficient.
  • Assertions: Assertions are disabled by default. You must enable them with the -ea (enable assertions) flag when running your Java program (e.g., java -ea MyProgram). This means they have zero performance cost in production code but are a powerful safety net during development and testing.
Java Implementation Notes

A good reusable template for competitive programming often includes:

  • A custom FastScanner class that wraps BufferedReader and StringTokenizer for efficient input parsing.
  • A main method that handles test case loops.
  • A dedicated solve() method where the core logic for a single test case resides.
  • A StringBuilder for accumulating output.
  • A collection of common helper methods (e.g., for math operations like GCD or modular exponentiation).
Clean Code Rules
  • Separate Concerns: Your template should enforce a clean separation between input/parsing logic, the core business logic of your algorithm, and output formatting. This makes the code much easier to read, debug, and reuse.
  • Debug Utilities: Your debugging tools (like a debug() print method) should be designed so they can be easily disabled for submission, either with a global boolean flag or by commenting out a single line.
  • Don't Over-Abstract: A contest template's purpose is to speed you up. If it's so complex and abstract that it's hard to understand or use, it has failed. Keep it simple and practical.
Mini Example

A simple but effective debug tracing method.

java
// A global flag to easily turn debugging on or off.
static final boolean DEBUG_MODE = true;

static void debug(String label, Object value) {
    if (DEBUG_MODE) {
        // Using System.err to separate debug output from the actual solution output.
        System.err.println(label + " = " + String.valueOf(value));
    }
}

// Usage in your code:
// debug("Current index i", i);
// debug("Current map state", frequencyMap);
Common Mistakes
  • Mixing I/O Styles: Using Scanner for some inputs and BufferedReader for others, leading to confusing and unpredictable performance.
  • Printing Inside Hot Loops: Calling System.out.println() inside a loop that runs millions of times is a classic performance killer.
  • Guess-and-Check Debugging: Randomly changing code without a clear hypothesis about the bug. This is slow, frustrating, and often introduces new bugs.
  • Forgetting to Enable Assertions: Writing assert statements but forgetting to run the code with the -ea flag, making them ineffective.
Debugging Tips
  • Start with a Dry Run: Always. It's the highest-value, lowest-effort debugging technique.
  • Use Assertions for Invariants: Assertions are perfect for checking conditions that must always be true if your logic is correct (e.g., a pointer should never be null, an index must be within bounds).
  • Find the Smallest Failing Case: When you find a bug, try to shrink the input that causes it to the absolute minimum. A bug that appears with an array of 3 elements is much easier to trace than one that requires 100.
Practical Note

During an interview, you might not need a full fast I/O template, but being able to talk about debugging is crucial. If your code has a bug, don't panic. Instead, say, "Okay, that's not the right output. Let's do a quick dry run with this input to see where my logic is going wrong." This shows maturity and a systematic problem-solving approach.

Deeper Note

Systematic debugging is a core professional skill that has a massive return on investment. The habits you build here—forming a hypothesis, testing it with a trace, and validating invariants—are the exact same skills senior engineers use to debug complex, large-scale distributed systems.

Complexity analysis, invariants, testability, unit testing, contest templates.

Worked Examples

Worked Example 1: Most Frequent Number

Problem or Design Scenario

Given an integer array, return the most frequent value. If multiple values have the same frequency, return the smallest value.

Technical Value

This example exercises variables, loops, arrays, methods, and HashMap frequency counting. It also shows a classic brute-force-to-better upgrade.

Constraints or Assumptions
  • array length can be 0
  • values may be negative
Example Input/Output or Usage Scenario

Input: [4, 1, 2, 2, 3, 4, 4, 2]

Output: 2

Explanation: both 2 and 4 appear 3 times, so choose the smaller value.

Brute Force or Naive Approach

For each element, scan the whole array and count how often it appears. Keep track of the best answer.

This works, but it is O(n^2).

Better or Optimized Approach

Use a HashMap<Integer, Integer> to count frequencies in one pass, then scan the map entries to choose the best value.

Why the Better Approach Works

The frequency map stores each distinct value once with its count. That avoids repeated full rescans of the array.

Decision Process

An experienced engineer starts by asking three questions:

  1. Is the brute force good enough for the expected input size?
  2. If not, what repeated work is being wasted?
  3. What standard library structure removes that repeated work cleanly?

Here the wasted work is recounting the same numbers again and again. A pragmatic solution uses a HashMap because it is standard, readable, and matches the exact need. There is no need to invent a custom counting structure.

Java Solution
java
import java.util.HashMap;
import java.util.Map;

public class MostFrequentNumber {

    static int mostFrequent(int[] values) {
        if (values.length == 0) {
            throw new IllegalArgumentException("Array must not be empty");
        }

        Map<Integer, Integer> frequency = new HashMap<>();
        for (int value : values) {
            frequency.put(value, frequency.getOrDefault(value, 0) + 1);
        }

        int bestValue = values[0];
        int bestCount = frequency.get(bestValue);

        for (Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
            int value = entry.getKey();
            int count = entry.getValue();

            if (count > bestCount || (count == bestCount && value < bestValue)) {
                bestCount = count;
                bestValue = value;
            }
        }

        return bestValue;
    }
}
Dry Run

For [4, 1, 2, 2, 3, 4, 4, 2]:

  • build map: {1=1, 2=3, 3=1, 4=3}
  • start with bestValue = 4, bestCount = 3
  • inspect 1: count smaller, ignore
  • inspect 2: same count, smaller value, update best to 2
  • final answer is 2
Time and Space Complexity
  • brute force: O(n^2) time, O(1) extra space
  • optimized: O(n) time on average, O(n) extra space
Edge Cases
  • empty array
  • all numbers equal
  • tie on frequency
  • negative values
Common Mistakes
  • forgetting tie-breaking rules
  • assuming HashMap iteration order matters
  • not handling empty input
  • return top k frequent values
  • return the first most frequent by position
  • frequency by modulo class or string token
Validation

Test with duplicates, ties, one-element arrays, and negative numbers.

Worked Example 2: Balanced Brackets

Problem or Design Scenario

Given a string containing ()[]{}, determine whether it is balanced.

Technical Value

This example introduces ArrayDeque as a stack and shows how a standard library collection matches a problem pattern.

Constraints or Assumptions
  • input may be empty
  • only bracket characters are considered in this version
Example Input/Output or Usage Scenario

Input: "{[()]}"

Output: true

Brute Force or Naive Approach

Repeatedly replace (), [], and {} with empty strings until the string stops changing.

This is simple but inefficient.

Better or Optimized Approach

Use ArrayDeque<Character> as a stack. Push opening brackets. For each closing bracket, verify it matches the top.

Why the Better Approach Works

Balanced brackets obey a last-opened, first-closed rule. A stack models that directly.

Decision Process

The pragmatic choice here is not just "use a stack". It is "use the Java stack-like structure with the best fit". That means ArrayDeque, not the legacy Stack class. The code also keeps matching logic in one helper method because bracket matching is a distinct idea and deserves a distinct name.

Java Solution
java
import java.util.ArrayDeque;
import java.util.Deque;

public class BalancedBrackets {

    static boolean isBalanced(String text) {
        Deque<Character> stack = new ArrayDeque<>();

        for (char ch : text.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }

                char open = stack.pop();
                if (!matches(open, ch)) {
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }

    static boolean matches(char open, char close) {
        return (open == '(' && close == ')')
                || (open == '[' && close == ']')
                || (open == '{' && close == '}');
    }
}
Dry Run

For "{[()]}":

  • read {, stack = {
  • read [, stack = [, {
  • read (, stack = (, [, {
  • read ), pop (, match
  • read ], pop [, match
  • read }, pop {, match
  • stack empty, so balanced
Time and Space Complexity
  • naive repeated replace: often O(n^2)
  • stack approach: O(n) time, O(n) space
Edge Cases
  • empty string
  • single opening bracket
  • starts with closing bracket
  • crossed nesting like ([)]
Common Mistakes
  • using the wrong collection end
  • forgetting to check for extra opening brackets at the end
  • ignore non-bracket characters
  • report first invalid position
  • support custom token pairs
Validation

Use minimal failing cases like ), (, ([)], and (().

Worked Example 3: Student Ranking Module

Problem or Design Scenario

Given student records with name, score, and submissionTime, sort students by score descending, submission time ascending, and name ascending.

Technical Value

This example combines classes, objects, comparators, helper methods, ArrayList, and clean module design.

Constraints or Assumptions
  • all fields are valid
  • smaller submissionTime means earlier submission
Example Input/Output or Usage Scenario

Input records:

  • Asha, 95, 14
  • Ravi, 95, 12
  • Mina, 88, 10

Sorted output:

  • Ravi, 95, 12
  • Asha, 95, 14
  • Mina, 88, 10
Brute Force or Naive Approach

Write a manual nested-loop sort with multiple if conditions.

This works but is error-prone and hard to maintain.

Better or Optimized Approach

Model the record as a class and use comparator chaining.

Why the Better Approach Works

The ordering logic becomes explicit, reusable, and less bug-prone. The standard library sort is cleaner and usually faster than hand-written beginner sorts.

Decision Process

The pragmatic engineer asks whether custom low-level sorting logic adds value. Here it does not. The real problem is expressing ordering clearly. So the best code models the record with a tiny class, names the ordering with a comparator constant, and delegates sorting to the library. That is easier to test, easier to read, and easier to change.

Java Solution
java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class StudentRankingModule {

    static class Student {
        final String name;
        final int score;
        final int submissionTime;

        Student(String name, int score, int submissionTime) {
            this.name = name;
            this.score = score;
            this.submissionTime = submissionTime;
        }

        @Override
        public String toString() {
            return name + " " + score + " " + submissionTime;
        }
    }

    static final Comparator<Student> STUDENT_ORDER =
            Comparator.comparingInt((Student s) -> s.score).reversed()
                    .thenComparingInt(s -> s.submissionTime)
                    .thenComparing(s -> s.name);

    static List<Student> rank(List<Student> students) {
        List<Student> copy = new ArrayList<>(students);
        copy.sort(STUDENT_ORDER);
        return copy;
    }
}
Dry Run

Compare Asha(95,14) and Ravi(95,12):

  • score tie at 95
  • submission time decides: 12 < 14
  • Ravi comes first
Time and Space Complexity
  • sorting: O(n log n) time
  • copy plus sort support: O(n) extra space for the copied list reference structure
Edge Cases
  • duplicate names
  • identical score and submission time
  • empty list
Common Mistakes
  • wrong comparator order
  • sorting the original list when the caller expects it unchanged
  • placing thenComparing(name) before submissionTime
  • rank by GPA then credits then name
  • maintain top k students with a priority queue
  • support updates with a map from id to student
Validation

Use small lists where the exact expected ordering is obvious.

Solved Problems

Problem 1: Count Even Numbers

Problem Statement

Given an integer array, count how many numbers are even.

Constraints or Assumptions
  • array can be empty
Example

Input: [1, 2, 4, 7, 9]

Output: 2

Brute Force or Naive Solution

Single scan checking value % 2 == 0.

Optimized or Refactored Solution

The single scan is already optimal.

Why the Final Approach Works

You must inspect each element at least once to know whether it is even.

Java Solution
java
public class CountEvenNumbers {
    static int countEvens(int[] values) {
        int count = 0;
        for (int value : values) {
            if (value % 2 == 0) {
                count++;
            }
        }
        return count;
    }
}
Dry Run

For [1, 2, 4, 7, 9], the even values are 2 and 4, so the answer is 2.

Time and Space Complexity

O(n) time, O(1) space.

Edge Cases
  • empty array
  • all even
  • all odd
  • count odd numbers
  • count numbers divisible by k

Problem 2: First Index of Target

Problem Statement

Return the first index of a target value in an array, or -1 if not found.

Constraints or Assumptions
  • array is unsorted
Example

Input: values = [9, 4, 7, 4], target = 4

Output: 1

Brute Force or Naive Solution

Linear scan.

Optimized or Refactored Solution

For an unsorted array and a single query, linear scan is optimal.

Why the Final Approach Works

Without preprocessing, you may need to inspect every element.

Java Solution
java
public class FirstIndexOfTarget {
    static int firstIndex(int[] values, int target) {
        for (int i = 0; i < values.length; i++) {
            if (values[i] == target) {
                return i;
            }
        }
        return -1;
    }
}
Dry Run

Scan from left to right. The first 4 appears at index 1.

Time and Space Complexity

O(n) time, O(1) space.

Edge Cases
  • empty array
  • target absent
  • target at index 0
  • return last index
  • count all occurrences

Problem 3: First Unique Character

Problem Statement

Given a string, return the first character that appears exactly once. If none exists, return '#'.

Constraints or Assumptions
  • string may be empty
Example

Input: "swiss"

Output: 'w'

Brute Force or Naive Solution

For each character, count its occurrences by scanning the whole string.

Optimized or Refactored Solution

Build a frequency map, then scan the string again to find the first frequency of 1.

Why the Final Approach Works

The first pass stores global counts. The second pass preserves left-to-right order.

Java Solution
java
import java.util.HashMap;
import java.util.Map;

public class FirstUniqueCharacter {
    static char firstUnique(String text) {
        Map<Character, Integer> frequency = new HashMap<>();
        for (char ch : text.toCharArray()) {
            frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
        }

        for (char ch : text.toCharArray()) {
            if (frequency.get(ch) == 1) {
                return ch;
            }
        }

        return '#';
    }
}
Dry Run

s -> 3, w -> 1, i -> 1. The second pass finds w first.

Time and Space Complexity

O(n) time, O(k) space where k is distinct characters.

Edge Cases
  • empty string
  • all repeated characters
  • one-character string
  • first unique word
  • first unique number in array

Problem 4: Reverse Words in a Sentence

Problem Statement

Given a sentence with words separated by single spaces, return the words in reverse order.

Constraints or Assumptions
  • assume trimmed input with single spaces between words
Example

Input: "java makes patterns clear"

Output: "clear patterns makes java"

Brute Force or Naive Solution

Split the string and rebuild it from the end.

Optimized or Refactored Solution

Using StringBuilder is already appropriate for output construction here.

Why the Final Approach Works

The words are naturally addressable after split, and StringBuilder avoids repeated string concatenation costs.

Java Solution
java
public class ReverseWords {
    static String reverseWords(String text) {
        String[] words = text.split(" ");
        StringBuilder builder = new StringBuilder();

        for (int i = words.length - 1; i >= 0; i--) {
            builder.append(words[i]);
            if (i > 0) {
                builder.append(' ');
            }
        }

        return builder.toString();
    }
}
Dry Run

Words are [java, makes, patterns, clear]. Append from right to left.

Time and Space Complexity

O(n) time, O(n) space.

Edge Cases
  • single word
  • empty string
  • reverse characters inside each word
  • normalize extra spaces

Problem 5: Leaderboard Query Processor

Problem Statement

Process commands of the form:

  • ADD name score
  • BEST

BEST should print the student with highest score, breaking ties by lexicographically smaller name.

Constraints or Assumptions
  • only ADD and BEST commands
  • there is at least one student before BEST
Example

Commands:

  • ADD Asha 90
  • ADD Ravi 95
  • ADD Anya 95
  • BEST

Output: Anya 95

Brute Force or Naive Solution

Store all students in a list and scan the entire list for each BEST query.

Optimized or Refactored Solution

Maintain a PriorityQueue<Student> ordered by score descending then name ascending.

Why the Final Approach Works

The heap keeps the best candidate at the front, so BEST becomes efficient.

Java Solution
java
import java.util.Comparator;
import java.util.PriorityQueue;

public class LeaderboardQueryProcessor {

    static class Student {
        final String name;
        final int score;

        Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    }

    static final Comparator<Student> BEST_FIRST =
            Comparator.comparingInt((Student s) -> s.score).reversed()
                    .thenComparing(s -> s.name);

    static class Leaderboard {
        private final PriorityQueue<Student> heap = new PriorityQueue<>(BEST_FIRST);

        void add(String name, int score) {
            heap.offer(new Student(name, score));
        }

        String best() {
            Student top = heap.peek();
            return top.name + " " + top.score;
        }
    }
}
Dry Run

After inserting Asha 90, Ravi 95, and Anya 95, the heap top is Anya 95 because the score ties at 95 and Anya is lexicographically smaller.

Time and Space Complexity
  • add: O(log n)
  • best: O(1) for peek
  • space: O(n)
Edge Cases
  • one student only
  • repeated same score
  • repeated names with different scores
  • support REMOVE
  • support top k
  • support latest score by student id using map plus heap

Recognition Guide

Use concepts from this chapter when:

  • the problem is still mostly about modeling data and basic traversal
  • you need frequency counts, membership checks, custom sorting, or queue/stack behavior
  • correctness depends more on clean state handling than advanced algorithms
  • you are building a reliable template for future chapters

Recognition signals:

  • "count occurrences"
  • "check whether seen before"
  • "return unique items"
  • "sort by multiple conditions"
  • "process commands"
  • "balanced symbols"

Constraint clues:

  • large input suggests fast I/O
  • repeated lookup suggests HashMap or HashSet
  • repeated best-element query suggests PriorityQueue
  • nested matching suggests ArrayDeque as stack

Common traps:

  • wrong type choice such as int instead of long
  • incorrect comparator ordering
  • assuming hash-based collections are sorted
  • off-by-one errors in loops
  • using immutable String for repeated concatenation

When not to use these techniques:

  • do not use a heap when a one-pass answer is enough
  • do not use inheritance when a small class plus comparator is simpler
  • do not introduce extra collections if a direct array scan is sufficient

Comparison Tables

Core Container Comparison

Structure Access Insert Membership Ordering Best Use Case
Array O(1) by index fixed size O(n) index order fixed-size indexed data
ArrayList O(1) amortized append O(1) amortized append O(n) insertion order dynamic list
HashSet no indexed access O(1) average O(1) average no stable order seen/unseen checks
HashMap key lookup O(1) average O(1) average by key no stable order frequency and lookup tables
ArrayDeque front/back O(1) O(1) O(n) deque order stack or queue workflows
PriorityQueue peek best O(1) O(log n) O(n) heap order only repeated min/max access

OO Building Block Comparison

Tool Best For Main Strength Common Misuse
Class data plus related behavior concrete modeling giant god objects
Interface shared contract flexibility too many tiny abstractions too early
Abstract Class shared partial implementation reuse forcing inheritance unnecessarily
Comparator custom ordering reusable sorting rules inconsistent ordering logic

Design and Decision Making

Even in a beginner chapter, good structure matters.

Recommended Java organization for problem solving:

  • Main or Solution as the entry point
  • solve() method for one problem execution
  • small helper methods like buildFrequencyMap, isBalanced, rankStudents
  • small data classes like Student
  • comparators as named constants when ordering is important
  • FastScanner utility for large inputs

Testability considerations:

  • keep logic out of main
  • write methods that return values instead of printing immediately
  • separate parsing from business logic
  • make comparator behavior independently testable

Relevant design ideas:

  • strategy-like thinking appears when you switch comparators
  • composition is better than inheritance for many small utilities
  • clear contracts today reduce refactoring pain later

Clean code rules that matter in this chapter:

  • keep parsing separate from computation
  • keep domain objects small and obvious
  • prefer descriptive method and comparator names
  • avoid hidden mutations unless the mutation is the point of the method
  • make the happy path easy to read

How a pragmatic programmer thinks here:

  • choose the simplest data structure that directly matches the problem
  • trust the standard library before writing custom infrastructure
  • optimize only after identifying the repeated cost or correctness risk
  • avoid abstraction that hides basic ideas from a beginner
  • write code that is easy to debug on tiny examples

Practical Applications

  • Backend systems: request parsing, entity sorting, frequency analysis, cache-key lookup
  • Frontend apps: list rendering order, filtering, event queue handling
  • Databases: query result ranking and grouping before persistence or display
  • Distributed systems: message priority handling and deduplication sets
  • Operating systems: ready queues and scheduling intuition map naturally to queues and heaps
  • Networking: packet or request prioritization can resemble queue and heap workflows
  • AI systems: token counts, histogram building, and candidate ranking often use maps and heaps
  • Mobile apps: local caching, screen-model sorting, and user-input parsing
  • Games: leaderboards, inventory lookup, and event stacks

Failure Modes and Trade-offs

  • Senior engineers optimize for clarity first, then speed.
  • Small helper methods are not overhead. They reduce bugs.
  • Comparator bugs are subtle and common. Test ordering explicitly.
  • Prefer ArrayDeque over legacy Stack.
  • Prefer StringBuilder over repeated + inside loops.
  • Pragmatic programmers remove wasted work, not readability.
  • Clean code is not decoration. It is a tool for making future changes and debugging cheaper.
  • If a bug feels mysterious, reduce the input and trace exact state after each operation.
  • If a problem asks for repeated membership checks, your first instinct should be set or map, not nested loops.

Condensed Notes

  • int for ordinary counts, long for bigger ranges
  • Arrays: fixed size, indexed access
  • Strings: immutable, use StringBuilder for repeated edits
  • ArrayList: dynamic list
  • HashMap: key to value
  • HashSet: uniqueness and membership
  • ArrayDeque: stack or queue
  • PriorityQueue: repeated best element
  • Comparator chain pattern:
java
Comparator.comparingInt((Student s) -> s.score).reversed()
        .thenComparingInt(s -> s.submissionTime)
        .thenComparing(s -> s.name);
  • Fast debugging checklist:
    • print critical variables
    • test empty and one-element cases
    • dry-run a tiny example
    • verify loop boundaries

Additional Problems

Easy

  • Array Sum Again: compute total sum of an array. Expected pattern: linear scan
  • Count Uppercase Letters: count uppercase characters in a string. Expected pattern: string traversal
  • Contains Duplicate: return whether any duplicate exists. Expected pattern: HashSet membership
  • Maximum Value: return the largest array element. Expected pattern: running best variable
  • Reverse String: reverse a string using StringBuilder. Expected pattern: traversal plus mutable builder

Medium

  • Frequency Sort Characters: sort characters by frequency. Expected pattern: HashMap plus custom sort
  • Valid Parentheses Extended: ignore non-bracket characters. Expected pattern: ArrayDeque stack
  • Student Ranking Board: sort by multiple fields. Expected pattern: class plus comparator
  • Top K Smallest Numbers: return smallest k elements. Expected pattern: PriorityQueue
  • Command Processor: parse add/remove/check commands. Expected pattern: methods plus collection selection

Hard

  • Streaming Leaderboard: support updates and top queries. Expected pattern: HashMap plus PriorityQueue
  • Browser History Simulator: support back/forward navigation. Expected pattern: two stacks or deques
  • Log Frequency Analyzer: process huge input quickly. Expected pattern: fast I/O plus HashMap
  • Multi-Key Scheduler: custom ordering with tie-breakers. Expected pattern: comparator plus heap
  • Mini Collection Framework: design interfaces for reusable containers. Expected pattern: interfaces, classes, abstraction

Key Questions

  1. What is the difference between an array and an ArrayList?

    • An array has fixed size and indexed storage. ArrayList resizes dynamically and provides higher-level methods.
  2. When would you use HashSet over ArrayList?

    • When fast membership checking or uniqueness matters more than preserving indexed access.
  3. Why is StringBuilder preferred over repeated string concatenation in loops?

    • Because strings are immutable, so repeated concatenation creates many intermediate objects.
  4. Why is ArrayDeque preferred over Stack in modern Java?

    • ArrayDeque is usually faster and avoids legacy synchronization behavior that is often unnecessary.
  5. What does a comparator do?

    • It defines a custom ordering between objects, typically for sorting or heap behavior.
  6. When would you use an interface instead of an abstract class?

    • Use an interface for a shared contract across potentially unrelated classes. Use an abstract class when you need partial shared implementation.
  7. What is the average-time advantage of HashMap?

    • Lookup, insert, and update are typically O(1) on average.
  8. What is an off-by-one error?

    • A boundary bug where a loop starts or ends one position too early or too late.
  9. What should a beginner reusable template include?

    • A clear solve() method, fast input helper, StringBuilder output, and small helper methods.
  10. How do you debug a wrong answer quickly?

    • Use a tiny failing input, trace state step by step, and verify assumptions about boundaries and collection behavior.

Applied Project

Mini Project: Java Problem Solving Starter Kit

Objective

Build a small Java console toolkit that demonstrates the foundations from this chapter.

Required Features
  • read commands using a fast scanner
  • maintain a student list
  • maintain a frequency map of submitted tags
  • support duplicate checking using a set
  • support a best-student query using a comparator or priority queue
  • print debug traces in a development mode
Suggested Java Module Structure
  • Main
  • FastScanner
  • Student
  • StudentService
  • TagAnalytics
  • DebugUtil
Testing Ideas
  • empty input
  • duplicate names
  • score ties
  • many commands
  • malformed command handling if you want extra robustness
Stretch Goals
  • export ranking as text report
  • add remove/update commands
  • add interface-based storage implementations

2: Complexity and Problem Solving Basics

Introduction and Context

Complexity analysis is the habit of translating code into cost. Every algorithm spends time and memory; the point is to understand which costs stay under control as input grows and which ones explode. Big-O matters because it strips away machine-specific noise and exposes the shape of that growth.

Problem constraints are really budgets. If n is 10^5, a quadratic scan is usually already dead. If there are many queries, preprocessing may be worth extra memory. If a data structure occasionally does expensive work but stays cheap on average, amortized analysis matters. The common mistakes are counting syntax instead of repeated work, ignoring hidden loops inside library calls, and trying to optimize before a brute-force baseline reveals the real bottleneck.

Core Intuition and Mechanics

Growth, Not Speed

Let’s build a simple, powerful intuition for what complexity analysis really is.

Imagine you're a librarian tasked with finding a specific book in a library. You have two different strategies:

  1. Strategy A (The "Linear Scan"): You start at the first shelf of the first aisle and check every single book, one by one, until you find the one you're looking for.
  2. Strategy B (The "Decimal System"): The library is organized by the Dewey Decimal System. You use the signs to find the right section, then the right aisle, then the right shelf. You can pinpoint the book's location very quickly.

Now, let's analyze these strategies:

  • In a tiny library with only 10 books, Strategy A is perfectly fine. It might even be faster because you don't have to think about the decimal system.
  • But what if the library has one million books? Strategy A becomes a nightmare. It could take you days or weeks. Strategy B, however, is still incredibly efficient. It might take you a few minutes, but it won't take you weeks.

This is the core intuition of complexity analysis. We don't care about the exact time it takes on a specific day in a specific library. We care about how the time required grows as the size of the library (the "input") grows.

  • The time for Strategy A grows linearly with the number of books. Double the books, double the time.
  • The time for Strategy B grows logarithmically. Even if you double the books, it only adds one or two extra "steps" to your search.

In programming, we call these growth rates Time Complexity. We use Big O Notation to describe them.

The mechanics of analysis are simpler than they first appear:

  1. Choose the input size variable that actually drives growth.
  2. Count the dominant repeated work instead of every tiny instruction.
  3. Separate preprocessing cost from per-query or per-operation cost.
  4. Track auxiliary memory with the same discipline you apply to runtime.
  5. Compare the final cost against the problem's constraints before choosing an approach.

That same habit is what later turns brute force into optimization. Once you can see where time and memory are being spent, you can identify whether the real fix is a better data structure, a reused prefix computation, a monotonic scan, or a different search strategy.

Core Concepts and Subtopics

Concept Cluster: The Language of Performance

Subtopics Covered: 2.1 Time and Space Complexity

Here, we learn the fundamental vocabulary used to describe an algorithm's efficiency.

What Are Time and Space Complexity?
  • Time Complexity is the measure of how an algorithm's runtime scales as its input size increases. It’s not about the exact seconds or milliseconds but about the number of operations performed.
  • Space Complexity is the measure of how the memory usage of an algorithm scales with the input size. It’s about how much additional memory the algorithm needs to do its work.
Why Does This Matter?

This is how we make apples-to-apples comparisons between different algorithms. An algorithm with a better time complexity will almost always outperform one with a worse complexity for large inputs, no matter how fast the computer is.

In a job interview, after you propose a solution, the very next question will almost certainly be: "What is the time and space complexity?" Answering this confidently shows you understand the real-world implications of your code. It demonstrates that you can think beyond just making the code work.

How It Works: The Magic of Big O Notation

We express complexity using Big O notation. Think of Big O as a way to classify algorithms into different "leagues" based on their growth rate. It focuses on the worst-case scenario and simplifies the math by ignoring two things:

  1. Constants: An algorithm that takes 2n steps and one that takes n steps are in the same league. We just say both are O(n).
  2. Lower-Order Terms: If an algorithm takes n² + 3n + 100 steps, the n² term is the one that truly dominates as n gets large. The 3n and 100 become insignificant in comparison. So, we simplify the whole thing to O(n²).

The Most Common Big O "Leagues" (from best to worst):

  • O(1): Constant Time. The runtime is flat; it doesn't change with the input size.
    • Example: Accessing an element in an array by its index (myArray[5]).
  • O(log n): Logarithmic Time. The runtime grows very slowly. Every time you double the input size, you only add one extra step.
    • Example: Binary search in a sorted array.
  • O(n): Linear Time. The runtime grows proportionally to the input size. Double the input, double the time.
    • Example: Iterating through all elements of an array with a single loop.
  • O(n log n): Log-Linear Time. A very common and efficient complexity for sorting algorithms.
    • Example: Efficient sorting algorithms like Merge Sort or Quicksort.
  • O(n²): Quadratic Time. The runtime grows by the square of the input size. If you 10x the input, the runtime increases 100x.
    • Example: A nested loop that iterates over the same array.
  • O(2ⁿ): Exponential Time. The runtime doubles with each new element added to the input. These algorithms quickly become unusable even for small inputs.
    • Example: A naive recursive solution for calculating Fibonacci numbers.
  • O(n!): Factorial Time. The runtime explodes. This is typically seen in problems that involve generating all possible permutations of a set.
Quick Guide for Java Code
  • Time Complexity:
    • A single loop from 0 to n-1 is O(n).
    • A nested loop, where both loops go from 0 to n-1, is O(n²).
    • A loop that cuts the problem size in half with each iteration is O(log n).
  • Space Complexity:
    • It’s all about the extra memory you allocate.
    • Creating a new array or ArrayList of size n costs O(n) space.
    • Simple variables (int, double, boolean) cost O(1) space.
    • A recursive function that calls itself n times deep will use O(n) space on the call stack.
Mini-Example: Seeing it in Code

Let's look at three simple functions and analyze them.

java
// Finds the largest number in an array.
// Time: O(n) - The loop runs once for each element.
// Space: O(1) - We only use a few variables (max, i), no matter how big the array is.
int findMax(int[] arr) {
    int max = Integer.MIN_VALUE; // O(1) space
    for (int i = 0; i < arr.length; i++) { // Loop runs 'n' times
        if (arr[i] > max) { // This is a constant time O(1) operation
            max = arr[i];
        }
    }
    return max;
}

// Checks if an array has any duplicate numbers.
// Time: O(n²) - The inner loop runs about n/2 times for each of the n outer loop iterations. n * n = n².
// Space: O(1) - We only use a few variables.
boolean hasDuplicates(int[] arr) {
    for (int i = 0; i < arr.length; i++) { // Outer loop runs 'n' times
        for (int j = i + 1; j < arr.length; j++) { // Inner loop runs up to 'n' times
            if (arr[i] == arr[j]) { // O(1) operation
                return true; // Found a duplicate
            }
        }
    }
    return false; // No duplicates found
}

// Creates a complete copy of an array.
// Time: O(n) - The loop runs 'n' times to copy each element.
// Space: O(n) - We allocate a new array of the same size 'n'. This is the dominant space cost.
int[] copyArray(int[] arr) {
    int[] newArr = new int[arr.length]; // O(n) space is allocated here!
    for (int i = 0; i < arr.length; i++) { // Loop runs 'n' times
        newArr[i] = arr[i];
    }
    return newArr;
}
Common Pitfalls for Beginners
  • Confusing Performance with Complexity: An O(n²) algorithm can sometimes be faster than an O(n) one, but only for very small inputs. Complexity is about the trend as the input grows, not the absolute speed on one specific example.
  • Forgetting Space Complexity: It's easy to focus only on time, but using too much memory can crash your program or slow it down significantly. Always analyze both.
  • Over-counting: Beginners often try to count every single operation. Remember to just focus on the dominant term. An algorithm with O(2n + 5) complexity is just O(n). Keep it simple.

Concept Cluster: A Deeper Look at Performance

Subtopics Covered: 2.2 Best, Average, and Worst-Case Analysis; Amortized Analysis

Big O gives us the worst-case scenario, but the real world is more nuanced. Let's explore the different "flavors" of analysis to get a more complete picture.

What Are Best, Worst, and Average Cases?

Imagine you're looking for your friend Alex in a crowded train.

  • Best Case: You step onto the train, and Alex is standing right in front of you. You found them instantly! This is the absolute minimum amount of work you could have done.
  • Worst Case: You have to walk through every single car, checking every single person, only to find Alex in the very last seat of the very last car. This is the maximum possible work.
  • Average Case: On an average day, you'll probably find Alex somewhere in the middle of the train. This is the expected amount of work on a typical trip.

In algorithms, this translates to:

  • Best-Case Complexity: The performance of the algorithm given the most favorable input possible. For a search algorithm, this is often finding the item on the first try (O(1)).
  • Worst-Case Complexity (Big O): The performance on the least favorable input. This is the most important because it gives us a guarantee: the algorithm will never be slower than this.
  • Average-Case Complexity: The expected performance over all possible inputs. This is often the most realistic measure but can be much harder to calculate.
Why Does This Matter?

Sometimes, an algorithm's worst case is extremely rare, making the average case a much better predictor of real-world performance.

The most famous example is Quicksort. It has a worst-case complexity of O(n²), which looks bad. However, this only happens on already-sorted data, which is rare. Its average-case complexity is O(n log n), and in practice, it's one of the fastest general-purpose sorting algorithms we have. Understanding this distinction is key to making smart algorithm choices.

A Special Case: Amortized Analysis

This is a powerful but slightly tricky concept. It's most useful when an operation is usually very cheap, but on rare occasions, it becomes very expensive. We want to find the average cost of the operation over a long sequence of uses.

The Perfect Analogy: A Self-Cleaning Oven

  • Most of the time, using your oven is fast. You put food in, you take it out. Let's call this a cost of 1 unit.
  • But after 100 uses, the oven locks itself for 4 hours to run a deep cleaning cycle. This one "use" is incredibly expensive—let's say it has a cost of 100 units.

If you only looked at the worst case, you'd say "using my oven can take 4 hours!" which is technically true but misleading. Amortized analysis looks at the total cost over many uses.

  • Total cost over 101 uses = (100 uses * 1 unit) + (1 cleaning * 100 units) = 200 units.
  • Amortized cost per use = 200 total units / 101 uses ≈ 2 units.

So, we can say the amortized cost of using the oven is cheap, even though one specific use is very expensive.

The Classic Java Example: ArrayList.add()

  • When you add() an element to an ArrayList, it's usually O(1). It just places the item in the next open spot in its internal array.
  • But what if the internal array is full? The ArrayList must perform an expensive "resize" operation:
    1. Create a new, bigger array (usually double the size).
    2. Copy every single element from the old array to the new one.
  • This single add() operation is O(n). However, because the array size doubles each time, these expensive resizes happen less and less frequently as the list grows. When we average the cost over many add() operations, the total cost is still effectively O(1) per operation.
  • Therefore, we say the amortized time complexity of ArrayList.add() is O(1).
Mini-Example: Analyzing Insertion Sort

Let's analyze the different cases for a simple sorting algorithm.

java
// Sorts an array in place using the insertion sort algorithm.
void insertionSort(int[] arr) {
    // Start from the second element, assuming the first is a sorted sub-array of one.
    for (int i = 1; i < arr.length; i++) {
        int key = arr[i]; // The element we want to insert into the sorted portion.
        int j = i - 1;

        // Move elements of the sorted portion (arr[0..i-1]) that are greater than the key
        // one position to the right to make space for the key.
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j]; // Shift element to the right.
            j = j - 1;
        }
        // Place the key in its correct sorted position.
        arr[j + 1] = key;
    }
}
  • Best Case: The array is already sorted (e.g., [10, 20, 30, 40]).
    • The inner while loop condition (arr[j] > key) will always be false.
    • The outer loop runs n times, but the inner loop does no work.
    • Best-case complexity: O(n).
  • Worst Case: The array is sorted in reverse order (e.g., [40, 30, 20, 10]).
    • For each element i, the inner while loop has to shift all i elements before it.
    • This results in roughly 1 + 2 + 3 + ... + n operations, which is a classic formula that sums to n * (n+1) / 2.
    • Worst-case complexity: O(n²).
  • Average Case: The array is in a random, jumbled order.
    • The analysis is more complex, but on average, the inner loop will have to shift about half of the elements.
    • This still results in an average-case complexity of O(n²).
Practical Note
  • Default to Worst-Case: Unless the interviewer asks otherwise, always provide the worst-case (Big O) complexity. It's the strongest guarantee you can give.
  • Show Your Depth: If an algorithm has a famously bad worst case but a great average case (like Quicksort), you must mention both. Explain why the average case is more representative in the real world. This shows a sophisticated understanding.
  • Mention Amortized Analysis: When discussing data structures like ArrayList or HashMap, casually mentioning that an operation's cost is "amortized O(1)" is a huge plus. It signals that you understand how these fundamental tools work under the hood.

Concept Cluster: From Problem to Plan

Subtopics Covered: 2.3 Reading Constraints; 2.4 Choosing Data Structures

The goal here is to turn a problem statement into a technical plan before writing code.

What Does This Mean?

It's a two-part process:

  1. Reading Constraints: This means carefully analyzing the "rules" of the problem. What are the limits on the input size (n)? What are the possible ranges for the values in the input? These aren't just boring details; they are secret clues.
  2. Reading Constraints: This means carefully analyzing the limits of the problem. What is the input size (n)? What ranges can the values take? These details determine which solution families are feasible.
  3. Choosing Data Structures: This means selecting the structure that keeps the expensive operations cheap. Should you use a HashMap for fast lookups? A PriorityQueue to always access the smallest or largest item? The choice often determines the final complexity.
Why It Matters

Constraints do more than limit the input; they define the feasible complexity budget. By working backward from those limits, you can rule out entire categories of algorithms early and focus only on solution shapes that can actually pass.

How It Works: The Golden Rule of Time Limits

Here's a crucial rule of thumb for almost any coding platform:

A modern computer can perform roughly 10⁸ (100 million) operations per second.

If your algorithm requires significantly more operations than this, it will be too slow and will "Time Out." We can use this rule to create a "complexity budget."

The Complexity Budget Table:

If Input Size n is... Your Solution Must Be... This Suggests Algorithms Like...
10 to 25 O(2ⁿ) or O(n!) Backtracking, generating all subsets or permutations.
up to 100 O(n⁴) or O(n³) Dynamic Programming with 3 or 4 dimensions, Floyd-Warshall.
up to 2,500 O(n²) Standard Dynamic Programming, nested loops, graph traversals.
up to 100,000 O(n log n) Sorting-based approaches, Divide and Conquer, Binary Search.
1,000,000+ O(n) or O(log n) Linear scans, Two Pointers, Sliding Window, Hash Maps.
10¹⁸+ (huge numbers) O(log n) or O(1) Pure math tricks, binary search on the answer, matrix exponentiation.

How to Use This Table:
Imagine a problem states that the input array size n can be up to 100,000.

  1. You look at the table. For n = 100,000, you need an O(n log n) or O(n) solution.
  2. An O(n²) approach would require (10⁵)² = 10¹⁰ operations. This is 100 times larger than our 10⁸ budget! It would take over a minute to run and will fail.
  3. This insight is gold. You know that a simple nested-loop solution is not an option. You must find a more clever approach. This might involve sorting the array first (O(n log n)) or using a HashMap for fast lookups (O(n)).

Choosing the Right Data Structure by Its Superpower:

  • Need fast key-value lookups? -> HashMap (average O(1) time).
  • Need to store only unique items? -> HashSet (average O(1) time).
  • Need to keep items sorted automatically? -> TreeSet (O(log n) for adds/removes).
  • Need to quickly find the smallest/largest item? -> PriorityQueue (O(log n) to add, O(1) to peek).
  • Need a simple, dynamic list? -> ArrayList (amortized O(1) to add to the end).
  • Need a fast queue or stack (add/remove from both ends)? -> ArrayDeque (O(1) time).
A Pragmatic Programmer's Thought Process

Here is a step-by-step guide to planning your solution:

  1. Read the Goal: First, understand the problem. What is the exact input? What is the exact required output? Don't rush this.
  2. Check the Constraints: Find the maximum value of n. This sets your "complexity budget."
  3. Create a Brute-Force Plan: How would you solve this with the most straightforward, simple-minded approach? This is your baseline. Don't code it yet, just think it through.
  4. Analyze the Brute Force: What is its Big O complexity? Does it fit your budget? (Usually, it won't.)
  5. Find the Bottleneck: What specific part of your brute-force plan is slow? Is it a repeated search? A calculation that you're doing over and over?
  6. Pick a Tool to Fix the Bottleneck: This is where you connect the problem to a data structure or pattern.
    • "My plan repeatedly searches for a value." -> Use a HashSet or HashMap to make searches O(1).
    • "My plan repeatedly finds the minimum value in a list." -> Use a PriorityQueue to make finding the min O(1).
    • "My O(n²) plan is too slow, but I notice the array is sorted." -> Use Binary Search or the Two Pointers pattern to get to O(n log n) or O(n).
  7. Develop the Optimized Plan: Refine your plan using the new data structure or pattern.
  8. Final Analysis: Analyze the new complexity. Does it fit the budget? If yes, you are ready to code with confidence.

Concept Cluster: The Philosophy of Patterns

Subtopics Covered: 2.5 The Idea of Patterns, Brute-Force Baselines; 2.6 Recognizing and Applying Patterns

Now we move from analysis to strategy. Solving complex problems consistently requires a library of mental models. These are called patterns.

What is a Pattern?
  • A Pattern is a reusable, high-level blueprint for solving a common class of problems. It’s not a specific piece of code, but a strategic approach. "Sliding Window," "Two Pointers," and "Binary Search" are all patterns.
  • A Brute-Force Baseline is the most direct, straightforward solution you can think of. It often mimics how you'd solve the problem by hand and is usually not very efficient. It is the essential first step in finding a better solution.
Why This Is So Important

Patterns are mental shortcuts. They are the key to rapid problem-solving. Instead of trying to invent a new solution from scratch every time, you learn to recognize a problem's underlying structure and map it to a known pattern. This makes your problem-solving faster, more reliable, and far less prone to errors.

Starting with a brute-force solution is the single most important habit you can develop. Here’s why:

  1. It Guarantees a Correct Solution: In an interview or on the job, a slow solution that works is infinitely better than a fast one that's buggy or incomplete. It proves you understand the problem.
  2. It Illuminates the Path Forward: The brute-force solution isn't the destination; it's the map. By understanding why it's slow, you discover the exact bottleneck you need to fix. The path to the optimal solution becomes clear.
How It Works: From Brute Force to Optimal

Let's see this process in action.

  1. The Problem: "Given an array of numbers, find if any pair of numbers adds up to a target k."

  2. Step 1: The Brute-Force Plan.
    The simplest way is to check every possible pair.

    • Take the first number, and check it against all other numbers.
    • Take the second number, and check it against all others (that you haven't checked).
    • ...and so on.
      This translates directly to a nested loop.
    java
    // Brute-force approach
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] + arr[j] == k) {
                return true; // Found a pair!
            }
        }
    }
    
  3. Step 2: Analyze.
    The complexity is O(n²). If the input array is large, this will be too slow.

  4. Step 3: Identify the Bottleneck.
    The slow part is the inner loop. For every element arr[i], we are doing a linear search through the rest of the array to find its partner, k - arr[i]. This repeated searching is the bottleneck.

  5. Step 4: Recognize a Pattern.
    The bottleneck is "repeated searching." What's the fastest way to search for something? A HashSet or HashMap gives us O(1) average time lookups. This insight leads us to the "Hash Map Lookup" pattern.

  6. Step 5: Apply the Pattern.
    Let's use a HashSet to keep track of the numbers we've seen so far.

    java
    // Optimized approach using the Hash Map Lookup pattern
    Set<Integer> seenNumbers = new HashSet<>();
    for (int i = 0; i < arr.length; i++) {
        int complement = k - arr[i];
        // Can we find the complement in the set of numbers we've already seen?
        if (seenNumbers.contains(complement)) {
            return true; // Yes! We found a pair.
        }
        // If not, add the current number to the set for future checks.
        seenNumbers.add(arr[i]);
    }
    

    This new solution has O(n) time complexity and O(n) space complexity. We traded a bit of space to gain a massive improvement in time.

Your Pattern Recognition Checklist

As you encounter problems, ask yourself these questions to see which pattern might fit:

  • Is the input array sorted (or can it be sorted)?
    • Think Binary Search, Two Pointers, or Merge Intervals.
  • Are you working with subarrays or substrings?
    • Think Sliding Window or Prefix Sums.
  • Are you asked to find all permutations, subsets, or valid combinations?
    • Think Backtracking.
  • Are you asked for the top/best/smallest k items out of a collection?
    • Think Heaps (PriorityQueue).
  • Are you processing items in a list and need to know the "next greater" or "next smaller" element?
    • Think Monotonic Stack.
  • Is the problem about connections, networks, or dependencies?
    • Think Graphs (BFS/DFS, Union-Find).
  • Can the problem be solved by breaking it down into smaller, overlapping subproblems?
    • Think Dynamic Programming.
When Not to Force a Pattern

This is a common trap for learners. You get excited about a new pattern (like Sliding Window) and suddenly, every problem looks like it needs that pattern. Be careful.

  • Always Check the Constraints First. If n is small enough that an O(n²) solution is acceptable, a simple nested loop is often the best choice. Don't over-engineer a solution when you don't have to.
  • Does the Pattern's Logic Actually Fit? The Two Pointers pattern works on a sorted array because moving a pointer maintains a useful property (the sum either increases or decreases). If your problem doesn't have a similar property, the pattern is useless.
  • Go Back to the Brute Force. If you can't clearly state why the brute-force approach is slow and how a specific pattern fixes that exact bottleneck, you are likely applying the pattern blindly. Always connect the pattern back to the problem you're trying to solve.

Worked Examples

Let's solidify these concepts by walking through real interview problems. We'll apply the exact thought process we just learned: Constraints -> Brute Force -> Bottleneck -> Optimization.

Worked Example 1: Maximum Subarray Sum (Kadane's Algorithm)

This is a true classic. It’s a favorite in interviews because the journey from the brute-force solution to the optimal one is both beautiful and insightful.

The Problem

You are given an array of integers, nums. Find the contiguous subarray (a slice of the array) that has the largest possible sum. Return that sum.

Why This Example Is Important

It perfectly illustrates the power of changing your perspective. The naive solutions are slow because they focus on checking every single subarray. The optimal solution is fast because it asks a more clever question: "What's the best subarray that ends at this specific position?" This shift in thinking is a common theme in more advanced dynamic programming problems.

Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

The moment you see nums.length <= 10^5, your brain should scream: "This has to be O(n) or O(n log n)!" An O(n²) solution will be too slow.

Example Input
  • nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
  • Output: 6
  • Explanation: The subarray [4, -1, 2, 1] has the sum of 6, which is the largest possible.
The Brute-Force Approach (O(n²))

The most direct way to solve this is to calculate the sum of every possible subarray and keep track of the maximum sum found.

  1. Start at the first element (i).
  2. From i, start a second loop (j) to form the end of the subarray.
  3. Calculate the sum of the subarray from i to j.
  4. Compare this sum to our maxSum so far.
java
// O(n^2) Brute-Force Solution - Correct, but too slow for the constraints.
public int maxSubArrayN2(int[] nums) {
    int maxSum = Integer.MIN_VALUE;
    // 'i' will be the starting point of our subarray.
    for (int i = 0; i < nums.length; i++) {
        int currentSubarraySum = 0;
        // 'j' will be the ending point of our subarray.
        for (int j = i; j < nums.length; j++) {
            // Add the current element to the sum of the subarray ending at j.
            currentSubarraySum += nums[j];
            // Have we found a new maximum?
            maxSum = Math.max(maxSum, currentSubarraySum);
        }
    }
    return maxSum;
}

This works, but with n = 10^5, it will time out. We identified the O(n²) complexity, and the constraints tell us it's not good enough.

The Optimized Approach: Kadane's Algorithm (O(n))

The Key Insight: As we iterate through the array, we don't need to look back. At any given point i, the maximum possible sum for a subarray that ends at i can be only one of two things:

  1. The number nums[i] all by itself.
  2. The number nums[i] added to the best subarray that ended at the previous position (i-1).

We can track two variables:

  • currentMax: The maximum sum of a subarray ending at the current position.
  • globalMax: The maximum sum found anywhere in the array so far.

For each number, we update currentMax by choosing the better of the two options above. Then, we update globalMax if our new currentMax is even better.

Why This Works (The "Greedy" Choice):
The algorithm works by making a "greedy" choice at each step. If currentMax ever becomes negative, it's like a losing streak. It's better to start a fresh subarray from the next number than to let that negative sum drag you down. The line currentMax = Math.max(nums[i], currentMax + nums[i]) handles this beautifully. If currentMax is negative, currentMax + nums[i] will be smaller than nums[i] alone, so the max function effectively "resets" the subarray to start fresh with nums[i].

A Pragmatic Programmer's Thought Process
  1. "Max subarray sum. Constraints are n=10^5. My complexity budget is O(n) or O(n log n). O(n²) is out."
  2. "The brute force is nested loops. The bottleneck is recalculating sums for every subarray."
  3. "How can I do this in one pass? As I walk the array, what information do I need to carry with me?"
  4. "At any position i, the answer isn't just about nums[i]. It depends on the elements before it. Specifically, it depends on the best subarray that ended at i-1."
  5. "Let's track that. I'll call it max_ending_here. I also need a global_max to store the best result I've seen anywhere."
  6. "If max_ending_here becomes negative, it's a liability. It will only pull down the sum of any future subarray. So, if it's negative, I should just discard it and start a new subarray from the current number. The logic max_ending_here = Math.max(current_number, max_ending_here + current_number) does exactly this. It's perfect."
  7. "The plan is solid. It's one loop, so O(n) time. I only need two variables, so O(1) space. This fits my budget perfectly. I'm ready to code."
The Java Solution
java
class Solution {
    public int maxSubArray(int[] nums) {
        // Handle edge case of an empty or null array, though constraints say length >= 1.
        if (nums == null || nums.length == 0) {
            return 0;
        }

        // Initialize both maxes to the first element.
        // currentMax tracks the max sum of a subarray ending at the current position.
        int currentMax = nums[0];
        // globalMax tracks the overall max sum found anywhere in the array.
        int globalMax = nums[0];

        // Start from the second element since we've already processed the first.
        for (int i = 1; i < nums.length; i++) {
            // The key step: is it better to start a new subarray here,
            // or to extend the previous best subarray?
            currentMax = Math.max(nums[i], currentMax + nums[i]);

            // We've found the best subarray ending at 'i'.
            // Is this better than the best we've ever seen anywhere?
            if (currentMax > globalMax) {
                globalMax = currentMax;
            }
        }
        return globalMax;
    }
}
Dry Run with an Example

Let's trace the algorithm with nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4].
Initial state: globalMax = -2, currentMax = -2.

i nums[i] currentMax = max(nums[i], currentMax + nums[i]) globalMax Note
0 -2 -2 (initial) -2 (initial) currentMax is negative.
1 1 max(1, -2 + 1) = max(1, -1) = 1 max(-2, 1) = 1 Start a new subarray at 1.
2 -3 max(-3, 1 + -3) = max(-3, -2) = -2 max(1, -2) = 1 Extend, but the sum is now negative.
3 4 max(4, -2 + 4) = max(4, 2) = 4 max(1, 4) = 4 Start a new subarray at 4.
4 -1 max(-1, 4 + -1) = max(-1, 3) = 3 max(4, 3) = 4 Extend the subarray [4].
5 2 max(2, 3 + 2) = max(2, 5) = 5 max(4, 5) = 5 Extend the subarray [4, -1].
6 1 max(1, 5 + 1) = max(1, 6) = 6 max(5, 6) = 6 Extend the subarray [4, -1, 2].
7 -5 max(-5, 6 + -5) = max(-5, 1) = 1 max(6, 1) = 6 Extend, but the sum drops.
8 4 max(4, 1 + 4) = max(4, 5) = 5 max(6, 5) = 6 Extend.

The loop finishes. The final globalMax is 6.

Final Complexity Analysis
  • Time Complexity: O(n). We iterate through the array exactly once.
  • Space Complexity: O(1). We only use two extra variables (currentMax, globalMax), regardless of the array's size.
Thinking About Edge Cases
  • Array with one element: [5]. globalMax and currentMax are initialized to 5. The loop is skipped. Returns 5. Correct.
  • All negative numbers: [-2, -1, -5]. The algorithm will correctly find the largest number (the one closest to zero), which is -1. Correct.
  • Empty array: The problem constraints say length >= 1, but our code handles this gracefully by returning 0. This is a good defensive programming habit.

Solved Problems

Now it's time to apply what you've learned. For each problem, we'll follow the same structured thinking: analyze constraints, devise a brute-force plan, identify the bottleneck, and then craft an optimized solution.

Problem 1: Two Sum (Difficulty: Easy)

This is arguably the most famous coding interview question of all time. It's a perfect first test of your ability to move from a brute-force to an optimized solution.

The Problem

Given an array of integers nums and a target integer target, find the indices of the two numbers in the array that add up to the target.

Assumptions
  • You can assume there is exactly one solution for each input.
  • You cannot use the same element twice.
Constraints
  • 2 <= nums.length <= 10^4
  • The numbers and target can be large, but that doesn't affect our logic.

The constraint n <= 10^4 tells us that an O(n²) solution, which would be (10^4)² = 10^8 operations, is on the edge of our time limit. It might pass, but it's risky. An O(n) solution would be much safer and is clearly preferred.

Example
  • Input: nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1] (Because nums[0] + nums[1] is 2 + 7 = 9)
The Brute-Force Solution (O(n²))

The most straightforward approach is to check every possible pair of numbers using a nested loop.

  • Time: O(n²)
  • Space: O(1)
The Optimized Solution (O(n))

The bottleneck in the brute-force approach is the inner loop, which performs a slow, linear search for the second number. We can eliminate this search by using a HashMap.

A Pragmatic Programmer's Thought Process
  1. Constraints & Budget: n is up to 10^4. My complexity budget is tight. O(n²) is risky; O(n) is ideal.
  2. Brute-Force Plan: A nested loop to check every pair. The outer loop picks the first number, nums[i]. The inner loop checks all subsequent numbers, nums[j], to see if nums[i] + nums[j] == target.
  3. Bottleneck: For each number nums[i], I'm searching the rest of the array for its "complement" (target - nums[i]). This search is O(n), and I'm doing it n times. That's my O(n²) bottleneck.
  4. Optimization Idea: How can I make that search faster? The fastest possible search is O(1). The data structure for O(1) lookups is a HashMap (or HashSet).
  5. Optimized Plan:
    • I'll iterate through the array just once.
    • I'll use a HashMap to store the numbers I've already seen and their indices. Let's call it seenNumbers.
    • For each number nums[i], I'll calculate its required partner: complement = target - nums[i].
    • Then, I'll ask the HashMap: "Have you seen the complement before?"
      • If yes, I've found my pair! I can immediately return the index of the complement (which I stored in the map) and the current index, i.
      • If no, I'll add the current number and its index to the map: seenNumbers.put(nums[i], i). This way, future numbers can check if nums[i] is their complement.
The Java Solution
java
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // This map will store the numbers we've seen and their indices.
        // Key: The number itself. Value: The index of that number.
        Map<Integer, Integer> seenNumbers = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int currentNum = nums[i];
            int complement = target - currentNum;

            // Check if the complement we need is already in our map.
            if (seenNumbers.containsKey(complement)) {
                // If yes, we've found our solution.
                return new int[]{seenNumbers.get(complement), i};
            }

            // If we didn't find the complement, add the current number and its index
            // to the map so that future elements can find it.
            seenNumbers.put(currentNum, i);
        }

        // The problem guarantees a solution exists, so we should never reach here.
        // In a real-world scenario, we'd throw an exception for an invalid state.
        throw new IllegalArgumentException("No solution found for Two Sum");
    }
}
Complexity and Trade-offs
  • Time Complexity: O(n). We iterate through the array of n elements only once. Each HashMap operation (containsKey and put) takes O(1) time on average.
  • Space Complexity: O(n). In the worst-case scenario, we might have to store all n elements in the HashMap.
  • The Trade-off: This is a classic space-time trade-off. We used extra memory (O(n) space for the map) to reduce our runtime from O(n²) to O(n). This is a very common and powerful optimization strategy.

Problem 2: Valid Parentheses (Difficulty: Easy)

This problem tests your knowledge of a fundamental data structure and its "Last-In, First-Out" behavior.

The Problem

Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid. An input string is valid if:

  1. Open brackets must be closed by the same type of bracket.
  2. Open brackets must be closed in the correct order.
Constraints
  • 1 <= s.length <= 10^4
Example
  • Input: s = "()[]{}" -> Output: true
  • Input: s = "(]" -> Output: false
  • Input: s = "([)]" -> Output: false (The [ was closed before the ( was.)
The Core Insight: Last-In, First-Out (LIFO)

The problem's rules scream "Last-In, First-Out." The most recently opened bracket must be the first one to be closed. For example, in ([{}]), the { is opened last, so it must be closed first. This LIFO behavior is the textbook use case for a Stack.

A Pragmatic Programmer's Thought Process
  1. "The problem is about matching pairs in the correct order. The last thing I open should be the first thing I close. This is LIFO. I need a Stack."
  2. The Plan:
    • I'll iterate through the input string, character by character.
    • I'll use a Stack (or in modern Java, an ArrayDeque which is preferred) to keep track of the open brackets I'm waiting to close.
    • If I see an opening bracket ((, {, [), I'll push it onto the stack. It's an "unclosed debt."
    • If I see a closing bracket (), }, ]), I need to check if it settles a debt.
      • First, is the stack empty? If so, I have a closing bracket with no opener. This is invalid.
      • If the stack is not empty, I'll pop the top element. This was the last open bracket.
      • Does the popped opener match the current closer? (e.g., ( matches ), { matches })?
        • If no, it's the wrong type of bracket. Invalid.
        • If yes, that pair is successfully closed. I continue.
  3. Final Check: After the loop finishes, what's the state of the stack?
    • If the stack is empty, it means every opening bracket found its matching closing partner. The string is valid.
    • If the stack is not empty, it means there are unclosed opening brackets (like in s = "(("). The string is invalid.
The Java Solution
java
import java.util.ArrayDeque;
import java.util.Deque;

class Solution {
    public boolean isValid(String s) {
        // Use ArrayDeque as a Stack. It's the recommended implementation in modern Java.
        Deque<Character> stack = new ArrayDeque<>();

        for (char c : s.toCharArray()) {
            // If it's an opening bracket, push it onto the stack.
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                // If it's a closing bracket, the stack cannot be empty.
                if (stack.isEmpty()) {
                    return false; // A closing bracket with no corresponding opener.
                }

                // Pop the last open bracket and check if it matches the current closing one.
                char top = stack.pop();
                if (c == ')' && top != '(') {
                    return false; // Mismatched: e.g., (]
                }
                if (c == '}' && top != '{') {
                    return false; // Mismatched: e.g., {]
                }
                if (c == ']' && top != '[') {
                    return false; // Mismatched: e.g., [)
                }
            }
        }

        // If the stack is empty at the end, all brackets were correctly matched and closed.
        return stack.isEmpty();
    }
}
Complexity Analysis
  • Time Complexity: O(n). We iterate through the string of n characters exactly once, and each stack operation (push, pop, isEmpty) is O(1).
  • Space Complexity: O(n). In the worst-case scenario, the input string could consist of all opening brackets (e.g., "((((...))))"), and we would have to store all n characters on the stack.

Recognition Guide

This section is your field guide to recognizing common patterns based on clues in the problem statement.

  • When should I think about complexity?

    • Always. Before you write code, use the constraints to set your complexity budget. After you write code, analyze it to ensure you met that budget.
  • How do I spot a chance to optimize from O(n²) to O(n)?

    • Look for problems that say "find a pair..." or "for each element, find a property in the rest of the array..."
    • The brute-force is almost always a nested loop.
    • The optimization often involves using a HashMap to replace the inner loop's search with an O(1) lookup.
  • What are the keywords for different data structures?

    • HashMap/HashSet: "count frequencies," "check for duplicates," "fast lookups," "store seen items," "cache results."
    • Stack (ArrayDeque): "parentheses matching," "LIFO (Last-In, First-Out)," "undo," "backtracking in a line."
    • PriorityQueue (Heap): "find the top/smallest/largest 'k' items," "find the median in a stream."
  • How do I use constraints as clues?

    • n is large (> 10^5): You must use an O(n) or O(n log n) algorithm.
    • n is medium (~2000): An O(n²) algorithm is likely acceptable.
    • n is small (< 25): An O(2ⁿ) exponential solution (like backtracking) is probably okay.
  • How do I avoid forcing a pattern where it doesn't belong?

    • Trust the brute force. The simplest solution that passes the time limit is the best solution. Don't use a complex pattern if a nested loop works.
    • Check the prerequisites. The Two Pointers pattern requires a sorted array. If your array isn't sorted (and can't be), the pattern is useless.
    • Articulate the "why." If you can't explain exactly how a pattern fixes the specific bottleneck of the brute-force solution, you're just guessing.

Tool Selection Table

Choosing the right data structure is often the single most important decision you'll make. This table is a quick reference for the most common Java collections and their performance characteristics.

Operation ArrayList LinkedList HashMap HashSet PriorityQueue ArrayDeque (as Stack/Queue)
Access by Index (get(i)) O(1) O(n) N/A N/A N/A N/A
Search for Value (contains) O(n) O(n) O(1) O(1) O(n) O(n)
Add to End O(1) (amortized) O(1) O(1) O(1) O(log n) O(1)
Add to Front O(n) O(1) O(1) O(1) O(log n) O(1)
Remove from End O(1) O(1) O(1) O(1) N/A O(1)
Remove from Front O(n) O(1) O(1) O(1) O(log n) O(1)
Get Min/Max O(n) O(n) O(n) O(n) O(1) O(n)
Space Complexity O(n) O(n) O(n) O(n) O(n) O(n)
When to Choose Default list; fast iteration & random access. Frequent additions/removals at both ends. Fast key-value lookups. Storing unique items; fast lookups. Finding the smallest/largest item quickly. The best choice for a Stack or Queue.

Key Takeaways from the Table:

  • ArrayList is your default List: Unless you have a specific reason not to, ArrayList is usually the best choice for a general-purpose list. Its O(1) access by index and excellent cache performance make it very fast for iteration.
  • HashMap is for lookups: If your problem involves repeatedly searching for items, counting frequencies, or associating one piece of data with another (like in twoSum), a HashMap is almost always the answer.
  • ArrayDeque is the modern Stack/Queue: It's more efficient than the older Stack and LinkedList classes for LIFO (stack) and FIFO (queue) operations.
  • PriorityQueue is for finding extremes: When a problem asks for the "k-th largest," "smallest," or "most frequent" items, a PriorityQueue is a strong candidate.

Design and Decision Making

The concepts in this chapter aren't just for interviews; they are fundamental to writing professional, high-quality software. Let's look at our examples through the lens of a pragmatic programmer.

  • Clean Code and Readability: An optimized algorithm is often a cleaner one. The HashMap solution for twoSum is not just faster than the nested loop; it's also more expressive. It clearly communicates the intent: "for each number, check if we've already seen its complement." Good variable names (seenNumbers, complement) make this intent even clearer.

  • Choosing the Right Tool for the Job: A pragmatic programmer knows their tools. They don't implement their own hash table from scratch for twoSum; they use java.util.HashMap. They know that ArrayDeque is the modern, efficient choice for a stack, replacing the older Stack class. This chapter is about learning to map a problem's abstract requirements to the concrete, battle-tested tools provided by your language's standard library.

  • The Power of Abstraction: Good algorithms are powerful abstractions. Kadane's algorithm is a concise example. It reduces "find the contiguous subarray with the largest sum" to two variables (currentMax, globalMax) and one update rule. Distilling a larger problem into a small, reusable model is a core software design skill.

  • Designing for Testability: The brute-force solution, while slow, is often very simple and obviously correct. This makes it an excellent tool for testing your optimized solution. You can write a test that runs both the brute-force and optimized versions on small inputs and asserts that they produce the same result. This is a powerful way to gain confidence in your more complex, optimized code.

  • Thinking in APIs: Look at the method signature for twoSum: public int[] twoSum(int[] nums, int target). It's a clean, well-defined contract. It takes exactly what it needs and returns a simple, predictable result. It doesn't rely on any hidden global state. This is a small-scale example of good API (Application Programming Interface) design, a crucial skill in professional development.

Practical Applications

These concepts aren't just abstract interview topics; they are at the core of everyday software engineering.

  • Time Complexity in Web Development: Imagine a social media feed. A slow, O(n²) algorithm for fetching posts might be fine for a user with 50 friends, but it will crash the server for a user with 5,000 friends. Backend engineers live and breathe complexity analysis to ensure their APIs are fast and scalable under heavy load.

  • Space Complexity in Data Processing: When you're running a data analysis job on a massive multi-gigabyte file, an O(n) algorithm that tries to load the entire file into memory will fail. A streaming algorithm that processes the file line-by-line with O(1) space complexity will succeed.

  • Amortized Analysis in Databases: When you INSERT a row into a database, it's usually very fast. But occasionally, the database needs to perform an expensive operation, like splitting a page or rebalancing an index tree. Database designers rely on amortized analysis to guarantee that the average cost of an INSERT remains extremely low.

  • Choosing Data Structures in System Design:

    • Caching Systems (like Redis or Memcached) are essentially giant HashMaps that provide O(1) access to frequently requested data, reducing database load.
    • Network Routers use a specialized tree-like data structure called a Trie to look up IP address prefixes in a highly efficient manner.
    • AI and Machine Learning models, like neural networks and knowledge graphs, are themselves complex graph data structures, and their training and inference rely on efficient graph traversal algorithms.

Failure Modes and Trade-offs

Mastering this topic means going beyond the basics and understanding the subtle trade-offs that senior engineers navigate.

  • Beyond Big O: Constant Factors Matter: A senior engineer knows that Big O notation hides constant factors. An ArrayList and a LinkedList are both O(n) for iteration, but ArrayList is dramatically faster in practice. Why? Because its elements are stored in a contiguous block of memory, which is very friendly to the CPU's cache (a concept called "cache locality"). A LinkedList, with its scattered nodes, is cache-unfriendly.

  • The Overhead of Data Structures: For a very small input size, the overhead of setting up a HashMap might make it slower than a simple nested loop. A senior engineer has the intuition to know when a "less optimal" but simpler solution is actually better for a specific use case.

  • Answering the "What If" Questions (Interview Traps):

    • Interviewer: "What's the complexity of your HashMap solution?"
    • You: "It's O(n) time on average."
    • Interviewer: "On average? What about the worst case?"
    • Expert You: "You're right to ask. In the pathological (and extremely rare) worst case where a poor hash function causes all keys to collide into the same bucket, every HashMap operation could degrade to O(n). This would make the overall time complexity O(n²). However, with Java's well-designed hash functions, we can confidently rely on the average-case O(n) performance."
    • This answer shows a deep, practical understanding.
  • Always State Both Complexities: A very common junior mistake is to only state the time complexity. Always remember to analyze and state both time and space.

  • Articulating the Space-Time Trade-off: This is a fundamental concept in computer science. For the twoSum problem, you should be able to say: "The brute-force O(n²) solution uses O(1) space. My optimized O(n) solution uses O(n) space. I made a space-time trade-off: I used more memory to achieve a significantly faster runtime."

Condensed Notes

  • Complexity is about growth, not absolute speed.
  • Big O describes the worst-case growth rate and ignores constants.
  • Time Complexity: Count the operations inside loops. Nested loops often mean n * m or n².
  • Space Complexity: Count the extra memory allocated based on the input size.
  • The 10⁸ Operations Rule: Your rule of thumb for a 1-second time limit.
  • Constraint -> Complexity:
    • n <= 10^5 -> Must be O(n) or O(n log n).
    • n <= 2000 -> O(n²) is probably fine.
    • n <= 25 -> O(2ⁿ) is probably fine.
  • Brute Force First: Always start with the simplest solution. It clarifies the problem and reveals the bottleneck.
  • Bottleneck -> Data Structure:
    • Slow search? -> HashMap
    • Need uniques? -> HashSet
    • Need smallest/largest? -> PriorityQueue
    • LIFO/FIFO? -> ArrayDeque

Additional Problems

This practice set is designed to help you internalize the patterns from this chapter.

  • Easy:
    1. Contains Duplicate: Given an array, find if it contains any duplicates. (Pattern: HashSet)
    2. Reverse String: Reverse a string in-place. (Pattern: Two Pointers)
    3. Majority Element: Find the element that appears more than n/2 times. (Pattern: HashMap or Boyer-Moore Voting Algorithm)
    4. Implement Queue using Stacks: (Pattern: Amortized Analysis)
  • Medium:
    1. 3Sum: Find all unique triplets in an array that sum to zero. (Pattern: Sort then Two Pointers)
    2. Group Anagrams: Group a list of strings by their anagrams. (Pattern: HashMap with a sorted string as the key)
    3. Longest Substring Without Repeating Characters: (Pattern: Sliding Window + HashSet)
    4. Product of Array Except Self: (Pattern: Prefix/Suffix Products)
    5. Daily Temperatures: For each day, find how many days until a warmer day. (Pattern: Monotonic Stack)
  • Hard:
    1. Largest Rectangle in Histogram: (Pattern: Monotonic Stack)
    2. Trapping Rain Water: (Pattern: Two Pointers, DP, or Stack)
    3. First Missing Positive: (Pattern: Cyclic Sort, using the array itself as a hash map)
    4. Sliding Window Maximum: (Pattern: Monotonic Deque)

Key Questions

  1. Q: You wrote a nested loop. Does that automatically mean the complexity is O(n²)?
    A: Not necessarily. It depends entirely on how many times each loop runs. A standard nested loop from 0 to n is O(n²). But if the outer loop runs n times and the inner loop runs m times, it's O(n*m). If an inner loop only runs a logarithmic number of times, the complexity could be O(n log n). You have to analyze the bounds of each loop.

  2. Q: In Java, when would you choose an ArrayList over a LinkedList?
    A: I would use ArrayList almost every time. It offers O(1) random access (get(i)) and is much faster for iteration due to better CPU cache performance (cache locality). I would only consider LinkedList in a rare scenario where my application almost exclusively adds or removes elements from the very beginning or end of a massive list and never accesses elements by index.

  3. Q: Can you give me a simple explanation of amortized analysis?
    A: It's about finding the average cost of an operation over a sequence of many operations. The classic example is adding to a Java ArrayList. While most adds are O(1), it occasionally has to resize its internal array, which is an expensive O(n) operation. But because this expensive event happens infrequently, the average cost, or amortized cost, of each add operation smooths out to be O(1).

  4. Q: A problem has a constraint of n=10^5. Your O(n²) brute-force solution is too slow. What are your immediate thoughts?
    A: My immediate thought is that I need to find a solution that is either O(n log n) or O(n). This tells me what to try next. An O(n log n) solution often involves sorting the input first, which might allow me to use patterns like Binary Search or Two Pointers. An O(n) solution suggests I need a single-pass algorithm, possibly using a clever data structure like a HashMap to speed up lookups.

  5. Q: What's the difference between O(1) and O(n) space complexity?
    A: O(1) or "constant" space means the algorithm's memory usage is fixed and does not grow with the input size. O(n) or "linear" space means the memory required grows in direct proportion to the input size, for example, if I create a copy of the input array.

  6. Q: Why is starting with a brute-force solution a good strategy in an interview?
    A: For three main reasons: First, it proves I can solve the problem correctly, which is a huge first step. Second, it gives me a working solution and a safety net. Third, and most importantly, analyzing the brute force is the key to finding the optimal solution. It helps me pinpoint the exact bottleneck that needs to be fixed.

  7. Q: What is an "in-place" algorithm?
    A: An in-place algorithm is one that transforms the input data using only a small, constant amount of extra memory. Its space complexity is typically O(1). For example, reversing an array by swapping elements from the ends toward the middle is an in-place algorithm.

Applied Project: Log File Analyzer

  • Objective: Create a command-line tool in Java that can efficiently analyze a large log file and report key metrics.
  • The Challenge: Your tool must be able to process a log file with over 1 million lines without running out of memory or taking an unreasonable amount of time. This forces you to think about complexity.
  • Log Format: Each line in the log file will have the format: TIMESTAMP LEVEL MESSAGE (e.g., 2023-10-27T10:00:00Z INFO Application started).
  • Required Features:
    1. Count the total number of log entries.
    2. Count the number of entries for each log level (INFO, WARN, ERROR, etc.).
    3. Find the single most frequent log message.
  • Analysis Questions:
    • What is the time and space complexity of your solution?
    • For feature #2 (counting levels), could you use an EnumMap? What would be the benefit?
    • For feature #3 (most frequent message), what data structure is essential?
  • Stretch Goal (The O(1) Space Challenge):
    • Can you identify if there are any duplicate log lines (lines that are 100% identical) in the file using only O(1) extra space? What is the time complexity trade-off you would have to make? (Hint: Think about sorting the file first, but without loading it all into memory).

3: Design Thinking Foundations

Introduction and Context

Software usually becomes painful not because the first version failed, but because later changes became expensive and risky. This chapter gives you the vocabulary and judgment to prevent that decay. Instead of only asking whether code works right now, you start asking whether responsibilities are clear, dependencies are controlled, and changes stay local instead of rippling through the system.

The core trade-off in design is not "pattern or no pattern." It is whether the structure makes future changes cheaper or more confusing. That is why this chapter focuses on principles, relationships, refactoring, and diagrams together: they are different ways of reasoning about the same problem, which is keeping code flexible without turning it into abstraction-heavy ceremony.

Core Intuition and Mechanics

The LEGO Analogy: How Design Thinking Works

Imagine building with LEGO bricks. A beginner just clicks bricks together to make something that looks roughly right. The structure might work in the short term, but it's brittle. If you need to change the color of one brick or add a new section, the whole thing falls apart.

An expert, however, understands:

  • Which types of bricks are available and what they're best for
  • Which connections are strong or weak and which to use for flexibility
  • How to build in modules that can be easily changed, removed, or reused later

Design thinking brings this expertise to software:

  • Design Patterns are like expert LEGO techniques. They are proven recipes for combining objects and classes to solve common structural problems. "Need to swap payment methods at runtime? Here's the standard way to do it."

  • SOLID Principles are like the physics of LEGO. They are the fundamental laws that explain why certain structures are better than others. "Don't build a giant, rigid monolith that will shatter if you change one dependency at the bottom. Use dependency injection instead."

  • UML is like the blueprint language. It lets you draw your LEGO design on paper to show someone else how the pieces connect before you start building. A picture is often clearer than a paragraph of explanation.

How Design Mechanics Fit Together

  • Principles such as SOLID, DRY, KISS, and YAGNI explain the forces that make code easier or harder to change.
  • Patterns package recurring responses to those forces when a certain kind of collaboration keeps showing up.
  • Object relationships such as composition, delegation, and inheritance determine how change and responsibility flow through the code.
  • UML diagrams externalize that structure so you can reason about it without holding every dependency in your head.
  • Refactoring is the controlled process of moving from a brittle design to a clearer one without changing externally visible behavior.

Seen together, these are not separate topics. They are one design loop: notice a force, model the structure, improve the relationships, and keep the system understandable as it evolves.

Core Concepts and Subtopics

Concept Cluster 1: What Are Design Patterns and Why Do They Matter?

Topics in this cluster:

  • 3.1 What are design patterns; Why design patterns matter; Why patterns exist in algorithmic problem solving
  • 3.2 History of design patterns; From recurring problems to reusable solutions; Pattern classifications
Definition

A design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design.

Key insight: It is not finished code. A pattern is a description or template for how to solve a problem. It's like a recipe in a cookbook, not the actual meal. You adapt it to your specific situation.

Why Patterns Matter

1. Shared Language
Instead of describing a complex structure from scratch, you can just say, "I used a Singleton here," and other developers instantly understand:

  • What the intent is
  • What trade-offs you've accepted
  • How the parts interact

This saves countless hours of explanation and reduces misunderstandings.

2. Proven Solutions
Patterns represent the collective wisdom of thousands of developers. When you use a pattern, you're not inventing a solution in isolation—you're leveraging decades of experience.

3. Avoids Reinventing the Wheel (or the Square Wheel)
Without patterns, you might invent a solution that seems clever but has hidden problems:

  • It might work for your current use case but fail when requirements change
  • It might create maintenance nightmares for future developers
  • It might have performance pitfalls that aren't obvious

Using established patterns means these pitfalls have already been discovered and addressed by countless developers before you.

How Design Patterns Work: The Four Components

Every pattern has four key components:

  1. Problem: What recurring problem does this pattern solve? What symptoms appear in the code that suggest you need this pattern?

  2. Context: When should you apply this pattern? What preconditions must be true? What alternatives might you consider instead?

  3. Solution: What are the key elements that make up the design? How do they relate to each other? What are the responsibilities of each piece? How do they collaborate?

  4. Consequences: What are the benefits and drawbacks of using this pattern? What new problems might it introduce? What trade-offs are you accepting?

A good pattern provides guidance on all four components, not just the solution.

Why Patterns Exist in Algorithmic Problem Solving

When people hear "design patterns," they think of object-oriented design (classes, interfaces, inheritance). But the concept of patterns is universal.

In algorithms, we have patterns too:

  • Two Pointers: A technique for traversing an array with two moving indices
  • Sliding Window: A technique for solving problems on contiguous subarrays
  • BFS on a Grid: A template for exploring connected cells in a 2D matrix
  • DFS with Backtracking: A template for exploring all possible combinations

These are patterns because they:

  • Solve a class of problems (not just one specific problem)
  • Provide a starting structure for your thinking
  • Come with known trade-offs (time complexity, space complexity, etc.)
  • Have a consistent vocabulary that developers recognize

Just as you'd recognize a "Factory Pattern" in OO code, you recognize a "Sliding Window" algorithm in interview problems. Both are patterns.

History: From Individual Solutions to Universal Patterns

The concept of design patterns in software was popularized by four software architects: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. They are collectively known as the "Gang of Four" (GoF).

In 1994, they published the seminal book: Design Patterns: Elements of Reusable Object-Oriented Software.

The Big Idea: Instead of each developer inventing their own solutions, let's document the solutions that the best developers have discovered through experience. Let's name them, categorize them, and teach them to others.

This book cataloged 23 fundamental patterns. More than 30 years later, these patterns are still the foundation of software architecture.

Pattern Classifications

All 23 GoF patterns fit into three broad categories:

1. Creational Patterns (4 patterns)

  • Purpose: Control object creation mechanisms
  • Goal: Create objects in a manner suitable to the situation
  • Common patterns: Singleton, Factory, Builder, Prototype
  • Why they matter: As systems get complex, controlling how objects are created becomes as important as what they do

2. Structural Patterns (7 patterns)

  • Purpose: Ease design by identifying simple ways to realize relationships between entities
  • Goal: Combine objects into larger structures while keeping these structures flexible and efficient
  • Common patterns: Adapter, Facade, Composite, Decorator, Proxy
  • Why they matter: They show you how to compose simple objects into complex ones while maintaining clarity

3. Behavioral Patterns (12 patterns)

  • Purpose: Identify common communication patterns between objects
  • Goal: Implement these communication patterns in a flexible, maintainable way
  • Common patterns: Strategy, Observer, Command, State, Template Method, Chain of Responsibility
  • Why they matter: They help you manage the flow of logic and responsibility through your system
Interview Insight: What Interviewers Really Want to Hear

When an interviewer asks, "How would you design X?", they are not looking for:

  • A single class with 1000 lines of code
  • A solution that only works for their specific example
  • Code you can type in 10 minutes

They are looking for:

  • Evidence that you think in terms of components and responsibilities
  • Understanding of trade-offs and when to apply different approaches
  • Ability to communicate your design clearly
  • Knowledge of how to extend the system without breaking existing code

Using the language of design patterns is the most effective way to demonstrate all of this. Saying "I'd use a Factory to create objects in a way that's decoupled from the client" tells an interviewer you understand principles, not just syntax.


Concept Cluster 2: The Principles of Good Design

Topics in this cluster:

  • 3.3 SOLID principles; DRY principle; KISS principle; YAGNI principle
What Are Design Principles?

Principles are different from patterns.

  • A pattern is a concrete solution template: "Use the Strategy pattern for this."
  • A principle is a high-level guideline: "Depend on abstractions, not concrete implementations."

Principles are more fundamental. They guide you toward good design decisions, and many patterns exist because they follow these principles.

SOLID: The Five Core Principles

SOLID is an acronym for five principles that form the foundation of object-oriented design. They were popularized by Robert C. Martin (often called "Uncle Bob").


S — Single Responsibility Principle (SRP)

Definition: A class should have one reason to change. In other words, a class should have only one job or one area of responsibility.

The Intuition:
Imagine a chef who is also the cashier, also does the dishes, and also handles inventory. When the restaurant gets busy, everything falls apart. When one responsibility changes (new inventory system), the chef has to stop cooking.

A specialized chef who only cooks is much more effective.

Bad Example:

java
// VIOLATES SRP: This class has THREE reasons to change:
// 1) If the Employee calculation logic changes
// 2) If the database schema changes
// 3) If the report format changes

public class Employee {
    private String name;
    private double salary;
    
    // Responsibility 1: Calculate compensation
    public double calculatePay() {
        return salary * 1.2; // With bonuses
    }
    
    // Responsibility 2: Persist to database
    public void saveToDatabase() {
        System.out.println("Saving to database...");
        // Database code here
    }
    
    // Responsibility 3: Generate reports
    public String generateReportXML() {
        return "<employee><name>" + name + "</name></employee>";
    }
}

Good Example:

java
// FOLLOWS SRP: Each class has ONE reason to change

// Responsibility 1: Encapsulate employee data and business logic
public class Employee {
    private String name;
    private double salary;
    
    public double calculatePay() {
        return salary * 1.2;
    }
    
    public String getName() { return name; }
    public double getSalary() { return salary; }
}

// Responsibility 2: Handle persistence
public class EmployeeRepository {
    public void save(Employee e) {
        System.out.println("Saving " + e.getName() + " to database...");
        // Database code here
    }
}

// Responsibility 3: Handle reporting
public class EmployeeReportGenerator {
    public String generateReportXML(Employee e) {
        return "<employee><name>" + e.getName() + "</name></employee>";
    }
}

Why It Matters:

  • Easier to test: You can test calculatePay() without needing a database
  • Easier to maintain: Changes to the report format don't affect the calculation logic
  • Easier to reuse: Another part of the system can use the Employee class without needing all three responsibilities

O — Open/Closed Principle (OCP)

Definition: Software entities should be open for extension but closed for modification.

The Intuition:
Imagine an electrical outlet in your home. The outlet's design is "closed" (you can't change it). But it's "open for extension" because you can plug in many different devices—a lamp, a charger, a vacuum.

Good design is like that outlet: you can add new functionality without changing the core structure.

Bad Example:

java
// VIOLATES OCP: Adding a new payment method requires modifying this class

public class PaymentProcessor {
    public void processPayment(String method, double amount) {
        if (method.equals("credit")) {
            System.out.println("Processing credit card: $" + amount);
        } else if (method.equals("paypal")) {
            System.out.println("Processing PayPal: $" + amount);
        }
        // If we add "bankTransfer", we have to modify this class!
    }
}

Good Example:

java
// FOLLOWS OCP: Adding a new payment method just means creating a new class

public interface PaymentStrategy {
    void pay(double amount);
}

public class CreditCardStrategy implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Processing credit card: $" + amount);
    }
}

public class PayPalStrategy implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Processing PayPal: $" + amount);
    }
}

public class PaymentProcessor {
    private PaymentStrategy strategy;
    
    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void processPayment(double amount) {
        strategy.pay(amount);
    }
}

// To add BankTransfer, we just create a new class. No modifications needed!
public class BankTransferStrategy implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Processing bank transfer: $" + amount);
    }
}

Why It Matters:

  • Safer to extend: You're adding code, not modifying existing code, so you're less likely to introduce bugs
  • Reduces coupling: New payment strategies don't need to know about PaymentProcessor
  • Scales to many variations: If you need 20 payment methods, you don't need a giant if/else chain

L — Liskov Substitution Principle (LSP)

Definition: Subtypes must be substitutable for their base types. If a function expects a Bird, it should work correctly with any subclass of Bird without knowing which specific type it is.

The Intuition:
If you write code that expects a Vehicle, you should be able to pass in a Car, a Truck, or a Motorcycle, and your code should work without special-casing each type.

The principle is named after Barbara Liskov, a computer scientist who formalized this concept.

Bad Example (A Classic Mistake):

java
// VIOLATES LSP: A Penguin is-a Bird, but it can't fly!

public class Bird {
    public void fly() {
        System.out.println("Bird is flying");
    }
}

public class Penguin extends Bird {
    @Override
    public void fly() {
        throw new UnsupportedOperationException("Penguins can't fly!");
    }
}

// Client code that expects a Bird:
public class Zoo {
    public void makeBirdsFly(Bird[] birds) {
        for (Bird bird : birds) {
            bird.fly(); // This throws an exception for Penguins!
            // The contract of Bird is violated.
        }
    }
}

Good Example:

java
// FOLLOWS LSP: We model the hierarchy correctly

public interface Bird {
    void move();
}

public class FlyingBird implements Bird {
    public void move() {
        System.out.println("Flying");
    }
}

public class Penguin implements Bird {
    public void move() {
        System.out.println("Swimming");
    }
}

// Client code doesn't make assumptions about HOW a bird moves
public class Zoo {
    public void moveBirds(Bird[] birds) {
        for (Bird bird : birds) {
            bird.move(); // Works for any Bird, including Penguin
        }
    }
}

Why It Matters:

  • Prevents surprises: You can use a subclass anywhere the parent type is expected without nasty surprises
  • Enables polymorphism: Polymorphism only works well when the contract is honestly fulfilled
  • Catches design errors: If you're violating LSP, it often means your inheritance hierarchy is wrong

I — Interface Segregation Principle (ISP)

Definition: Clients should not be forced to depend on interfaces they do not use. It's better to have many small, specific interfaces than one large, general-purpose interface.

The Intuition:
Imagine a universal remote that controls TVs, air conditioners, and microwaves. Your TV client only cares about power and volume, but it's forced to know about features for the air conditioner and microwave. That's bad design.

Better: Create separate, focused interfaces. A TV Remote interface has power and volume. An AC Remote interface has temperature controls.

Bad Example:

java
// VIOLATES ISP: Worker interface has too much

public interface Worker {
    void work();
    void eat();
    void sleep();
    void manage();
}

public class HumanWorker implements Worker {
    public void work() { /* ... */ }
    public void eat() { /* ... */ }
    public void sleep() { /* ... */ }
    public void manage() { /* not all humans are managers! */ }
}

public class Robot implements Worker {
    public void work() { /* ... */ }
    public void eat() { /* robots don't eat */ throw new UnsupportedOperationException(); }
    public void sleep() { /* robots don't sleep */ throw new UnsupportedOperationException(); }
    public void manage() { /* not all robots manage */ throw new UnsupportedOperationException(); }
}

Good Example:

java
// FOLLOWS ISP: Focused, segregated interfaces

public interface Workable {
    void work();
}

public interface Eatable {
    void eat();
}

public interface Sleepable {
    void sleep();
}

public interface Manageable {
    void manage();
}

public class HumanWorker implements Workable, Eatable, Sleepable {
    public void work() { /* ... */ }
    public void eat() { /* ... */ }
    public void sleep() { /* ... */ }
}

public class Manager implements Workable, Manageable {
    public void work() { /* ... */ }
    public void manage() { /* ... */ }
}

public class Robot implements Workable {
    public void work() { /* ... */ }
}

Why It Matters:

  • Reduces coupling: Classes only depend on what they actually use
  • More flexible: You can implement just the interfaces you need
  • Clearer contracts: Each interface has a clear, single purpose

D — Dependency Inversion Principle (DIP)

Definition: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.

The Intuition:
Imagine a light bulb connected directly to a generator with a hard-wired cable. If you want to use a different power source, you have to rewire everything. That's bad.

Better: Use a socket (the abstraction). The bulb plugs into the socket; the generator plugs into the socket. You can swap the generator without touching the bulb.

Bad Example:

java
// VIOLATES DIP: High-level PaymentProcessor depends on low-level CreditCard

public class CreditCard {
    public void charge(double amount) {
        System.out.println("Charging credit card: $" + amount);
    }
}

public class PaymentProcessor {
    private CreditCard creditCard; // Directly depends on concrete class!
    
    public PaymentProcessor(CreditCard creditCard) {
        this.creditCard = creditCard;
    }
    
    public void processPayment(double amount) {
        creditCard.charge(amount);
    }
}

// If we want to use PayPal, we have to modify PaymentProcessor!

Good Example:

java
// FOLLOWS DIP: Both depend on the abstraction

public interface PaymentMethod {
    void pay(double amount);
}

public class CreditCard implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Charging credit card: $" + amount);
    }
}

public class PayPal implements PaymentMethod {
    public void pay(double amount) {
        System.out.println("Processing PayPal: $" + amount);
    }
}

public class PaymentProcessor {
    private PaymentMethod paymentMethod; // Depends on abstraction!
    
    public PaymentProcessor(PaymentMethod paymentMethod) {
        this.paymentMethod = paymentMethod;
    }
    
    public void processPayment(double amount) {
        paymentMethod.pay(amount);
    }
}

// New payment methods are just new implementations. PaymentProcessor never changes.

Why It Matters:

  • Maximum flexibility: You can swap implementations without changing high-level code
  • Testability: You can inject a fake implementation for testing
  • Loose coupling: Changes to low-level details don't ripple up to high-level logic

Beyond SOLID: Three More Principles

While SOLID principles are the core, three other principles are equally important:


DRY — Don't Repeat Yourself

Definition: Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

In Plain English: Don't copy-paste code. Each piece of logic should exist in exactly one place.

Why It Matters:

  • Bug fixes propagate: Fix a bug in one place, and it's fixed everywhere that code is used
  • Changes are easier: Change the logic once; it's changed everywhere
  • Less to maintain: Fewer lines of code means fewer lines where bugs can hide

Example:

java
// BAD: Same validation logic repeated in three places
public class RegistrationForm {
    public boolean validateEmail(String email) {
        return email.contains("@");
    }
}

public class LoginForm {
    public boolean validateEmail(String email) {
        return email.contains("@");
    }
}

public class ProfileForm {
    public boolean validateEmail(String email) {
        return email.contains("@");
    }
}

// GOOD: Single source of truth
public class EmailValidator {
    public static boolean validate(String email) {
        return email.contains("@");
    }
}

public class RegistrationForm {
    public boolean validateEmail(String email) {
        return EmailValidator.validate(email);
    }
}

public class LoginForm {
    public boolean validateEmail(String email) {
        return EmailValidator.validate(email);
    }
}

public class ProfileForm {
    public boolean validateEmail(String email) {
        return EmailValidator.validate(email);
    }
}

KISS — Keep It Simple, Stupid

Definition: Most systems work best if they are kept simple rather than made complicated. Simplicity should be a key goal in design, and unnecessary complexity should be avoided.

Why It Matters:

  • Easier to understand: Future developers (including you in 6 months) can understand the code faster
  • Fewer bugs: Less code complexity means fewer places for bugs to hide
  • Faster development: Simple code is quicker to write and test

Example:

java
// COMPLEX (and unnecessary)
public int getValue() {
    return Optional.ofNullable(obj)
        .flatMap(o -> Optional.ofNullable(o.getField()))
        .map(f -> f.getValue())
        .orElseGet(() -> {
            try {
                return computeDefault();
            } catch (Exception e) {
                return fallback();
            }
        });
}

// SIMPLE and clear
public int getValue() {
    if (obj != null && obj.getField() != null) {
        return obj.getField().getValue();
    }
    try {
        return computeDefault();
    } catch (Exception e) {
        return fallback();
    }
}

The second version is more readable and achieves the same result.


YAGNI — You Ain't Gonna Need It

Definition: Always implement things when you actually need them, never when you just foresee that you might need them. Avoid "speculative development."

Why It Matters:

  • Reduces bloat: Features that aren't needed add complexity without value
  • Focuses effort: You spend time on what actually matters now, not imagined future needs
  • Easier to refactor: Less code means fewer places to update when requirements change

Example:

java
// BAD: Anticipating features that might never be needed
public class User {
    private String name;
    private String email;
    private List<String> allPreviousEmails; // "Users might change email"
    private List<Date> loginHistory; // "We might need analytics someday"
    private List<String> preferredLanguages; // "Users might be multilingual"
    private Map<String, Object> metadata; // "Just in case"
}

// GOOD: Implement what you actually need right now
public class User {
    private String name;
    private String email;
}

// If you later need to track email changes, add it then.

Why These Principles Matter: The Big Picture

Following SOLID, DRY, KISS, and YAGNI leads to systems that are:

Benefit How It's Achieved
Easier to understand Each part has a clear, single responsibility (SRP). No surprises.
Easier to maintain Changes are localized (DRY). You're not hunting through 10 files for the bug.
Easier to extend New features can be added without changing existing code (OCP).
More robust Components are interchangeable and behave as expected (LSP).
More flexible Dependencies are managed through abstractions (DIP). You can swap implementations.
Less buggy Less code duplication means fewer places for bugs to hide (DRY).
Simpler to reason about The code isn't over-engineered or speculative (KISS, YAGNI).

Interview Insight: How to Talk About Principles

When you're in an interview or code review and you want to explain a design decision:

✗ Weak: "I did this because it's cleaner."

✓ Strong: "I did this to follow the Open/Closed Principle. By depending on the PaymentStrategy interface rather than concrete classes, I can add new payment methods without modifying existing code."

✓ Strong: "I extracted this into a separate class to follow the Single Responsibility Principle. Now the User class only manages user data, and UserValidator handles validation. This makes both easier to test."

Naming the principle and explaining the benefit shows you understand why you made the choice, not just that you followed a pattern.


Concept Cluster 3: Object Relationships and Composition

Topics in this cluster:

  • 3.4 Composition over inheritance; Coupling and cohesion; Inheritance, composition, and aggregation
  • 3.5 Association and delegation; Encapsulation, abstraction, and polymorphism; Immutability and dependency management
Understanding Object Relationships

Objects in a system relate to each other in specific ways. Understanding these relationships is crucial to designing flexible systems.

The Four Key Relationships

1. Inheritance ("Is-A")

Definition: A subclass derives from a superclass, inheriting its public and protected members.

Symbol: Dog is-a Animal

Real-World Example: A penguin is a bird. A car is a vehicle.

Simple Code Example:

java
public class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dog is eating dog food");
    }
    
    public void bark() {
        System.out.println("Woof!");
    }
}

// Usage
Animal animal = new Dog();
animal.eat(); // Prints: Dog is eating dog food

When to Use:

  • When a true hierarchical relationship exists ("IS-A")
  • When you want to share common code (but see Composition as an alternative!)

When NOT to Use:

  • When the relationship is temporary or contextual
  • When a class needs multiple "is-a" relationships (Java doesn't support multiple inheritance)
  • When you're just trying to reuse code (use composition instead)

2. Composition ("Has-A", Strong Ownership)

Definition: An object is built from other objects. The composed objects are "owned" by the container, and their lifecycles are tied together.

Symbol: Car has-a Engine. If the Car is destroyed, the Engine is too (typically).

Real-World Example: A car has an engine. If the car is junked, the engine goes with it.

Simple Code Example:

java
public class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

public class Car {
    private Engine engine; // Car HAS-A Engine
    
    public Car() {
        this.engine = new Engine(); // Car owns the Engine
    }
    
    public void drive() {
        engine.start();
        System.out.println("Car is driving");
    }
}

// Usage
Car myCar = new Car();
myCar.drive();
// When myCar is destroyed, the engine is also destroyed (garbage collected)

When to Use:

  • When one object needs to use another object to function
  • When the contained object's lifetime is tied to the container
  • When you want to avoid the rigidity of inheritance

The "Composition Over Inheritance" Mantra:
Inheritance is tempting but often creates brittle designs. Composition is more flexible.


3. Aggregation ("Has-A", Weak Ownership)

Definition: A weaker form of composition. An object uses another, independent object, but the contained object can exist independently.

Symbol: Department has-a Professor. If the Department is disbanded, the Professors still exist and can work elsewhere.

Real-World Example: A university department has professors. If the department closes, the professors still exist and can work at other universities.

Simple Code Example:

java
public class Professor {
    private String name;
    
    public Professor(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

public class Department {
    private String name;
    private List<Professor> professors; // Department HAS-A list of Professors
    
    public Department(String name) {
        this.name = name;
        this.professors = new ArrayList<>();
    }
    
    public void addProfessor(Professor prof) {
        professors.add(prof); // Professors are added, not created by the Department
    }
    
    public void printProfessors() {
        for (Professor prof : professors) {
            System.out.println(prof.getName());
        }
    }
}

// Usage
Professor alice = new Professor("Alice");
Professor bob = new Professor("Bob");

Department cs = new Department("Computer Science");
cs.addProfessor(alice);
cs.addProfessor(bob);

// If the CS department is deleted, Alice and Bob still exist
Department math = new Department("Mathematics");
math.addProfessor(alice); // Alice can teach in multiple departments

When to Use:

  • When objects have independent lifecycles
  • When the same object can be "part of" multiple containers
  • When there's a "uses but doesn't own" relationship

4. Association (General Relationship)

Definition: A general relationship between two classes. The relationship is looser than composition or aggregation.

Symbol: Student is associated with Course

Real-World Example: A student takes a course. The relationship is real but less intimate than "owns" or "uses".

Simple Code Example:

java
public class Student {
    private String name;
    private List<Course> courses;
    
    public void enrollInCourse(Course course) {
        courses.add(course);
    }
}

public class Course {
    private String name;
    private List<Student> students;
    
    public void addStudent(Student student) {
        students.add(student);
    }
}

// Usage: Both classes know about each other, but neither owns the other

When to Use:

  • When objects interact or know about each other
  • When the relationship is not a "has-a" or "is-a"
  • When classes are peers rather than hierarchical

Delegation: Making Composition Work

Definition: An object forwards a request to another object (its delegate) to handle.

Delegation is the mechanism that makes composition powerful. Instead of inheriting behavior, an object asks another object to perform a behavior.

Example: Without Delegation (Inheritance):

java
public class Car {
    public void start() {
        // Car directly implements starting logic
        System.out.println("Car starts");
    }
}

public class Truck extends Car {
    // Truck inherits start() from Car
    // If the start logic changes, both Car and Truck are affected
}

Example: With Delegation (Composition):

java
public interface Engine {
    void start();
}

public class GasEngine implements Engine {
    public void start() {
        System.out.println("Gas engine starts");
    }
}

public class Car {
    private Engine engine; // Delegation: Car delegates starting to its engine
    
    public void start() {
        engine.start(); // Asking the delegate to do the work
    }
}

// Later, if we need an ElectricEngine, the Car class doesn't change
public class ElectricEngine implements Engine {
    public void start() {
        System.out.println("Electric engine starts silently");
    }
}

Car gasCar = new Car(new GasEngine());
Car electricCar = new Car(new ElectricEngine());

Why Delegation Matters:

  • Runtime flexibility: You can swap the delegate at runtime
  • No rigid hierarchies: You're not locked into a class hierarchy
  • Cleaner separation of concerns: Each object focuses on its job

Coupling and Cohesion: The Metrics of Good Design

Coupling: The degree to which components depend on each other. Low coupling is good.

Cohesion: The degree to which elements within a component belong together. High cohesion is good.

Simple Analogy:

  • Low Coupling: A car doesn't need to understand how to make steel; it just uses steel wheels. The car and steel factory are loosely coupled.
  • High Cohesion: All parts of a car's engine work together for a single purpose: generating power. They're tightly bound and belong together.

Bad Design (High Coupling, Low Cohesion):

java
public class OrderProcessor {
    // This class does EVERYTHING—low cohesion
    public void processOrder(Order order) {
        // Validate the order
        if (order.getTotal() < 0) throw new Exception("Invalid");
        
        // Apply discount
        double discount = order.getTotal() * 0.1;
        
        // Calculate tax
        double tax = (order.getTotal() - discount) * 0.08;
        
        // Charge the credit card—high coupling to CreditCard details
        CreditCard card = order.getCreditCard();
        if (!card.isValid()) throw new Exception("Invalid card");
        card.charge(order.getTotal() - discount + tax);
        
        // Send email
        Email email = new Email();
        email.setTo(order.getCustomer().getEmail());
        email.send("Order processed");
        
        // Log to database
        Database db = new Database();
        db.insert("orders", order);
    }
}

Good Design (Low Coupling, High Cohesion):

java
// Each class has ONE job (high cohesion)
public class OrderValidator {
    public void validate(Order order) { /* ... */ }
}

public class PricingService {
    public double calculateTotal(Order order) { /* ... */ }
}

public class PaymentProcessor {
    private PaymentMethod paymentMethod;
    public void charge(double amount) { /* ... */ }
}

public class NotificationService {
    public void notifyOrderProcessed(Order order) { /* ... */ }
}

// Main processor is simple (low coupling—depends on abstractions, not details)
public class OrderProcessor {
    private OrderValidator validator;
    private PricingService pricing;
    private PaymentProcessor payment;
    private NotificationService notification;
    
    public void processOrder(Order order) {
        validator.validate(order);
        double total = pricing.calculateTotal(order);
        payment.charge(total);
        notification.notifyOrderProcessed(order);
    }
}

Encapsulation, Abstraction, and Polymorphism

These three concepts are the pillars of OOP and make good design possible.


Encapsulation: Hide the Details

Definition: Bundling data (state) and methods (behavior) into a single unit (a class) and hiding the internal details from the outside world.

Rule of Thumb: Make fields private and provide public methods to interact with them.

Example:

java
// BAD: No encapsulation
public class BankAccount {
    public double balance; // Anyone can access and modify!
}

account.balance = -1000000; // Nothing stops this

// GOOD: Encapsulation
public class BankAccount {
    private double balance; // Hidden
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount; // Only valid operations allowed
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount; // Validation
        }
    }
    
    public double getBalance() {
        return balance;
    }
}

Why It Matters:

  • Protects invariants: You ensure that balance is never negative
  • Allows changes: You can change the internal representation without affecting clients
  • Enforces business rules: Withdrawals are validated

Abstraction: Hide Complexity

Definition: Showing only the essential features of an object while hiding the complex implementation details.

Example:

java
// Abstraction through an interface
public interface PaymentMethod {
    void pay(double amount); // Simple contract
}

// The implementation details are hidden
public class CreditCardPayment implements PaymentMethod {
    public void pay(double amount) {
        // Complex logic: encryption, API calls, error handling, retry logic
        // But the client just sees: paymentMethod.pay(100);
    }
}

Why It Matters:

  • Reduces cognitive load: You don't need to understand all the details
  • Allows specialization: Experts can handle complex implementations; others can use the simple interface
  • Supports change: Implementation details can change without affecting the interface

Polymorphism: One Interface, Many Forms

Definition: The ability of objects to take on many forms. Usually, a parent class reference can refer to objects of different subclasses.

Example:

java
public interface Shape {
    double getArea();
}

public class Circle implements Shape {
    private double radius;
    public double getArea() { return Math.PI * radius * radius; }
}

public class Rectangle implements Shape {
    private double width, height;
    public double getArea() { return width * height; }
}

// Polymorphism in action:
List<Shape> shapes = new ArrayList<>();
shapes.add(new Circle(5));
shapes.add(new Rectangle(4, 6));

double totalArea = 0;
for (Shape shape : shapes) {
    totalArea += shape.getArea(); // Same method call, different behavior!
}

Why It Matters:

  • Write generic code: You handle all types uniformly without special-casing each one
  • Extend without modification: Add new shape types without changing the loop
  • Cleaner architecture: High-level code doesn't need to know all low-level types

Immutability and Dependency Management

Immutability: Frozen State

Definition: An object's state cannot be modified after it is created.

Classic Example: String in Java is immutable.

java
// Immutable class
public final class ImmutableUser {
    private final String name;
    private final int age;
    
    public ImmutableUser(String name, int age) {
        this.name = name;
        this.age = age;
        // No setters!
    }
    
    public String getName() { return name; }
    public int getAge() { return age; }
}

// Once created, it cannot change
ImmutableUser user = new ImmutableUser("Alice", 25);
// user.name = "Bob"; // Compile error!

Why It Matters:

  • Thread safety: Immutable objects are inherently thread-safe
  • Predictability: An immutable object's state never changes, reducing bugs
  • Easy to reason about: You know the state of the object at any point

Dependency Management: Control What Objects Know About

Definition: Managing the dependencies (other classes, services, resources) that a component relies on.

Bad Approach (Direct Dependency):

java
public class ReportGenerator {
    private Database db = new Database(); // Hard-wired dependency
    
    public void generate() {
        Data data = db.query("SELECT ...");
        // Generate report
    }
}

// Problems:
// 1) Can't test without a real database
// 2) Can't swap the database for a different one

Good Approach (Dependency Injection):

java
public interface DataSource {
    Data query(String sql);
}

public class ReportGenerator {
    private DataSource dataSource; // Depend on abstraction
    
    public ReportGenerator(DataSource dataSource) {
        this.dataSource = dataSource; // Dependency is "injected"
    }
    
    public void generate() {
        Data data = dataSource.query("SELECT ...");
        // Generate report
    }
}

// Usage
ReportGenerator generator = new ReportGenerator(new RealDatabase());

// In tests
ReportGenerator testGenerator = new ReportGenerator(new FakeDatabase());

Why It Matters:

  • Testability: You can inject fake implementations for testing
  • Flexibility: Swap implementations without changing the code
  • Loose coupling: High-level code doesn't depend on low-level details

Concept Cluster 4: Refactoring and Code Smells

Topics in this cluster:

  • 3.6 Refactoring basics; Code smell detection; Replace conditionals; Extract abstraction; Introduce interfaces
What Is Refactoring?

Definition: Refactoring is the process of restructuring existing computer code—changing its internal structure—without changing its external behavior.

Key Insight: Refactoring preserves functionality while improving nonfunctional attributes like:

  • Readability
  • Maintainability
  • Testability
  • Flexibility
  • Performance

Why It's Important:
Code is read far more often than it's written. A piece of code might be written in 1 hour but read hundreds of times over its lifetime. Refactoring pays dividends by making the code easier to understand and maintain.

Code Smells: Red Flags That Suggest Refactoring

A code smell is a surface indication that usually points to a deeper problem. Smells don't always indicate a bug, but they're a signal that something might be wrong.


Common Code Smells

1. Long Method

  • Smell: A method is hundreds of lines long
  • Problem: Hard to understand, hard to test, likely doing multiple things
  • Fix: Extract Method—pull related code into smaller methods

2. Large Class

  • Smell: A class has too many responsibilities
  • Problem: Hard to understand, hard to test, violates SRP
  • Fix: Extract Class—create new classes to handle some responsibilities

3. Long Parameter List

  • Smell: A method takes 5+ parameters
  • Problem: Hard to call correctly, often indicates coupling to multiple concerns
  • Fix: Introduce Parameter Object—group related parameters into a single object

4. Duplicate Code

  • Smell: The same logic appears in multiple places
  • Problem: Violates DRY. Bugs fixed in one place aren't fixed elsewhere
  • Fix: Extract Method—create a shared method and call it from both places

5. Feature Envy

  • Smell: A method is more interested in another class than its own
  • Problem: Indicates poor organization and tight coupling
  • Example:
java
// Employee is envying the Department
public void giveBonus(Employee emp, Department dept) {
    double bonus = dept.getSalary() * 0.1; // Too much interest in dept!
    emp.setSalary(emp.getSalary() + bonus);
}

// Better: Give the method to Department
public void giveBonus(Employee emp) {
    double bonus = getSalary(emp) * 0.1;
    emp.setSalary(emp.getSalary() + bonus);
}

6. Switch Statements (Polymorph Smell)

  • Smell: A switch statement that checks an object's type
  • Problem: Violates OCP. Adding a new type means modifying the switch statement
  • Fix: Replace Conditional with Polymorphism—create subclasses or implementations instead

7. Data Class

  • Smell: A class that is just getters and setters, no real behavior
  • Problem: Indicates logic is elsewhere (feature envy), violates proper encapsulation
  • Fix: Move the logic that uses this data into the class itself

Refactoring Techniques: Tools for Improvement

1. Extract Method

When: You have a fragment of code that would be clearer as its own method

How:

java
// BEFORE
public void processOrder(Order order) {
    double total = order.getItems().stream()
        .mapToDouble(item -> item.getPrice() * item.getQuantity())
        .sum();
    double discount = total > 100 ? total * 0.1 : 0;
    double tax = (total - discount) * 0.08;
    System.out.println("Order total: $" + (total - discount + tax));
}

// AFTER
public void processOrder(Order order) {
    double total = calculateSubtotal(order);
    double discount = calculateDiscount(total);
    double tax = calculateTax(total, discount);
    printOrderTotal(total, discount, tax);
}

private double calculateSubtotal(Order order) {
    return order.getItems().stream()
        .mapToDouble(item -> item.getPrice() * item.getQuantity())
        .sum();
}

private double calculateDiscount(double total) {
    return total > 100 ? total * 0.1 : 0;
}

private double calculateTax(double total, double discount) {
    return (total - discount) * 0.08;
}

private void printOrderTotal(double total, double discount, double tax) {
    System.out.println("Order total: $" + (total - discount + tax));
}

Benefits: Easier to understand, test, and reuse each piece


2. Replace Conditional with Polymorphism

When: You have a switch or if/else chain that checks an object's type

How:

java
// BEFORE (Violates OCP)
public double getDamage() {
    switch (playerType) {
        case KNIGHT: return 15;
        case WIZARD: return 20;
        case ARCHER: return 12;
    }
}

// AFTER (Follows OCP)
public interface PlayerType {
    double getDamage();
}

public class Knight implements PlayerType {
    public double getDamage() { return 15; }
}

public class Wizard implements PlayerType {
    public double getDamage() { return 20; }
}

public class Archer implements PlayerType {
    public double getDamage() { return 12; }
}

public class Player {
    private PlayerType type;
    public double getDamage() {
        return type.getDamage();
    }
}

Benefits: New types can be added without modifying existing code; follows OCP


3. Extract Class

When: A class has too many responsibilities

How:

java
// BEFORE (Large class with multiple responsibilities)
public class User {
    private String name;
    private String email;
    
    public void calculatePay() { /* ... */ }
    public void saveToDB() { /* ... */ }
    public String generateReport() { /* ... */ }
}

// AFTER (Responsibilities separated)
public class User {
    private String name;
    private String email;
}

public class PaymentCalculator {
    public double calculatePay(User user) { /* ... */ }
}

public class UserRepository {
    public void save(User user) { /* ... */ }
}

public class UserReportGenerator {
    public String generate(User user) { /* ... */ }
}

Benefits: Each class is simpler, follows SRP, easier to test


4. Introduce Interface

When: You want to decouple a client from a specific implementation

How:

java
// BEFORE (Direct dependency on concrete class)
public class PaymentProcessor {
    private CreditCardProcessor processor = new CreditCardProcessor();
    
    public void process(double amount) {
        processor.process(amount);
    }
}

// AFTER (Depends on abstraction)
public interface PaymentGateway {
    void process(double amount);
}

public class CreditCardProcessor implements PaymentGateway {
    public void process(double amount) { /* ... */ }
}

public class PaymentProcessor {
    private PaymentGateway gateway;
    
    public PaymentProcessor(PaymentGateway gateway) {
        this.gateway = gateway;
    }
    
    public void process(double amount) {
        gateway.process(amount);
    }
}

Benefits: Easy to swap implementations; can inject fake for testing


Concept Cluster 5: The Unified Modeling Language (UML)

Topics in this cluster:

  • 3.7 Class diagrams; Sequence diagrams; Object diagrams
  • 3.8 State diagrams; Activity diagrams; Package diagrams
What Is UML?

UML (Unified Modeling Language) is a standardized, visual language for specifying, visualizing, constructing, and documenting the artifacts of software systems.

Think of UML as the "blueprint language" for software—just like architects use blueprints to show how a building will be structured before construction begins.

Why Learn UML?
  1. Communication: A diagram often communicates a design idea faster and clearer than paragraphs of text
  2. Documentation: Future developers can understand the structure at a glance
  3. Design Tool: Working through a design on paper (or whiteboard) often reveals problems before coding
  4. Common Language: Most software engineers understand UML, so it's a universal communication tool
UML Diagram Categories

UML diagrams fall into two main categories:

Structural Diagrams (Show static structure)

  • Class Diagram
  • Package Diagram
  • Object Diagram

Behavioral Diagrams (Show dynamic behavior)

  • Sequence Diagram
  • Activity Diagram
  • State Diagram

Key Diagram Types
1. Class Diagram

Purpose: Describes the structure of a system by showing classes, their attributes, operations, and relationships.

This is the most important and commonly used diagram for developers.

Key Elements:

+---------------------+
|   ClassName         |
+---------------------+
| - attribute: type   |  <- Fields (with visibility modifiers)
| + method(): return  |  <- Methods
+---------------------+

Visibility Modifiers:

  • + = public
  • - = private
  • # = protected
  • ~ = package-private

Example Class Diagram:

+----------+         +---------+
| Vehicle  |         | Car     |
+----------+         +---------+
| - brand  |         | - model |
| + start()|         | + drive()|
+----------+         +---------+
     ^
     |
  inherits

Relationships:

Inheritance (is-a): Empty arrow pointing to parent

Child ---|> Parent

Composition (has-a, strong): Filled diamond pointing to container

Car *-- Engine  (Car has 1 Engine)

Aggregation (has-a, weak): Empty diamond pointing to container

Department o-- Professor (Department has many Professors)

Example Full Diagram:

+---------+       +--------+
| Vehicle |       | Wheel  |
+---------+       +--------+
| -brand  |       | -size  |
+---------|---   |+rotate()|
| +start()        +--------+
| +stop()  |           ^
+---------+           | 1 to 4

Car ---|> Vehicle
Car *-- Wheel

2. Sequence Diagram

Purpose: Shows how objects interact with each other over time, and the order of those interactions.

Perfect for: Visualizing a specific use case or method call flow

Key Elements:

  • Actors/Objects: Boxes at the top
  • Lifelines: Vertical dashed lines representing the object's existence over time
  • Messages: Arrows showing interactions between objects

Example: Booking a Flight

Customer    ReservationSystem    PaymentProcessor
    |               |                    |
    |--booking----->|                    |
    |               |--validate------->|
    |               |<--valid---------|
    |               |--charge------->|
    |               |<--confirmed----|
    |<--confirm-----|

Real Code Scenario:

java
// This sequence diagram represents this code:
public void bookFlight(Flight flight) {
    // 1. Customer calls the system
    ReservationSystem sys = new ReservationSystem();
    
    // 2. System validates
    boolean valid = flight.validate();
    
    // 3. System charges
    PaymentProcessor processor = new PaymentProcessor();
    boolean charged = processor.charge(flight.getPrice());
    
    // 4. Return confirmation
}

3. State Diagram

Purpose: Describes the different states an object can be in and how it transitions between those states in response to events.

Perfect for: Modeling objects with complex lifecycles (e.g., order processing, authentication)

Example: User Authentication

[Logged Out] --login--> [Logged In] --logout--> [Logged Out]
                              |
                         --timeout-->
                              |
                         [Timed Out]

Real Scenario: Order Processing

[New Order] --validate--> [Validated] --payment--> [Paid]
    |
    +--invalid--> [Rejected]

[Paid] --ship--> [Shipped] --deliver--> [Delivered]

4. Activity Diagram

Purpose: Displays the workflow of a system, like a flowchart.

Perfect for: Modeling business processes or complex algorithms

Example: Order Processing

     Start
       |
       v
   [Place Order]
       |
       v
   [Validate]
     /    \
   Valid  Invalid
   /        \
  v          v
[Process]  [Reject]
  |          |
  |          +-----> [Notify Customer] --> End
  |
  v
[Ship]
  |
  v
[Deliver]
  |
  v
 End

Interview Insight: Whiteboard Confidence

You are not expected to be a UML expert. But being able to sketch a simple class diagram on a whiteboard to explain your design is a massive plus.

What shows mastery:
✓ Draw a basic class diagram showing inheritance and composition
✓ Explain what each arrow means
✓ Sketch a simple sequence diagram for a specific interaction
✓ Understand the difference between aggregation and composition

What you don't need to do:
✗ Draw perfect diagrams with perfect tools
✗ Remember every UML notation detail
✗ Draw comprehensive diagrams for large systems


Worked Examples

Worked Example 1: Designing a Payment Processor (SOLID Principles)

Problem or Design Scenario

Context: You're building an e-commerce platform. Initially, it only needs to handle credit card payments. But you know that soon, you'll need to support PayPal and Bank Transfers. The system should be easy to extend with new payment methods without modifying the core processor.

Challenge: Design it so that adding a new payment method only requires adding a new class, not modifying existing code.

Technical Value

This scenario directly tests your understanding of Open/Closed Principle and Dependency Inversion Principle. A naive solution will become a maintenance nightmare as you add more payment methods.

Analysis: What We Want to Achieve

✓ Adding a new payment method doesn't require modifying existing code (Open/Closed)
✓ The processor doesn't depend on concrete payment classes (Dependency Inversion)
✓ Each payment method is isolated (Single Responsibility)
✓ Easy to test with fake payment methods

Naive Approach (What NOT to Do)
java
// ❌ NAIVE APPROACH - Violates OCP and SRP
public class PaymentProcessor {
    public void processPayment(String method, double amount) {
        if (method.equals("credit")) {
            System.out.println("Processing credit card payment of $" + amount);
            // Validate credit card
            // Call credit card API
            // Handle response
            // TODO: Tons of complex logic here...
        } else if (method.equals("paypal")) {
            System.out.println("Processing PayPal payment of $" + amount);
            // OAuth flow
            // Call PayPal API
            // Handle PayPal-specific errors
            // TODO: Different complex logic...
        }
        // If we add Bank Transfer, we MUST modify this class!
    }
}

Problems with This Approach:

  1. Violates OCP: To add a new payment method, you must modify PaymentProcessor. It's closed for extension!
  2. Violates SRP: The class knows about credit cards, PayPal, and banks. That's three reasons for this class to change!
  3. Violates DIP: The high-level PaymentProcessor depends on low-level details (how to charge a credit card).
  4. Hard to test: You can't test without actual API calls. You can't inject a fake payment method.
  5. Error-prone: Every new method means searching through and modifying the existing method.
Better Approach: The Strategy Pattern

Key Idea: Extract the payment logic into separate classes (strategies). The processor depends only on an interface, not concrete classes.

java
// ✅ BETTER APPROACH - Follows OCP, DIP, and SRP

// 1. Define the abstraction (the contract all strategies must follow)
public interface PaymentStrategy {
    /**
     * Process a payment of the given amount.
     * @param amount The amount to charge
     * @throws PaymentException If the payment fails
     */
    void pay(double amount) throws PaymentException;
}

// 2. Create concrete strategies
public class CreditCardStrategy implements PaymentStrategy {
    private String cardNumber;
    private String expiryDate;
    private String cvv;
    
    public CreditCardStrategy(String cardNumber, String expiryDate, String cvv) {
        this.cardNumber = cardNumber;
        this.expiryDate = expiryDate;
        this.cvv = cvv;
    }
    
    @Override
    public void pay(double amount) throws PaymentException {
        // Validate card details
        if (!isValidCard()) {
            throw new PaymentException("Invalid card");
        }
        
        // Call the credit card processor API
        System.out.println("Charging $" + amount + " to credit card " + cardNumber);
        // In real code: callPaymentGatewayAPI(cardNumber, amount, cvv);
    }
    
    private boolean isValidCard() {
        // TODO: Real validation logic (Luhn algorithm, expiry check, etc.)
        return true;
    }
}

public class PayPalStrategy implements PaymentStrategy {
    private String email;
    private String password;
    
    public PayPalStrategy(String email, String password) {
        this.email = email;
        this.password = password;
    }
    
    @Override
    public void pay(double amount) throws PaymentException {
        // OAuth authentication
        System.out.println("Authenticating with PayPal account " + email);
        
        // Call PayPal API
        System.out.println("Processing $" + amount + " via PayPal");
        // In real code: callPayPalAPI(email, amount);
    }
}

public class BankTransferStrategy implements PaymentStrategy {
    private String accountNumber;
    private String routingNumber;
    
    public BankTransferStrategy(String accountNumber, String routingNumber) {
        this.accountNumber = accountNumber;
        this.routingNumber = routingNumber;
    }
    
    @Override
    public void pay(double amount) throws PaymentException {
        System.out.println("Processing $" + amount + " via bank transfer to account " + accountNumber);
        // In real code: callBankingAPI(accountNumber, routingNumber, amount);
    }
}

// 3. The high-level module depends only on the abstraction
public class PaymentProcessor {
    private PaymentStrategy paymentStrategy;
    
    /**
     * Constructor: Set the payment strategy
     * This demonstrates Dependency Injection
     */
    public PaymentProcessor(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }
    
    /**
     * Can also set the strategy after construction
     * Allows switching payment methods mid-session
     */
    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }
    
    /**
     * Process payment using the injected strategy
     * Notice: PaymentProcessor doesn't know HOW to pay
     * It just delegates to the strategy
     */
    public void processPayment(double amount) throws PaymentException {
        if (paymentStrategy == null) {
            throw new IllegalStateException("Payment strategy not set.");
        }
        paymentStrategy.pay(amount);
    }
}

// Custom exception for payment failures
public class PaymentException extends Exception {
    public PaymentException(String message) {
        super(message);
    }
    public PaymentException(String message, Throwable cause) {
        super(message, cause);
    }
}

// 4. Client code that uses the processor
public class ShoppingCart {
    public static void main(String[] args) throws PaymentException {
        // Scenario 1: Pay with Credit Card
        System.out.println("=== Scenario 1: Credit Card Payment ===");
        PaymentStrategy ccStrategy = new CreditCardStrategy("1234-5678-9012-3456", "12/25", "123");
        PaymentProcessor processor = new PaymentProcessor(ccStrategy);
        processor.processPayment(100.0);
        System.out.println();
        
        // Scenario 2: Pay with PayPal
        System.out.println("=== Scenario 2: PayPal Payment ===");
        PaymentStrategy payPalStrategy = new PayPalStrategy("user@example.com", "password");
        processor.setPaymentStrategy(payPalStrategy);
        processor.processPayment(50.0);
        System.out.println();
        
        // Scenario 3: Pay via Bank Transfer
        System.out.println("=== Scenario 3: Bank Transfer Payment ===");
        PaymentStrategy bankStrategy = new BankTransferStrategy("9876543210", "102938");
        processor.setPaymentStrategy(bankStrategy);
        processor.processPayment(200.0);
        System.out.println();
        
        // To add a new payment method (e.g., Apple Pay):
        // 1. Create a new class that implements PaymentStrategy
        // 2. Implement the pay() method
        // 3. Pass it to PaymentProcessor
        // NO CHANGES TO PaymentProcessor!
    }
}
Why the Better Approach Works

1. Open/Closed Principle:

  • Open for extension: To add Apple Pay, just create ApplePayStrategy and implement pay(). Done.
  • Closed for modification: PaymentProcessor never needs to change.

2. Dependency Inversion Principle:

  • High-level PaymentProcessor depends on the abstraction (PaymentStrategy)
  • Low-level details (CreditCardStrategy) also depend on the abstraction
  • Not the other way around

3. Single Responsibility Principle:

  • PaymentProcessor is responsible only for orchestrating the payment process
  • CreditCardStrategy is responsible only for credit card logic
  • PayPalStrategy is responsible only for PayPal logic

4. Testability:

java
// In your test file
public class PaymentProcessorTest {
    @Test
    public void testProcessPayment() {
        // Create a fake strategy for testing
        PaymentStrategy fakeStrategy = new PaymentStrategy() {
            public void pay(double amount) {
                System.out.println("Fake payment of $" + amount);
            }
        };
        
        PaymentProcessor processor = new PaymentProcessor(fakeStrategy);
        processor.processPayment(100); // No real API calls!
    }
}
Dry Run: Step-by-Step Execution

Let's trace through Scenario 2 above:

Input: payPalStrategy, amount = 50.0

1. processor.setPaymentStrategy(payPalStrategy)
   - paymentStrategy field is now set to the PayPalStrategy instance

2. processor.processPayment(50.0)
   - Check: paymentStrategy != null? YES, so continue
   - Call: paymentStrategy.pay(50.0)
   
3. Inside PayPalStrategy.pay(50.0):
   - Print: "Authenticating with PayPal account user@example.com"
   - Print: "Processing $50.0 via PayPal"
   - Return to caller

Output:
Authenticating with PayPal account user@example.com
Processing $50.0 via PayPal
Edge Cases and Robustness
  1. Null Strategy: The code throws an IllegalStateException if no strategy is set
  2. Invalid Amount: Strategies could validate that amount > 0
  3. Payment Failure: Strategies throw PaymentException if something goes wrong
  4. Switching Methods: You can call setPaymentStrategy() to switch payment methods mid-session

Worked Example 2: Designing a Notification System (Composition vs. Inheritance)

Problem or Design Scenario

Context: You're building a notification system. A basic Notifier can send emails. Soon, you need to add SMS and push notifications. Here's the twist: Users can choose any combination of channels. One user wants Email + SMS, another wants Email + Push, and yet another wants all three.

Challenge: Design it so users can mix and match notification channels without creating an explosion of classes.

Technical Value

This scenario highlights a critical weakness of inheritance: the class explosion problem. It shows why composition is a more flexible approach.

Analysis: Why Inheritance Fails

Let's see what happens if we try inheritance:

Notifier (base)
├── EmailNotifier
├── SmsNotifier
├── PushNotifier
├── EmailSmsNotifier
├── EmailPushNotifier
├── SmsPushNotifier
├── EmailSmsPushNotifier

We'd need 2^n classes for n notification types! With 5 types, that's 32 classes. With 10 types, that's 1024 classes. This is called the class explosion problem.

Naive Approach (Inheritance-Based)
java
// ❌ NAIVE APPROACH - Inheritance leads to class explosion

public class Notifier {
    public void send(String message) {
        System.out.println("Sending email: " + message);
    }
}

public class SmsNotifier extends Notifier {
    @Override
    public void send(String message) {
        super.send(message); // Send email
        System.out.println("Sending SMS: " + message);
    }
}

public class PushNotifier extends Notifier {
    @Override
    public void send(String message) {
        super.send(message); // Send email
        System.out.println("Sending Push: " + message);
    }
}

// What about Email + SMS + Push? We need another class...
public class AllNotifier extends SmsNotifier { // No! This doesn't inherit from PushNotifier
    @Override
    public void send(String message) {
        super.send(message); // Sends Email + SMS
        System.out.println("Sending Push: " + message);
    }
}

Problems:

  1. Class explosion: 2^n classes needed
  2. Rigidity: Behavior is fixed at compile time by the class type
  3. Code duplication: SMS logic might be duplicated in multiple classes
  4. Impossible combinations: Multiple inheritance isn't allowed in Java
  5. Inflexible: Can't decide at runtime to add/remove a channel
Better Approach: The Decorator Pattern

Key Idea: Treat additional channels as "decorations" that wrap around a base notifier. Each decorator adds its own behavior while delegating to the wrapped notifier.

java
// ✅ BETTER APPROACH - Composition with the Decorator Pattern

// 1. Define the core interface
public interface INotifier {
    void send(String message);
}

// 2. Base implementation
public class EmailNotifier implements INotifier {
    @Override
    public void send(String message) {
        System.out.println("Sending email: " + message);
    }
}

// 3. Base decorator class (optional but good practice)
public abstract class BaseDecorator implements INotifier {
    protected final INotifier wrappedNotifier;
    
    public BaseDecorator(INotifier notifier) {
        this.wrappedNotifier = notifier;
    }
    
    @Override
    public void send(String message) {
        wrappedNotifier.send(message);
    }
}

// 4. Concrete decorators
public class SmsDecorator extends BaseDecorator {
    public SmsDecorator(INotifier notifier) {
        super(notifier);
    }
    
    @Override
    public void send(String message) {
        super.send(message); // First, do what the wrapped notifier does
        System.out.println("Sending SMS: " + message); // Then, add our own behavior
    }
}

public class PushDecorator extends BaseDecorator {
    public PushDecorator(INotifier notifier) {
        super(notifier);
    }
    
    @Override
    public void send(String message) {
        super.send(message);
        System.out.println("Sending Push Notification: " + message);
    }
}

// 5. Client code composes the object at runtime
public class NotificationClient {
    public static void main(String[] args) {
        System.out.println("=== Scenario 1: Email Only ===");
        INotifier emailOnly = new EmailNotifier();
        emailOnly.send("Hello!");
        System.out.println();
        
        System.out.println("=== Scenario 2: Email + SMS ===");
        INotifier emailAndSms = new SmsDecorator(new EmailNotifier());
        emailAndSms.send("Important alert!");
        System.out.println();
        
        System.out.println("=== Scenario 3: Email + Push ===");
        INotifier emailAndPush = new PushDecorator(new EmailNotifier());
        emailAndPush.send("Update available!");
        System.out.println();
        
        System.out.println("=== Scenario 4: Email + SMS + Push ===");
        INotifier allChannels = new PushDecorator(new SmsDecorator(new EmailNotifier()));
        allChannels.send("System-wide broadcast!");
        System.out.println();
        
        // Easy to add more decorators
        System.out.println("=== Scenario 5: Email + SMS + Push + Custom ===");
        INotifier withCustom = new SlackDecorator(new PushDecorator(new SmsDecorator(new EmailNotifier())));
        withCustom.send("Multi-channel alert!");
    }
}

// Adding a new channel is just one new class!
public class SlackDecorator extends BaseDecorator {
    public SlackDecorator(INotifier notifier) {
        super(notifier);
    }
    
    @Override
    public void send(String message) {
        super.send(message);
        System.out.println("Sending Slack message: " + message);
    }
}
Why the Better Approach Works

1. No Class Explosion:

  • With 5 notification types, we need only 5 decorator classes + 1 base class = 6 total
  • Not 32 classes like with inheritance!

2. Runtime Flexibility:

  • You can decide at runtime what channels to use
  • You can even wrap a notifier multiple times

3. Single Responsibility:

  • Each decorator has one job: add one channel
  • Each is easy to understand and test

4. Open/Closed:

  • Adding a new channel means creating a new decorator
  • Existing code doesn't change
Dry Run: Step-by-Step Execution

Let's trace Scenario 4: Email + SMS + Push

allChannels = new PushDecorator(new SmsDecorator(new EmailNotifier()))

Structure:
PushDecorator
  └── wrappedNotifier: SmsDecorator
      └── wrappedNotifier: EmailNotifier

Execution: allChannels.send("System-wide broadcast!")

1. PushDecorator.send("System-wide broadcast!")
   - Calls: super.send("System-wide broadcast!")
   - Which calls: wrappedNotifier.send(...)
   
2. SmsDecorator.send("System-wide broadcast!")
   - Calls: super.send(...)
   - Which calls: wrappedNotifier.send(...)
   
3. EmailNotifier.send("System-wide broadcast!")
   - Prints: "Sending email: System-wide broadcast!"
   - Returns
   
4. Back in SmsDecorator:
   - Prints: "Sending SMS: System-wide broadcast!"
   - Returns
   
5. Back in PushDecorator:
   - Prints: "Sending Push Notification: System-wide broadcast!"
   - Returns

Output:
Sending email: System-wide broadcast!
Sending SMS: System-wide broadcast!
Sending Push Notification: System-wide broadcast!

Solved Problems

(For this foundational chapter, the "problems" are mini design scenarios rather than algorithmic challenges.)

Problem 1: Document Converter (Easy, Strategy Pattern)

Problem Statement

Design a simple document converter. A Converter object takes a file path and should be able to convert it to different formats. Initially, it supports converting to PDF. Soon, you'll need to add conversion to DOCX, HTML, PowerPoint, and other formats.

Requirement: Design the system so it's easy to add new formats without modifying the Converter class.

Solution Outline

This is a perfect fit for the Strategy Pattern (which we previewed in Worked Example 1).

Steps:

  1. Create a ConversionStrategy interface with a method String convert(String filePath)
  2. Create concrete strategy classes:
    • PdfConversionStrategy
    • DocxConversionStrategy
    • HtmlConversionStrategy
  3. The main Converter class will have:
    • setStrategy(ConversionStrategy strategy)
    • performConversion(String filePath) that delegates to the strategy
  4. This follows the Open/Closed Principle and Dependency Inversion

Key Insight: The Converter doesn't know how to convert. It just tells the strategy to do it.


Problem 2: User Authentication (Easy, Strategy Pattern)

Problem Statement

Design a user authentication module. The system needs to support:

  • Authentication via username/password
  • Authentication via Google Sign-In
  • Later: Facebook, GitHub, etc.

Requirement: Design so that adding a new authentication method doesn't require changing existing code.

Solution Outline

Another perfect fit for the Strategy Pattern.

Steps:

  1. Create an AuthenticationStrategy interface: boolean authenticate(Credentials creds)
  2. Create concrete strategies:
    • PasswordAuthStrategy
    • GoogleAuthStrategy
    • FacebookAuthStrategy (for later)
  3. The Authenticator class has:
    • setStrategy(AuthenticationStrategy strategy)
    • authenticate(Credentials creds) delegates to the strategy
  4. The system can switch authentication methods based on user choice or configuration

Key Benefits:

  • Each auth method is isolated and testable
  • Adding Google doesn't affect password authentication
  • Easy to mock for testing

Problem 3: Coffee Shop Orders (Medium, Decorator Pattern)

Problem Statement

Design a system to calculate the cost of a coffee order.

  • A basic coffee has a base cost (e.g., $2.00)
  • Customers can add extras like:
    • Milk: +$0.50
    • Sugar: +$0.25
    • Whipped Cream: +$0.75
    • Vanilla Syrup: +$0.50
  • Customers can add any combination of extras
  • The system should output both the description and the total cost

Example:

Coffee + Milk + Whipped Cream = $3.25
Description: "Black Coffee, with Milk, with Whipped Cream"
Solution Outline

This is a classic use case for the Decorator Pattern.

Steps:

  1. Create a Coffee interface with:
    • double getCost()
    • String getDescription()
  2. Create a SimpleCoffee class (the base):
    • getCost() returns the base price
    • getDescription() returns "Black Coffee"
  3. Create decorator classes for each extra:
    • MilkDecorator, SugarDecorator, etc.
    • Each wraps a Coffee object
    • Each decorator's getCost() returns wrappedCoffee.getCost() + extraCost
    • Each decorator's getDescription() returns wrappedCoffee.getDescription() + ", with Milk"
  4. Build the order by stacking decorators:
    java
    Coffee order = new MilkDecorator(new WhippedCreamDecorator(new SimpleCoffee()));
    System.out.println(order.getDescription() + ": $" + order.getCost());
    

Why Decorators Work Here:

  • Each extra is independent
  • You can combine them in any way
  • No "MilkAndWhippedCreamCoffee" class needed
  • Easy to add new extras

Problem 4: GUI Toolkit (Medium, Composite Pattern)

Problem Statement

Design a structure for a GUI toolkit. You have:

  • Leaf elements: Button, TextBox, Label
  • Containers: Panel, Window that can hold other elements (including other containers)

Requirement: You should be able to call render() on any element, and it should "just work" whether it's a leaf or a container with nested children.

Solution Outline

The Composite Pattern fits this structure because leaves and containers need the same outward interface.

Steps:

  1. Create a Component interface: void render()
  2. Create "leaf" classes like Button and TextBox:
    • Their render() method draws themselves
  3. Create "composite" classes like Panel:
    • Have a List<Component> children
    • Their render() method iterates through children and calls render() on each
  4. The beauty: You can treat a single Button and a Panel containing 10 buttons uniformly
    java
    List<Component> components = new ArrayList<>();
    components.add(new Button("Click me"));
    components.add(new Panel(/* ... nested components ... */));
    
    for (Component comp : components) {
        comp.render(); // Works for both Button and Panel!
    }
    

Why Composite Works Here:

  • No special-casing for containers vs. leaves
  • Nested structures are natural and easy
  • Adding a new component type doesn't break existing code

Problem 5: Undo/Redo Functionality (Hard, Command Pattern)

Problem Statement

Design the undo/redo functionality for a simple text editor.

  • The editor can perform actions like "insert text" and "delete text"
  • You need to undo a sequence of actions and then redo them
  • Each undo should reverse the most recent action
  • Redoing should re-apply the most recent undone action
Solution Outline

The Command Pattern fits this requirement because undo and redo need actions to be stored as explicit, reversible objects.

Steps:

  1. Create a Command interface with two methods:
    • void execute() - perform the action
    • void undo() - reverse the action
  2. Create concrete command classes:
    • InsertTextCommand(String text, int position): execute() inserts, undo() deletes
    • DeleteTextCommand(String text, int position): execute() deletes, undo() re-inserts
  3. The editor maintains two stacks:
    • undoStack: Commands that have been executed
    • redoStack: Commands that have been undone
  4. Workflow:
    • User types "Hello": Create InsertTextCommand("Hello", 0), call execute(), push to undoStack
    • User hits Undo: Pop from undoStack, call undo(), push to redoStack
    • User hits Redo: Pop from redoStack, call execute(), push to undoStack

Why Command Works Here:

  • Each action is encapsulated in an object
  • You can store, queue, and replay actions
  • Undo/Redo become simple stack operations
  • Easy to add new commands (MacroCommand, LoggingCommand, etc.)

Recognition Guide

Key Signals That You Need Better Design

This chapter is about the principles behind the patterns. The key is to recognize when your code is becoming rigid, brittle, or complex, and then use these principles to guide your refactoring.


Signal 1: Giant if/else or switch Chain

java
if (paymentMethod.equals("credit")) {
    // Process credit
} else if (paymentMethod.equals("paypal")) {
    // Process PayPal
} else if (paymentMethod.equals("bank")) {
    // Process bank
}
  • Principle Violated: Open/Closed Principle
  • Problem: Adding a new method requires modifying this method
  • Potential Solution: Replace Conditional with Polymorphism (Strategy Pattern)

Signal 2: Class Explosion from Inheritance

You need a new class for every possible combination of features:

  • EmailNotifier

  • SmsNotifier

  • EmailSmsNotifier

  • EmailPushNotifier

  • SmsPushNotifier

  • EmailSmsPushNotifier

  • Principle Violated: Open/Closed Principle, indicates inheritance-driven design

  • Problem: Exponential class growth; unmanageable

  • Potential Solution: Use Composition (Decorator or Strategy Pattern)


Signal 3: A Class Doing Too Much

java
public class User {
    // Business logic
    public double calculateBonus() { /* ... */ }
    
    // Database logic
    public void saveToDatabase() { /* ... */ }
    
    // Email logic
    public void sendEmail() { /* ... */ }
    
    // Reporting logic
    public String generateReport() { /* ... */ }
}
  • Principle Violated: Single Responsibility Principle
  • Problem: Class has multiple reasons to change
  • Potential Solution: Extract Class - Split into User, BonusCalculator, UserRepository, EmailService, ReportGenerator

Signal 4: High-Level Code Directly Depends on Low-Level Code

java
public class ReportGenerator {
    private DatabaseConnection db = new DatabaseConnection(); // Concrete class!
    
    public void generate() {
        Data data = db.query("SELECT ...");
    }
}
  • Principle Violated: Dependency Inversion Principle
  • Problem: Can't test without a real database; can't swap for a different database
  • Potential Solution: Introduce Interface - Depend on IDataSource, use dependency injection

Signal 5: Copy-Paste Code

You find the exact same block of code in three different places.

java
// In UserValidator
if (!email.contains("@")) throw new Exception("Invalid email");

// In RegistrationForm
if (!email.contains("@")) throw new Exception("Invalid email");

// In LoginForm
if (!email.contains("@")) throw new Exception("Invalid email");
  • Principle Violated: DRY (Don't Repeat Yourself)
  • Problem: Fix a bug in one place, but forget to fix the others
  • Potential Solution: Extract Method - Create EmailValidator.validate(email)

Design and Decision Making

Software is written by humans, for humans. Good design serves that reality.

Clean Code in Algorithm Problems

Even if you're solving a LeetCode problem, good design matters.

Bad:

java
public static int[] solve(String input) {
    // Parse the input
    String[] parts = input.split(",");
    int[] arr = new int[parts.length];
    for (int i = 0; i < parts.length; i++) {
        arr[i] = Integer.parseInt(parts[i]);
    }
    
    // Solve the problem
    // 200 lines of algorithm logic here mixed with output formatting
    
    // Format and return
}

Good:

java
public static void main(String[] args) {
    String input = "1,2,3,4,5";
    int[] arr = parseInput(input);
    int result = solve(arr);
    printResult(result);
}

private static int[] parseInput(String input) {
    // Parsing logic isolated
}

private static int solve(int[] arr) {
    // Pure algorithm logic, easy to test
}

private static void printResult(int result) {
    // Output logic isolated
}

Benefits:

  • Each method is testable independently
  • Easy to understand what each part does
  • Easy to reuse methods for different problems

Pragmatic Choice: Know When NOT to Apply Patterns

A pragmatic programmer knows that YAGNI (You Ain't Gonna Need It) is important. Don't apply a complex design pattern to a simple problem just to show you know it.

Example:

java
// If you only have 2 payment methods and you're 100% sure you'll never have more:
if (method.equals("credit")) {
    processCredit();
} else {
    processPayPal();
}

// This is FINE. It's simple, clear, and maintainable for the current context.

But:

java
// If you know you'll have 10+ payment methods, or if you know requirements will change:
// Use the Strategy Pattern. The complexity investment pays off.

The Key: Recognize when an assumption is likely to change. If it is, invest in flexibility.


API Design: Think Like a Library Author

When you write a helper class or data structure, think about its public API.

Bad API:

java
public class MyList {
    public int[] elements; // Exposed internal state!
}

list.elements[0] = -1000; // Allowed, even though it might violate invariants

Good API:

java
public class MyList {
    private int[] elements; // Hidden
    
    public int get(int index) { return elements[index]; }
    public void add(int value) { /* ... */ }
    public int size() { return elements.length; }
}

list.add(-1000); // If add() validates, we maintain invariants

Principles:

  • Encapsulate internal state (make it private)
  • Provide clear methods for interaction (get, add, remove, size)
  • Enforce business rules through your API

Testability: Design for Testing

Code that follows SOLID principles is almost always easier to test.

java
// Hard to test (tight coupling)
public class EmailService {
    private SmtpServer server = new SmtpServer(); // Hard-wired
    
    public void send(String to, String message) {
        server.send(to, message);
    }
}

// Easy to test (loose coupling, dependency injection)
public class EmailService {
    private MailServer server; // Injected
    
    public EmailService(MailServer server) {
        this.server = server;
    }
    
    public void send(String to, String message) {
        server.send(to, message);
    }
}

// In tests:
EmailService service = new EmailService(new FakeMailServer());
service.send("test@example.com", "Hello");
// No real emails sent; we're testing in isolation

Common Mistakes and How to Avoid Them

Mistake 1: Over-Engineering Simple Problems

  • Symptom: You've created 10 classes for a problem that could be solved in 2
  • Fix: Start simple. Refactor when complexity becomes real

Mistake 2: Premature Abstraction

  • Symptom: You're creating interfaces for everything, even when there's only one implementation
  • Fix: Only abstract when you have (or foresee) multiple implementations or a real need for decoupling

Mistake 3: Inheritance Hierarchies That Are Too Deep

  • Symptom: Animal > Mammal > Carnivore > Cat > PersianCat > BlackPersianCat
  • Fix: Prefer composition. Cat has behaviors, not a deep hierarchy

Mistake 4: Ignoring Testability

  • Symptom: Your code has hard-wired dependencies (like new DatabaseConnection()) scattered throughout
  • Fix: Use dependency injection; pass dependencies in via constructors or setters

4: Core Linear Structures

Introduction and Context

Arrays, strings, and hash-based lookups are the everyday tools of algorithm work. Later patterns like two pointers, sliding windows, and dynamic programming often look more advanced, but they still depend on the same core decisions you learn here: how to access data, what state to carry forward, and which repeated work can be avoided.

This chapter is really about choosing the right representation before writing the loop. Some problems want direct indexing, some want frequency lookup, some want cumulative state, and some want local rearrangement. The common failures are off-by-one boundaries, rebuilding strings inefficiently, using hashing without understanding equality, and recomputing ranges that could have been accumulated once.

Core Intuition and Mechanics

Think of linear structures as different ways of navigating one line of data.

  • An array is a numbered row of lockers: direct access is cheap, middle insertion is expensive.
  • A string is a sealed version of that row: reading is easy, but rebuilding is expensive unless you use mutable helpers like StringBuilder.
  • A HashMap is a keyed jump table: you pay hashing overhead to avoid repeated scanning.
  • A prefix sum is carried state: instead of recomputing every range, you store enough past work to answer future queries cheaply.

The important mechanics are access pattern and carried state. If you need instant position lookup, indexes dominate. If you need membership or counts, hashing dominates. If you need many range totals, prefix accumulation dominates. If you need local rearrangement, in-place swaps and reversals dominate. If you need the best contiguous result, algorithms like Kadane keep only the useful part of the past instead of carrying everything forward.

Once you see these as choices about what work to precompute, reuse, or discard, later patterns stop feeling like isolated tricks and start feeling like structured extensions of the same linear-data toolbox.

Core Concepts and Subtopics


Concept Cluster 1: Arrays — Traversal, Indexing, Mutation, and Rearrangement

Topics in this cluster:

  • Traversal and indexing patterns
  • Insertion and deletion
  • Searching and lookup strategies
  • Rotation and rearrangement problems
Definition

An array is a fixed-size, contiguous block of memory where every element is accessed by a zero-based integer index in O(1) time.

In Java, arrays are objects. The declaration int[] nums = new int[5] allocates space for exactly five integers on the heap. The length is fixed at creation. If you need a dynamic array, use ArrayList<Integer>.

Why It Matters

Arrays are the substrate of almost every other structure — heaps, segment trees, hash tables, queues, and stacks can all be built on top of arrays. If you understand array access patterns deeply, you understand the performance profile of everything built on top.

How It Works
Operation Array ArrayList
Random access by index O(1) O(1)
Append at end N/A (fixed) O(1) amortized
Insert at position i O(n) shift O(n) shift
Delete at position i O(n) shift O(n) shift
Search (unsorted) O(n) O(n)
Search (sorted, binary search) O(log n) O(log n)
Traversal Patterns

Forward traversal — the default:

java
for (int i = 0; i < nums.length; i++) {
    process(nums[i]);
}

Reverse traversal — useful for rotation and palindrome checks:

java
for (int i = nums.length - 1; i >= 0; i--) {
    process(nums[i]);
}

Two-index traversal — scanning from both ends (preview of Chapter 5):

java
int left = 0, right = nums.length - 1;
while (left < right) {
    // process pair nums[left], nums[right]
    left++;
    right--;
}

Index-safety rule: Always guard array access. The most common bug is an ArrayIndexOutOfBoundsException caused by off-by-one errors. If you access nums[i + 1], your loop condition must be i < nums.length - 1, not i < nums.length.

Insertion and Deletion

In a raw array, insertion at index k requires shifting elements k..n-1 one step to the right:

java
// Insert value at index k in array of current used size n
// (array must have capacity n+1)
for (int i = n; i > k; i--) {
    arr[i] = arr[i - 1];
}
arr[k] = value;

Deletion at index k shifts elements left:

java
for (int i = k; i < n - 1; i++) {
    arr[i] = arr[i + 1];
}
// Decrease n by 1 conceptually

Use ArrayList when you need frequent insertions or deletions; use raw arrays when size is fixed and performance is critical.

Searching and Lookup Strategies
  • Linear search: O(n). Scan every element. Use when unsorted or when the array is tiny.
  • Binary search: O(log n). Requires sorted array. Use Arrays.binarySearch(arr, target) or implement manually.
  • Hash-based lookup: O(1) average. Use a HashMap or HashSet when you need repeated "does element X exist?" queries.

Rule of thumb: If you search the same array more than once, preload it into a HashMap or HashSet and search in O(1) per query.

Rotation and Rearrangement

Array rotation is a classic interview topic. Rotating [1,2,3,4,5] right by 2 produces [4,5,1,2,3].

Reverse-based rotation — elegant O(n) time, O(1) space:

  1. Reverse the entire array.
  2. Reverse the first k elements.
  3. Reverse the remaining n-k elements.
java
import java.util.Arrays;

public class ArrayRotation {
    public static void rotate(int[] nums, int k) {
        int n = nums.length;
        k %= n; // handle k >= n
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

    private static void reverse(int[] nums, int left, int right) {
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        rotate(nums, 2);
        System.out.println(Arrays.toString(nums)); // [4, 5, 1, 2, 3]
    }
}

Dry run for rotate([1,2,3,4,5], 2):

  • After full reverse: [5,4,3,2,1]
  • After reverse first 2: [4,5,3,2,1]
  • After reverse last 3: [4,5,1,2,3] ✓
Common Mistakes
  • Off-by-one in loop bounds (most common bug in array code)
  • Using == to compare arrays; use Arrays.equals(a, b) instead
  • Forgetting k %= n before rotation, causing index out of bounds when k >= n
  • Mutating an array while iterating over it
Practical Note

Rotation problems often appear disguised: "shift elements right by k", "find the minimum in a rotated sorted array", or "search in a rotated sorted array." The reverse trick is the cleanest in-place rotation. Binary search on a rotated sorted array is a direct follow-up.


Concept Cluster 2: Strings — Fundamentals, Traversal, and Frequency Counting

Topics in this cluster:

  • Character arrays and string fundamentals
  • String traversal and frequency counting
Definition

In Java, a String is an immutable sequence of char values backed by a char[] internally. Immutability means every operation that appears to modify a string (like s + "x") actually creates a new String object. This is critical for performance.

A char in Java is a 16-bit Unicode code unit. For ASCII problems, characters fit within 'a'–'z' (26 values), 'A'–'Z', and '0'–'9'.

Why It Matters

String problems dominate technical interviews. Anagrams, palindromes, character windows, and tokenizing are everywhere. Understanding that strings are immutable — and that StringBuilder is the mutable alternative — is the difference between O(n) and O(n²) string building.

How It Works
java
String s = "hello";
char c = s.charAt(2);          // 'l'   — O(1)
int len = s.length();          // 5     — O(1)
String sub = s.substring(1,4); // "ell" — O(k) where k = length of substring

String concatenation in a loop creates a new object every iteration:

java
// BAD — O(n²) total work because each + copies the whole string so far
String result = "";
for (char ch : chars) {
    result += ch;
}

// GOOD — O(n) with StringBuilder
StringBuilder sb = new StringBuilder();
for (char ch : chars) {
    sb.append(ch);
}
String result = sb.toString();
Character-Array Traversal Template
java
String s = "abcabc";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    // process c
}
Frequency Counting with an Array

For lowercase-only problems, an int[26] is faster and lighter than a HashMap<Character,Integer>:

java
int[] freq = new int[26];
for (char c : s.toCharArray()) {
    freq[c - 'a']++;
}
// freq[0] = count of 'a', freq[1] = count of 'b', ...

For general characters (Unicode, digits, punctuation), use HashMap<Character, Integer>:

java
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) {
    freq.put(c, freq.getOrDefault(c, 0) + 1);
}
Clean Code Rules
  • Prefer s.toCharArray() in a for-each loop when you only need characters sequentially; it is readable and avoids repeated charAt calls.
  • Use int[26] for lowercase-only problems; it avoids HashMap overhead and is more cache-friendly.
  • Name the frequency array or map freq or count, not arr or map.
Common Mistakes
  • Calling s.toCharArray() inside a nested loop — this allocates a new array every call.
  • Comparing characters with == on Character objects (autoboxing pitfall) — always use char primitives when iterating.
  • Forgetting that s.substring(i,j) is exclusive of j.

Concept Cluster 3: Substrings, Subsequences, Palindromes, and Interview String Patterns

Topics in this cluster:

  • Substrings and subsequences
  • Palindrome problems
  • StringBuilder and mutable string workflows
  • Common interview string patterns
Substrings vs Subsequences
Concept Contiguous? Example (s="abcde")
Substring Yes "bcd" (indices 1–3)
Subsequence No "ace" (skip b,d)

A substring is a contiguous portion of the original string. There are O(n²) substrings in a string of length n.

A subsequence preserves relative order but allows gaps. There are O(2ⁿ) subsequences. Subsequences appear heavily in DP chapters (LCS, Edit Distance).

Palindrome Problems

A palindrome reads the same forwards and backwards: "racecar", "madam", "abcba".

Two-pointer palindrome check — O(n) time, O(1) space:

java
public static boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) return false;
        left++;
        right--;
    }
    return true;
}

Expand-around-center — useful for finding the longest palindromic substring:

java
public class LongestPalindrome {
    public static String longestPalindrome(String s) {
        int start = 0, maxLen = 1;
        for (int i = 0; i < s.length(); i++) {
            // Odd-length palindromes (center at i)
            int len1 = expand(s, i, i);
            // Even-length palindromes (center between i and i+1)
            int len2 = expand(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > maxLen) {
                maxLen = len;
                start = i - (len - 1) / 2;
            }
        }
        return s.substring(start, start + maxLen);
    }

    private static int expand(String s, int left, int right) {
        while (left >= 0 && right < s.length()
               && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad")); // "bab" or "aba"
        System.out.println(longestPalindrome("cbbd"));  // "bb"
    }
}
StringBuilder Workflows

Use StringBuilder whenever you build a string incrementally:

java
// Reverse a string — O(n), O(n) space
public static String reverse(String s) {
    return new StringBuilder(s).reverse().toString();
}

// Build a result string with condition
public static String keepDigits(String s) {
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()) {
        if (Character.isDigit(c)) sb.append(c);
    }
    return sb.toString();
}

Key StringBuilder methods:

  • append(x) — add to end
  • insert(i, x) — insert at index
  • delete(i, j) — remove range [i, j)
  • reverse() — reverse in place
  • toString() — produce final immutable String
Common Interview String Patterns
Pattern Problem Example
Anagram check Two strings are anagrams iff their sorted characters are equal, or their frequency arrays are equal
Valid parentheses Stack-based balance check
First unique character Frequency count → scan for freq == 1
Longest palindromic substring Expand around center
Reverse words in a string Split → reverse array → join
Is one string a rotation of another? Check if s2 is a substring of s1+s1
Practical Note

When a string problem mentions "all distinct characters" or "at most k distinct characters," it is usually a sliding window problem (Chapter 6). When it mentions "anagram" or "permutation exists in string," it is a sliding window with a frequency map. Recognizing these signals early saves enormous time.


Concept Cluster 4: HashMap and HashSet — Frequency Counter and Lookup Patterns

Topics in this cluster:

  • HashMap fundamentals
  • HashSet fundamentals
  • Frequency Counter Pattern
  • Hash Map Lookup Pattern
  • Frequency maps and counting patterns
Definition

A HashMap<K,V> stores key-value pairs. Every key is unique. Lookup, insertion, and deletion are O(1) average. In Java, HashMap is backed by an array of buckets; a hash function maps keys to bucket indices.

A HashSet stores unique elements with O(1) average contains/add/remove. It is effectively a HashMap where the value is always a dummy sentinel.

Why It Matters

Hash structures collapse many O(n) scan problems into O(1) lookups. The Two Sum problem is a standard example: naively O(n²) with nested loops, but O(n) with a HashMap. Any time you find yourself scanning an array inside another loop to find something, ask: "Could a map or set precompute this?"

Frequency Counter Pattern

Intuition: Count how many times each element appears, then reason about those counts.

java
import java.util.*;

public class FrequencyCounter {
    // Count frequencies
    public static Map<Integer, Integer> buildFreqMap(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : nums) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }
        return freq;
    }

    // Classic use: are two strings anagrams?
    public static boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] freq = new int[26];
        for (char c : s.toCharArray()) freq[c - 'a']++;
        for (char c : t.toCharArray()) freq[c - 'a']--;
        for (int count : freq) {
            if (count != 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("anagram", "nagaram")); // true
        System.out.println(isAnagram("rat", "car"));         // false
    }
}
Hash Map Lookup Pattern

Intuition: Store previously seen values in a map so you can answer "have I seen the complement of this element?" in O(1).

java
import java.util.*;

public class TwoSum {
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>(); // value -> index
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (seen.containsKey(complement)) {
                return new int[]{seen.get(complement), i};
            }
            seen.put(nums[i], i);
        }
        return new int[]{};
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{2,7,11,15}, 9)));
        // [0, 1]
    }
}

Dry run for twoSum([2,7,11,15], 9):

  • i=0, num=2, complement=7, seen={}, add {2→0}
  • i=1, num=7, complement=2, seen={2→0}, FOUND → return [0,1] ✓
Frequency Maps and Counting Patterns

Common counting idioms:

java
// Count occurrences and find first character with freq == 1
public static char firstUniqueChar(String s) {
    int[] freq = new int[26];
    for (char c : s.toCharArray()) freq[c - 'a']++;
    for (char c : s.toCharArray()) {
        if (freq[c - 'a'] == 1) return c;
    }
    return ' ';
}

// Top K frequent elements using frequency map + heap
import java.util.*;
public static int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int n : nums) freq.put(n, freq.getOrDefault(n, 0) + 1);
    // Min-heap of size k
    PriorityQueue<Integer> heap = new PriorityQueue<>(
        (a, b) -> freq.get(a) - freq.get(b)
    );
    for (int key : freq.keySet()) {
        heap.offer(key);
        if (heap.size() > k) heap.poll();
    }
    int[] result = new int[k];
    for (int i = k - 1; i >= 0; i--) result[i] = heap.poll();
    return result;
}
Clean Code Rules
  • Use getOrDefault(key, 0) instead of if (map.containsKey(key)) { ... } else { map.put(key,0); } — it is shorter and clearer.
  • Use map.merge(key, 1, Integer::sum) as an idiomatic Java 8+ frequency count.
  • Name your map freq, count, or something that describes what it counts. Do not name it map.

Concept Cluster 5: Hashing Internals — Collisions, equals/hashCode, and Pitfalls

Topics in this cluster:

  • Collision handling basics
  • Custom hashing and equality in Java
  • Common map-state mistakes and collision-style pitfalls
How HashMap Works Under the Hood

A HashMap stores entries in an array of buckets. When you call map.put(key, value):

  1. Java calls key.hashCode() to compute an integer.
  2. The integer is mapped to a bucket index (typically hash % capacity).
  3. The entry is placed in that bucket.

When two keys hash to the same bucket, that is a collision. Java handles collisions with separate chaining: each bucket holds a linked list (or, since Java 8, a balanced tree when the chain grows beyond 8 entries) of all entries that map to that bucket.

Load factor controls when the backing array is resized (default: 0.75). When the number of entries exceeds capacity * loadFactor, Java doubles the capacity and re-hashes everything. This resize is O(n) but happens rarely, so amortized insertion remains O(1).

Custom equals and hashCode in Java

If you use a custom object as a map key, you must override both equals and hashCode. They must be consistent: if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true.

java
import java.util.*;

public class Point {
    final int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Point)) return false;
        Point other = (Point) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y); // Delegates to a well-distributed hash
    }

    public static void main(String[] args) {
        Map<Point, String> map = new HashMap<>();
        map.put(new Point(1, 2), "origin");
        System.out.println(map.get(new Point(1, 2))); // "origin"
        // Without override, this would print null
    }
}
Common Map-State Mistakes
  1. Using mutable objects as keys: If you change a key after inserting it, the hash changes and the map can no longer find the entry.
  2. Forgetting to override hashCode when overriding equals: Java's contract says equal objects must have equal hash codes. Violating this makes the map silently lose entries.
  3. Checking map.get(key) != null instead of map.containsKey(key): If a null value is legitimately stored, get returning null is ambiguous.
  4. ConcurrentModificationException: Modifying a map while iterating its keySet() or entrySet(). Collect keys to modify first, then apply changes after.
java
// WRONG — throws ConcurrentModificationException
for (Integer key : map.keySet()) {
    if (someCondition) map.remove(key);
}

// CORRECT
Iterator<Map.Entry<Integer,Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<Integer,Integer> entry = it.next();
    if (someCondition) it.remove();
}
Practical Note

Interviewers sometimes ask "what is the worst-case complexity of HashMap?" The answer is O(n) if all keys collide (adversarial hash codes). In practice, Java's HashMap degrades chains to balanced trees in Java 8+, bounding the worst case to O(log n) per bucket. A well-implemented hashCode makes this a non-issue in practice.


Concept Cluster 6: Prefix Sums and Range Queries

Topics in this cluster:

  • Prefix sum arrays
  • One-dimensional prefix sums
  • Range sum queries
Definition

A prefix sum array pre for input array nums is defined as:

pre[0] = 0
pre[i] = nums[0] + nums[1] + ... + nums[i-1]

The sum of elements from index l to r (inclusive) is then:

rangeSum(l, r) = pre[r+1] - pre[l]

This reduces a range sum query from O(n) to O(1), after O(n) preprocessing.

Why It Matters

Any time you answer many "what is the sum of a range?" questions on a static array, prefix sums are the right tool. They also power sliding window, subarray sum, and hash-based range counting problems.

Java Implementation
java
public class PrefixSum {
    private final int[] pre;

    public PrefixSum(int[] nums) {
        pre = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            pre[i + 1] = pre[i] + nums[i];
        }
    }

    // Returns sum of nums[l..r] inclusive, 0-indexed
    public int rangeSum(int l, int r) {
        return pre[r + 1] - pre[l];
    }

    public static void main(String[] args) {
        PrefixSum ps = new PrefixSum(new int[]{3, 1, 4, 1, 5, 9, 2, 6});
        System.out.println(ps.rangeSum(1, 4)); // 1+4+1+5 = 11
        System.out.println(ps.rangeSum(0, 2)); // 3+1+4 = 8
    }
}

Dry run for [3,1,4,1,5,9,2,6]:

  • pre = [0, 3, 4, 8, 9, 14, 23, 25, 31]
  • rangeSum(1,4) = pre[5] - pre[1] = 14 - 3 = 11 ✓
Subarray Sum Equals K (prefix sum + hashing)

This classic problem asks: how many subarrays sum to exactly k?

Brute force: O(n²) — try all pairs.
Optimized: O(n) using prefix sums + frequency map.

Insight: If pre[j] - pre[i] == k, then the subarray nums[i..j-1] sums to k. Rearranging: pre[i] == pre[j] - k. So for each j, look up pre[j] - k in a frequency map of previously seen prefix sums.

java
import java.util.*;

public class SubarraySum {
    public static int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> prefixCount = new HashMap<>();
        prefixCount.put(0, 1); // empty prefix
        int prefixSum = 0, count = 0;
        for (int num : nums) {
            prefixSum += num;
            count += prefixCount.getOrDefault(prefixSum - k, 0);
            prefixCount.put(prefixSum, prefixCount.getOrDefault(prefixSum, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(subarraySum(new int[]{1, 1, 1}, 2)); // 2
        System.out.println(subarraySum(new int[]{1, 2, 3}, 3)); // 2
    }
}
Common Mistakes
  • Off-by-one in prefix sum indexing. Using pre[i] = nums[0]+...+nums[i] (length-n array) instead of pre[i+1] = nums[0]+...+nums[i] (length-n+1 array) makes the range formula harder and more error-prone. Prefer the length-n+1 convention shown above.
  • Forgetting to initialize prefixCount.put(0, 1) — this handles subarrays that start at index 0.

Concept Cluster 7: Difference Arrays, Prefix XOR, and Combining Prefix Data with Hashing

Topics in this cluster:

  • Difference arrays
  • Prefix XOR
  • Prefix XOR and accumulation variants
  • Combining prefix data with hashing
Difference Arrays

A difference array is the dual of a prefix sum: it allows you to apply range updates in O(1) and then reconstruct the final array in O(n).

Problem: Given an array, apply q range increment operations (add val to every element from l to r). Report the final array. With brute force each update is O(n); total O(n·q). With a difference array, each update is O(1) and final reconstruction is O(n): total O(n+q).

How it works:

  • diff[l] += val marks the start of the range.
  • diff[r+1] -= val marks where the increment ends.
  • After all operations, a prefix sum over diff gives the final array.
java
import java.util.Arrays;

public class DifferenceArray {
    public static int[] applyUpdates(int n, int[][] updates) {
        int[] diff = new int[n + 1];
        for (int[] u : updates) {
            int l = u[0], r = u[1], val = u[2];
            diff[l] += val;
            if (r + 1 <= n) diff[r + 1] -= val;
        }
        // Prefix sum over diff to rebuild array
        int[] result = new int[n];
        int running = 0;
        for (int i = 0; i < n; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }

    public static void main(String[] args) {
        // Array size 5, updates: [0,2,+3], [1,4,+2], [2,3,-1]
        System.out.println(Arrays.toString(
            applyUpdates(5, new int[][]{{0,2,3},{1,4,2},{2,3,-1}})
        ));
        // [3, 5, 4, 1, 2]
    }
}

Dry run:

  • diff after updates: [3, 2, -4, -1, 0, -2]
  • Prefix sum: 3, 5, 1, 0, 0 — wait, let me recompute cleanly:
    • diff=[0..5]: [3, 2, -4, -1, 0, -2]
      • update (0,2,3): diff[0]+=3 → diff[3]-=3
      • update (1,4,2): diff[1]+=2 → diff[5]-=2
      • update (2,3,-1): diff[2]-=1 → diff[4]+=1
    • diff = [3, 2, -1, -3, 1, -2]
    • prefix: 3, 5, 4, 1, 2 ✓
Prefix XOR

XOR has a powerful property: x XOR x = 0 and x XOR 0 = x. This means XOR is "self-canceling."

A prefix XOR array allows range XOR queries in O(1):

xorRange(l, r) = pre[r] ^ pre[l-1]

where pre[i] = nums[0] ^ nums[1] ^ ... ^ nums[i].

Classic use: Find the single non-duplicate element in an array where every element appears twice except one.

java
public class PrefixXOR {
    // Single non-duplicate using XOR accumulation
    public static int singleNumber(int[] nums) {
        int xor = 0;
        for (int num : nums) xor ^= num;
        return xor; // all duplicates cancel out
    }

    // Range XOR query in O(1) after O(n) build
    static int[] buildPrefixXOR(int[] nums) {
        int[] pre = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            pre[i + 1] = pre[i] ^ nums[i];
        }
        return pre;
    }

    static int rangeXOR(int[] pre, int l, int r) {
        return pre[r + 1] ^ pre[l];
    }

    public static void main(String[] args) {
        System.out.println(singleNumber(new int[]{4,1,2,1,2})); // 4

        int[] nums = {3, 5, 2, 8};
        int[] pre = buildPrefixXOR(nums);
        System.out.println(rangeXOR(pre, 1, 3)); // 5^2^8 = 15
    }
}
Combining Prefix Data with Hashing

This technique is the key to many "count subarrays with property X" problems.

Pattern:

  1. Compute prefix data (sum, XOR, product, parity, etc.).
  2. Store each prefix value in a HashMap<value → frequency>.
  3. For each position, look up the complement that would make the subarray satisfy the property.

Example: Count subarrays with XOR equal to k.

java
import java.util.*;

public class SubarrayXOR {
    public static int countSubarraysWithXOR(int[] nums, int k) {
        Map<Integer, Integer> prefixCount = new HashMap<>();
        prefixCount.put(0, 1);
        int prefixXOR = 0, count = 0;
        for (int num : nums) {
            prefixXOR ^= num;
            // If prefixXOR ^ prev == k, then prev == prefixXOR ^ k
            count += prefixCount.getOrDefault(prefixXOR ^ k, 0);
            prefixCount.put(prefixXOR, prefixCount.getOrDefault(prefixXOR, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countSubarraysWithXOR(new int[]{4, 2, 2, 6, 4}, 6)); // 4
    }
}
Practical Note

Prefix XOR + HashMap is the XOR analog of prefix sum + HashMap. Whenever you see "count subarrays where XOR equals k", apply this pattern directly. The structure of the solution is identical — only the operation changes from + to ^.


Concept Cluster 8: Kadane's Algorithm and Maximum Subarray Problems

Topics in this cluster:

  • Kadane's algorithm
  • Common interview warmups
Definition

Kadane's algorithm finds the maximum sum contiguous subarray in O(n) time and O(1) space. It is one of the most elegant and important algorithms in competitive programming.

Intuition

At each position, you make one decision: should the current subarray extend the best subarray seen so far, or should it start fresh with just the current element?

  • Extend if the running sum from the previous step is positive (it adds value).
  • Start fresh if the running sum is negative (it would only drag the new element down).
Algorithm
maxSum = nums[0]
currentSum = nums[0]

for i from 1 to n-1:
    currentSum = max(nums[i], currentSum + nums[i])
    maxSum = max(maxSum, currentSum)

return maxSum
Java Implementation
java
public class Kadane {
    public static int maxSubArray(int[] nums) {
        int maxSum = nums[0];
        int currentSum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            maxSum = Math.max(maxSum, currentSum);
        }
        return maxSum;
    }

    public static void main(String[] args) {
        System.out.println(maxSubArray(new int[]{-2,1,-3,4,-1,2,1,-5,4}));
        // 6 — subarray [4,-1,2,1]
        System.out.println(maxSubArray(new int[]{1}));       // 1
        System.out.println(maxSubArray(new int[]{-3,-1,-2})); // -1
    }
}

Dry run for [-2,1,-3,4,-1,2,1,-5,4]:

i nums[i] currentSum maxSum
0 -2 -2 -2
1 1 max(1,-1)=1 1
2 -3 max(-3,-2)=-2 1
3 4 max(4,2)=4 4
4 -1 max(-1,3)=3 4
5 2 max(2,5)=5 5
6 1 max(1,6)=6 6
7 -5 max(-5,1)=1 6
8 4 max(4,5)=5 6

Result: 6 ✓

Common Interview Warmups
Problem Key Idea
Maximum subarray sum Kadane's
Maximum product subarray Track both maxProduct and minProduct (negatives flip sign)
Maximum sum of circular subarray max(normalKadane, totalSum - minSubarrayKadane)
Find indices of maximum subarray Track start/end during Kadane's
Edge Cases
  • All-negative array: answer is the largest single element (most negative element is the least bad). The algorithm handles this correctly because currentSum = max(nums[i], currentSum+nums[i]) always picks at least nums[i].
  • Single-element array: return nums[0].
  • All zeros: return 0.
Common Mistakes
  • Initializing maxSum = 0 instead of maxSum = nums[0]. A zero initialization incorrectly returns 0 for all-negative arrays instead of the largest element.
  • Forgetting to reset currentSum by taking max(nums[i], currentSum + nums[i]) — some buggy implementations always extend, which breaks on all-negative inputs.

Worked Examples


Worked Example 1: Product of Array Except Self (Intermediate Array)

Problem or Design Scenario

Given an array nums, return an array output where output[i] is the product of all elements except nums[i]. Do not use division. Solve in O(n) time.

Technical Value

This problem directly tests prefix-product thinking — a generalization of prefix sums. It also tests whether you can use two passes (left prefix, right prefix) instead of extra space.

Constraints or Assumptions
  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • The answer fits in a 32-bit integer
Example Input/Output
  • Input: [1,2,3,4]
  • Output: [24,12,8,6]
Brute Force Approach

For each index i, multiply all elements except nums[i]. O(n²) time, O(1) extra space (not counting output).

Optimized Approach
  1. Build a left-prefix product array: left[i] = product of all elements to the left of i.
  2. Traverse from right, maintaining a running right-side product.
  3. Multiply left[i] * rightProduct for each position. O(n) time, O(1) extra space (beyond output array).
Why the Better Approach Works

Left products and right products each encode "everything except me" from one direction. Their product at position i excludes nums[i] from both sides.

Decision Process

"Two passes instead of a nested loop" is the general heuristic: precompute what you know from the left, then sweep from the right to combine. This avoids division (which would fail on zeros) and stays O(n).

Java Solution
java
import java.util.Arrays;

public class ProductExceptSelf {
    public static int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] output = new int[n];

        // Pass 1: output[i] = product of all elements left of i
        output[0] = 1;
        for (int i = 1; i < n; i++) {
            output[i] = output[i - 1] * nums[i - 1];
        }

        // Pass 2: multiply by product of all elements right of i
        int rightProduct = 1;
        for (int i = n - 1; i >= 0; i--) {
            output[i] *= rightProduct;
            rightProduct *= nums[i];
        }

        return output;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
            productExceptSelf(new int[]{1, 2, 3, 4})
        )); // [24, 12, 8, 6]
        System.out.println(Arrays.toString(
            productExceptSelf(new int[]{-1, 1, 0, -3, 3})
        )); // [0, 0, 9, 0, 0]
    }
}
Dry Run

Input: [1,2,3,4]

After pass 1: output = [1, 1, 2, 6]
Pass 2 (right to left):

  • i=3: output[3] = 6*1=6; rightProduct=4
  • i=2: output[2] = 2*4=8; rightProduct=12
  • i=1: output[1] = 1*12=12; rightProduct=24
  • i=0: output[0] = 1*24=24; rightProduct=24

Result: [24,12,8,6] ✓

Time and Space Complexity
  • Time: O(n)
  • Space: O(1) extra (output array not counted by convention)
Edge Cases
  • Array with zero: products for all non-zero positions become 0 except the zero position.
  • Two or more zeros: all positions are 0.
  • All ones: output is all ones.
Common Mistakes
  • Not initializing output[0] = 1 before the first pass.
  • Using division — breaks when nums[i] == 0.
  • Maximum product subarray (uses similar "track from both ends" idea).
  • Product of range queries on immutable array (use prefix product with division if no zeros guaranteed).
Validation

Test: [0,1,2,3], [1,0,0,1], single-element neighbors.


Worked Example 2: Group Anagrams (HashMap + String Frequency)

Problem or Design Scenario

Given an array of strings, group all strings that are anagrams of each other together.

Technical Value

This tests stable representation via a frequency key — the core of the Frequency Counter Pattern applied to grouping.

Constraints or Assumptions
  • All input strings are lowercase letters.
  • 1 ≤ strings.length ≤ 10⁴, 0 ≤ strings[i].length ≤ 100
Example Input/Output
  • Input: ["eat","tea","tan","ate","nat","bat"]
  • Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Brute Force Approach

Sort each string and use that as a key. Two strings that are anagrams produce the same sorted key.

Better Approach

Use a 26-character frequency count as the key. Slightly faster for short strings since sorting is O(k log k) vs O(k) for counting, though both are practical.

Java Solution
java
import java.util.*;

public class GroupAnagrams {
    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groups = new HashMap<>();
        for (String s : strs) {
            // Build canonical key from character frequency
            int[] freq = new int[26];
            for (char c : s.toCharArray()) freq[c - 'a']++;
            String key = Arrays.toString(freq); // "[1,0,0,...,1,0,...]"
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
        }
        return new ArrayList<>(groups.values());
    }

    public static void main(String[] args) {
        String[] input = {"eat","tea","tan","ate","nat","bat"};
        List<List<String>> result = groupAnagrams(input);
        for (List<String> group : result) {
            Collections.sort(group);
            System.out.println(group);
        }
    }
}
Dry Run
  • "eat" → freq key → group with "tea","ate"
  • "tan" → freq key → group with "nat"
  • "bat" → its own group
Time and Space Complexity
  • Time: O(n · k) where k = max string length
  • Space: O(n · k) for the map
Edge Cases
  • Empty string "" is an anagram of itself only.
  • Single-character strings each form their own group unless duplicated.
  • Count number of anagram groups.
  • Find anagram groups of exactly size k.

Worked Example 3: Maximum Sum Circular Subarray (Advanced Kadane's Variant)

Problem or Design Scenario

Given a circular array of integers, find the maximum sum of a non-empty contiguous subarray. The array is circular, meaning the subarray can wrap around the end and continue from the beginning.

Technical Value

This is an advanced Kadane's variant that requires insight: the optimal circular subarray is either (a) a normal subarray (handled by standard Kadane's) or (b) a "wrapped" subarray that equals totalSum - minSubarraySum.

Constraints
  • 1 ≤ nums.length ≤ 3 × 10⁴
  • -3 × 10⁴ ≤ nums[i] ≤ 3 × 10⁴
Example
  • Input: [1,-2,3,-2] → Output: 3
  • Input: [5,-3,5] → Output: 10
Intuition

A wrapped subarray = everything EXCEPT the minimum subarray in the middle. So:

  • maxWrap = totalSum - minSubarray
  • answer = max(maxNormal, maxWrap)

Special case: if all elements are negative, maxWrap = 0 (empty subarray), which would be invalid. Detect this with the all-negative check: if maxNormal < 0, return maxNormal.

Java Solution
java
public class MaxCircularSubarray {
    public static int maxSubarraySumCircular(int[] nums) {
        int totalSum = 0;
        int maxSum = nums[0], currentMax = nums[0];
        int minSum = nums[0], currentMin = nums[0];

        for (int i = 1; i < nums.length; i++) {
            totalSum += nums[i - 1];
            currentMax = Math.max(nums[i], currentMax + nums[i]);
            maxSum = Math.max(maxSum, currentMax);
            currentMin = Math.min(nums[i], currentMin + nums[i]);
            minSum = Math.min(minSum, currentMin);
        }
        totalSum += nums[nums.length - 1];

        // If all elements are negative, maxWrap is invalid (empty subarray)
        return maxSum > 0 ? Math.max(maxSum, totalSum - minSum) : maxSum;
    }

    public static void main(String[] args) {
        System.out.println(maxSubarraySumCircular(new int[]{1,-2,3,-2})); // 3
        System.out.println(maxSubarraySumCircular(new int[]{5,-3,5}));    // 10
        System.out.println(maxSubarraySumCircular(new int[]{-3,-2,-3}));  // -2
    }
}
Dry Run for [5,-3,5]
  • totalSum = 7
  • maxSum (Kadane's): 5 → 2 → 7, so maxSum=7
  • minSum (Kadane's min): 5 → -3 → -3+5=2... actually min at single element: minSum=-3
  • maxWrap = 7 - (-3) = 10
  • answer = max(7, 10) = 10 ✓
Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • All negative: maxSum < 0, return maxSum (the least-negative element).
  • Single element: works correctly.
  • Maximum product circular subarray (track min/max product simultaneously).

Solved Problems


Problem 1 (Easy): Find the Maximum in a Rotated Array

Problem Statement

Given a sorted array that has been rotated at an unknown pivot, find the maximum element.

Constraints
  • 1 ≤ nums.length ≤ 10⁵, all values distinct
Example

Input: [4,5,6,7,0,1,2] → Output: 7

Naive Solution

Linear scan: O(n).

Optimized Solution

Binary search: O(log n). The maximum is the last element before the rotation point. In a rotated sorted array, the minimum is the rotation point; maximum is one position before it.

Alternatively, for "find maximum": scan linearly but recognize that in a rotation problem, the maximum is at the rotation boundary.

Java Solution
java
public class MaxInRotated {
    public static int findMax(int[] nums) {
        int left = 0, right = nums.length - 1;
        // If not rotated, the last element is the max
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[right]) {
                // Max is in [mid+1, right] is wrong; max is in [left, mid]
                // Actually, for "find max", check differently:
                // If nums[mid] > nums[mid+1], mid is the max
                left = mid + 1; // not quite — let's use a clean approach
            } else {
                right = mid;
            }
        }
        // left now points to the minimum; max is just before it
        return nums[(left - 1 + nums.length) % nums.length];
    }

    // Cleaner: just find the minimum (rotation point), then max = arr[(minIdx-1+n)%n]
    public static int findMaxClean(int[] nums) {
        int n = nums.length;
        if (n == 1 || nums[0] < nums[n - 1]) return nums[n - 1]; // not rotated
        int left = 0, right = n - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[right]) left = mid + 1;
            else right = mid;
        }
        // left = index of minimum; max is right before it
        return nums[(left - 1 + n) % n];
    }

    public static void main(String[] args) {
        System.out.println(findMaxClean(new int[]{4,5,6,7,0,1,2})); // 7
        System.out.println(findMaxClean(new int[]{1,3,5}));          // 5
    }
}
Time and Space Complexity
  • Time: O(log n), Space: O(1)
Edge Cases
  • Non-rotated array: handled by early return.
  • Single element: returns that element.
  • Find minimum in rotated sorted array (symmetric problem — the inner binary search directly finds it).

Problem 2 (Easy): First Non-Repeating Character

Problem Statement

Given a string, find the index of the first character that does not repeat. Return -1 if none exists.

Example

Input: "leetcode" → Output: 0 (l appears once)
Input: "aabb" → Output: -1

Java Solution
java
public class FirstUnique {
    public static int firstUniqChar(String s) {
        int[] freq = new int[26];
        for (char c : s.toCharArray()) freq[c - 'a']++;
        for (int i = 0; i < s.length(); i++) {
            if (freq[s.charAt(i) - 'a'] == 1) return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(firstUniqChar("leetcode")); // 0
        System.out.println(firstUniqChar("loveleetcode")); // 2
        System.out.println(firstUniqChar("aabb")); // -1
    }
}
Time and Space Complexity
  • Time: O(n), Space: O(1) (array of size 26)
Edge Cases
  • All characters repeat → -1.
  • Single character → 0.

Problem 3 (Medium): Subarray Sum Equals K

Problem Statement

Given an integer array and an integer k, return the number of continuous subarrays whose sum equals k.

Example

Input: nums=[1,1,1], k=2 → Output: 2

Brute Force

Double loop: O(n²).

Optimized

Prefix sum + HashMap: O(n).

Java Solution
java
import java.util.*;

public class SubarraySumK {
    public static int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> prefixCount = new HashMap<>();
        prefixCount.put(0, 1);
        int prefixSum = 0, count = 0;
        for (int num : nums) {
            prefixSum += num;
            count += prefixCount.getOrDefault(prefixSum - k, 0);
            prefixCount.merge(prefixSum, 1, Integer::sum);
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(subarraySum(new int[]{1,1,1}, 2)); // 2
        System.out.println(subarraySum(new int[]{1,2,3}, 3)); // 2
        System.out.println(subarraySum(new int[]{-1,-1,1}, 0)); // 1
    }
}
Time and Space Complexity
  • Time: O(n), Space: O(n)
Edge Cases
  • Negative numbers: handled correctly because we're tracking prefix sums.
  • k=0: counts subarrays with zero sum.

Problem 4 (Medium): Longest Subarray of Ones After Deleting One Element

Problem Statement

Given a binary array (only 0s and 1s), return the length of the longest subarray containing only 1s after deleting exactly one element.

Example

Input: [1,1,0,1] → Output: 3

Brute Force

Try deleting each element, count longest run of 1s → O(n²).

Optimized

Difference array / prefix count approach: maintain count of 1s from left and from right for each position, combine at each 0.

Or: sliding window with a "budget" of one zero allowed — the window itself is covered in Chapter 6, but we can use a prefix sum approach here.

java
public class LongestOnesDeleteOne {
    public static int longestSubarray(int[] nums) {
        // prefix[i] = number of 1s in nums[0..i-1]
        int n = nums.length;
        int[] prefix = new int[n + 1];
        for (int i = 0; i < n; i++) {
            prefix[i + 1] = prefix[i] + nums[i];
        }
        int maxLen = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 0) {
                // Delete nums[i], count 1s on both sides
                int leftOnes = prefix[i] - prefix[0];      // ones in [0..i-1]
                // Actually we want the run adjacent to i on the right:
                // Use left endpoint = largest j < i with nums[j]==0 (or 0)
                // Simpler: just use two passes tracking gaps
            }
        }
        // Cleaner two-pointer / two-variable approach
        int left = 0, zeros = 0;
        maxLen = 0;
        for (int right = 0; right < n; right++) {
            if (nums[right] == 0) zeros++;
            while (zeros > 1) {
                if (nums[left] == 0) zeros--;
                left++;
            }
            // Subtract 1 because we must delete exactly one element
            maxLen = Math.max(maxLen, right - left);
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(longestSubarray(new int[]{1,1,0,1}));       // 3
        System.out.println(longestSubarray(new int[]{0,1,1,1,0,1,1,0,1})); // 5
        System.out.println(longestSubarray(new int[]{1,1,1}));         // 2
    }
}

Note: The two-pointer section in the solution above previews Chapter 5. The key insight from this chapter: the window shrinks when it contains more than one zero, and the final length subtracts 1 for the required deletion.

Time and Space Complexity
  • Time: O(n), Space: O(1)

Problem 5 (Hard): Minimum Window Substring (Preview — solved with frequency maps)

Problem Statement

Given strings s and t, return the minimum window substring of s that contains every character in t. If no such window exists, return "".

Example

Input: s="ADOBECODEBANC", t="ABC" → Output: "BANC"

Why It's Hard

You need to track character requirements and know when the window is "complete," then shrink it as much as possible.

Brute Force

O(n² · m): try all substrings, check each.

Optimized

Sliding window with two frequency maps and a "formed" counter: O(n + m).

java
import java.util.*;

public class MinWindowSubstring {
    public static String minWindow(String s, String t) {
        if (s.isEmpty() || t.isEmpty()) return "";

        Map<Character, Integer> need = new HashMap<>();
        for (char c : t.toCharArray()) need.merge(c, 1, Integer::sum);

        int required = need.size(); // distinct chars to satisfy
        int formed = 0;
        Map<Character, Integer> window = new HashMap<>();

        int left = 0;
        int minLen = Integer.MAX_VALUE;
        int minLeft = 0;

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            window.merge(c, 1, Integer::sum);

            if (need.containsKey(c) && window.get(c).equals(need.get(c))) {
                formed++;
            }

            // Try to contract the window until it's no longer valid
            while (formed == required) {
                if (right - left + 1 < minLen) {
                    minLen = right - left + 1;
                    minLeft = left;
                }
                char leftChar = s.charAt(left);
                window.merge(leftChar, -1, Integer::sum);
                if (need.containsKey(leftChar)
                        && window.get(leftChar) < need.get(leftChar)) {
                    formed--;
                }
                left++;
            }
        }
        return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen);
    }

    public static void main(String[] args) {
        System.out.println(minWindow("ADOBECODEBANC", "ABC")); // "BANC"
        System.out.println(minWindow("a", "a"));               // "a"
        System.out.println(minWindow("a", "aa"));              // ""
    }
}
Dry Run (abbreviated)

For s="ADOBECODEBANC", t="ABC":

  • Expand right until window has A, B, C → "ADOBEC" (valid)
  • Shrink left: remove 'A' → invalid, stop
  • Continue expanding... find "BANC" as minimum
Time and Space Complexity
  • Time: O(|s| + |t|)
  • Space: O(|s| + |t|)
  • Minimum window containing all distinct characters of s.
  • Smallest substring with all characters of t (exactly, not at-least).

Recognition Guide

When to Use Techniques from This Chapter

Signal Technique
"Find sum/count of elements in a range" Prefix sum
"Apply many range increment updates, then query final array" Difference array
"Count subarrays with sum/XOR equal to k" Prefix sum/XOR + HashMap
"Check if two strings are anagrams" Frequency array or sorted key
"Find elements with given property (exists? index?)" HashMap lookup
"Count occurrences of elements" Frequency Counter Pattern
"Maximum sum contiguous subarray" Kadane's algorithm
"Maximum sum in circular array" Kadane's + totalSum - minKadane
"Build result string incrementally" StringBuilder
"Search for element or complement in O(1)" HashSet or HashMap

When NOT to Use These Techniques

  • Prefix sums require a static array. If the array is updated between queries, use a Fenwick Tree or Segment Tree (Chapter 15).
  • HashMap lookup is O(1) average but has a constant factor. For tiny arrays (≤20 elements), a linear scan may outperform it in practice.
  • Kadane's solves the sum version. For the maximum product, count, or other objectives, the core loop changes.
  • Frequency maps are for counting. When order matters or you need contiguous structure, a sliding window (Chapter 6) is more appropriate.

Recognition Keywords

  • "subarray", "contiguous": think prefix sums, Kadane's, sliding window
  • "anagram", "permutation": frequency map
  • "complement", "pair", "two numbers that sum to": HashMap lookup
  • "range update", "range query on mutable array": difference array or segment tree
  • "XOR of range", "find single non-duplicate": prefix XOR
  • "palindrome": expand around center, two pointers

Comparison Tables

Array vs ArrayList

Dimension Array ArrayList
Size Fixed at creation Dynamic
Access by index O(1) O(1)
Insert/delete at middle O(n), manual shifting O(n), handles shifting
Memory Compact, no overhead Slightly more overhead
Java primitives Supported directly Requires boxing
Use case Fixed-size, performance-critical Dynamic, general purpose

int[26] Frequency Array vs HashMap

Dimension int[26] HashMap
Space 26 ints, constant Proportional to unique chars
Lookup speed Array index, extremely fast Hash function, slightly slower
Flexibility Lowercase only Any character type
Readability Less clear to beginners More self-documenting
Use case Lowercase a–z problems General character problems

Prefix Sum vs Difference Array

Dimension Prefix Sum Difference Array
Build time O(n) O(n)
Range query O(1) Requires rebuild: O(n)
Range update Rebuild needed: O(n) O(1) per update
Best for Many queries, no updates Many updates, then one query

String Searching Strategies

Strategy Time Notes
Naive contains O(n·m) Built into Java's contains
Sorted key anagram O(k log k) per string Simple, readable
Frequency array anagram O(k) per string Fastest for lowercase
Expand-around-center O(n²) total Palindromic substrings
KMP / Rolling Hash O(n+m) Chapter 25

Design and Decision Making

Keep Array Code Simple

Arrays are not where complexity should live. The complexity belongs in the algorithm. Keep array manipulation code (traversal, rotation, shifting) in small, named helper methods:

java
private static void reverse(int[] arr, int left, int right) { ... }
private static void swap(int[] arr, int i, int j) { ... }

This makes higher-level algorithms (rotation, partition) read like plain English.

Choose the Right Key Representation

When using maps for grouping (e.g., anagrams), the key design matters:

  • Sorted string key: simple, readable, O(k log k) per entry.
  • Arrays.toString(freq) key: O(k), more efficient, slightly less readable.
  • Custom object key: requires equals/hashCode override.

For production code, document why you chose a particular key format, especially for non-obvious canonicalization strategies.

Immutability and StringBuilder

Respect Java's string immutability design. The immutability of String enables safe sharing and caching (the JVM's string pool). When you need a mutable string, explicitly switch to StringBuilder. Do not fight the design; work with it.

Frequency Maps Are State Machines

A frequency map is really a lightweight state machine: each character's count is its state, and the algorithm transitions between states by incrementing/decrementing. Name the map to reflect this intent: remaining, need, freq, count. Avoid generic names like map or hashmap.

When to Use computeIfAbsent and merge

Java 8+ idioms:

  • map.computeIfAbsent(key, k -> new ArrayList<>()).add(value) — idiomatic grouping
  • map.merge(key, 1, Integer::sum) — idiomatic frequency increment
  • map.getOrDefault(key, 0) — safe read with default

Prefer these over verbose if (map.containsKey(k)) { ... } else { ... } blocks.


Practical Applications

Backend Systems

  • Prefix sums in time-series databases for range aggregations (e.g., analytics dashboards).
  • Frequency maps in log processing pipelines to count event types.
  • HashMap lookup in caches (e.g., request deduplication).

Databases

  • Difference arrays model the equivalent of range-update queries before a full-table scan.
  • Anagram grouping is used in query planners that normalize table name or column casing.

Distributed Systems

  • Kadane's algorithm inspires the "maximum profit window" calculations in trading systems.
  • Prefix XOR is used in distributed checksum computation (data integrity over ranges).

Text Processing

  • StringBuilder is the backbone of template engines, code generators, and serialization frameworks.
  • Frequency maps power spell-checkers and autocorrect engines.

Competitive Programming

Every algorithm from this chapter appears directly in competitive programming problems. Prefix sums + hashing alone unlocks dozens of problems that would otherwise require brute force or segment trees.


Failure Modes and Trade-offs

Senior Engineer Insights

  1. Prefix sums generalize to any associative operation with a neutral element: sum, XOR, product (with care for zeros), min/max (with segment trees). Once you internalize the pattern, you recognize it everywhere.

  2. HashMap collision attacks exist in adversarial inputs. Java 8+ mitigates this with tree buckets, but in security-critical code, consider a randomized hash or a TreeMap instead.

  3. String.intern() can reduce memory for large numbers of identical strings but is tricky to use correctly. Avoid it in interview problems; it is a micro-optimization.

  4. Kadane's algorithm is a special case of DP. The currentSum variable is a DP state where dp[i] = maximum subarray sum ending at index i. Recognizing this connection makes it easier to generalize (e.g., 2D Kadane's for maximum submatrix sum).

Performance Tuning

  • For frequency counting of a large stream, int[26] is significantly faster than HashMap<Character,Integer> due to cache locality and lack of boxing.
  • For prefix sums on large arrays, ensure you use long instead of int when element values can cause overflow.
  • StringBuilder.append in a loop is O(n) amortized because it doubles capacity. Specify initial capacity via new StringBuilder(estimatedSize) when you know the target size.

Interview Traps

  1. All-negative array with Kadane's: If you initialize maxSum = 0, you get the wrong answer. Always initialize from nums[0].
  2. Subarray sum equals k with negatives: Prefix sum + HashMap works; sliding window does NOT (shrinking window does not reliably reduce the sum when negatives exist).
  3. Circular subarray maximum: The wrapped case requires totalSum - minSubarraySum, not a direct application of standard Kadane's.

Condensed Notes

Array Rules

  • int[] is fixed size; use ArrayList for dynamic resizing.
  • Index guard: access nums[i+1] only when loop condition is i < nums.length - 1.
  • Rotation by k: reverse all → reverse [0,k-1] → reverse [k,n-1]. Always do k %= n first.

String Rules

  • Java strings are immutable; always use StringBuilder for incremental construction.
  • s.charAt(i) is O(1). s.substring(l,r) is O(r-l).
  • Anagram check: int[26] frequency array, check all zeros after subtracting.

HashMap Rules

  • getOrDefault(key, defaultValue) for safe reads.
  • merge(key, 1, Integer::sum) for frequency increment.
  • computeIfAbsent(key, k -> new ArrayList<>()) for grouping.
  • Override equals AND hashCode together, always.

Prefix Sum Formula

pre[0] = 0
pre[i+1] = pre[i] + nums[i]
rangeSum(l, r) = pre[r+1] - pre[l]

Initialize prefixCount.put(0, 1) for subarray-count problems.

Difference Array Formula

diff[l] += val
diff[r+1] -= val
Rebuild: running prefix sum over diff[]

Prefix XOR

pre[i+1] = pre[i] ^ nums[i]
rangeXOR(l, r) = pre[r+1] ^ pre[l]
Subarray XOR = k: look up (prefixXOR ^ k) in map

Kadane's Template

java
int maxSum = nums[0], cur = nums[0];
for (int i = 1; i < n; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    maxSum = Math.max(maxSum, cur);
}

Decision Shortcuts

  • Range sum query, static array → prefix sum
  • Range update, one final query → difference array
  • Subarray count with property → prefix + HashMap
  • Two elements summing to target → HashMap lookup
  • Anagram / character count → int[26] or frequency map
  • Max sum contiguous → Kadane's
  • Max sum circular → Kadane's + totalSum - minKadane

Additional Problems

Easy

  1. Reverse Array In-Place — Reverse [1,2,3,4,5] without extra space. Pattern: two-pointer swap.

  2. Contains Duplicate — Return true if any value appears twice. Pattern: HashSet membership check.

  3. Running Sum of 1D Array — Return prefix sums of [1,2,3,4] as [1,3,6,10]. Pattern: prefix sum build.

  4. Valid Anagram — Check if two strings are anagrams. Pattern: int[26] frequency counter.

  5. Single Number — Find the one non-duplicate in an array where all others appear twice. Pattern: XOR accumulation.

Medium

  1. Two Sum — Return indices of two numbers that sum to a target. Pattern: HashMap lookup.

  2. Subarray Sum Equals K — Count subarrays summing to k (with negatives). Pattern: prefix sum + HashMap.

  3. Find All Anagrams in a String — Find all start indices of anagram substrings. Pattern: sliding frequency window.

  4. Range Sum Query — Immutable — Answer multiple range sum queries. Pattern: prefix sum precomputation.

  5. Rotate Array — Rotate array right by k positions in O(1) space. Pattern: three-step reverse.

Hard

  1. Minimum Window Substring — Smallest window in s containing all characters of t. Pattern: frequency map + expand/contract window.

  2. Subarray XOR Equal to K — Count subarrays with XOR equal to k. Pattern: prefix XOR + HashMap.

  3. Maximum Sum Circular Subarray — Max subarray sum in a circular array. Pattern: Kadane's + totalSum - minKadane.

  4. Longest Subarray with Equal Number of 0s and 1s — Replace 0 with -1, find longest zero-sum subarray. Pattern: prefix sum + HashMap (first occurrence).

  5. Corporate Flight Bookings — Given n flights and booking intervals, compute total seats for each flight. Pattern: difference array.


Key Questions

Q1: What is the time complexity of accessing an element in a Java array vs a HashMap?

Array access is O(1) with guaranteed constant time — it's a direct memory index calculation. HashMap access is O(1) amortized average, but in the worst case (all keys collide into one bucket), it degrades to O(n), or O(log n) in Java 8+ due to tree-based bucket fallback.


Q2: Why should you use StringBuilder instead of string concatenation in a loop?

Java strings are immutable. Each += operation creates a new String object and copies all existing characters. In a loop of n iterations building a string of length n, this results in O(n²) total work. StringBuilder uses a mutable buffer and doubles capacity as needed, giving O(n) amortized time for the entire build.


Q3: Walk me through how you would check if two strings are anagrams without sorting.

Build an int[26] frequency array. Increment for each character in string one, decrement for each character in string two. If all entries are zero at the end, the strings are anagrams. This is O(n) time and O(1) space — better than the O(n log n) sort-based approach.


Q4: What is the prefix sum formula for range queries, and why does it work?

Build pre where pre[i+1] = pre[i] + nums[i] and pre[0] = 0. Then rangeSum(l, r) = pre[r+1] - pre[l]. This works because pre[r+1] accumulates all elements from index 0 to r, and subtracting pre[l] removes the contribution of elements 0 to l-1, leaving exactly the sum from l to r.


Q5: Explain Kadane's algorithm in one minute.

Kadane's scans from left to right and maintains currentSum = the maximum subarray sum ending at the current index. At each step, you either extend the previous subarray (add the current element to currentSum) or start fresh (the current element alone). You take the max of these two choices. Simultaneously you track the global maxSum. This works because extending is only useful if currentSum was positive; otherwise starting fresh gives a better foundation.


Q6: When does prefix sum + HashMap fail for subarray sum problems?

Prefix sum + HashMap works correctly even with negative numbers. However, sliding window fails for subarray sum problems with negatives because contracting the window from the left does not guarantee the sum decreases. Always use prefix sum + HashMap when elements can be negative.


Q7: What does overriding only equals without hashCode break in a HashMap?

Java's contract requires that equal objects have equal hash codes. If you override equals but not hashCode, two objects that are logically equal will compute different hash codes, land in different buckets, and the map will not find the entry when you look it up. You get a silent bug where map.get(key) returns null even though the key was inserted.


Q8: How would you handle Kadane's algorithm when all elements are negative?

Initialize maxSum = nums[0] and currentSum = nums[0], not to 0. The algorithm naturally picks the "least negative" single element as the maximum. Initializing to 0 would incorrectly return 0 for an all-negative input (implying an empty subarray, which is not allowed by the problem statement requiring a non-empty subarray).


Q9: What is a difference array and when do you use it?

A difference array supports O(1) range increment updates. You record diff[l] += val and diff[r+1] -= val for each update. After all updates, a single prefix sum pass reconstructs the final array. Use it when you have many range updates to apply on a static array, and you only need the final values rather than intermediate queries.


Q10: How do you count subarrays with XOR equal to k?

Use prefix XOR + HashMap — the exact same structural pattern as prefix sum + HashMap for sum-equals-k. Compute running XOR. For each prefix XOR value p, check how many times p ^ k has appeared before (because prevXOR ^ subXOR = k implies prevXOR = p ^ k). Store each prefix XOR value in a frequency map and look up the complement at each step.


Applied Project

Objective

Build a Range Analytics Engine that supports the following operations over a sequence of integer values:

  1. Answer multiple range sum queries after loading data.
  2. Apply batch range increment updates (e.g., "add 5 to all elements from index 2 to 7").
  3. Find the maximum-sum contiguous segment.
  4. Given a second sequence, group elements that are "value-anagrams" (same multiset of digits when each number is converted to its digit string).
  5. Count how many subarrays have a sum equal to a user-specified target.

Required Features

  • loadData(int[] nums) — load the array.
  • rangeSum(int l, int r) — O(1) query using prefix sums.
  • applyUpdates(int[][] updates) — apply all updates using a difference array, then rebuild prefix sums.
  • maxSubarraySum() — returns result via Kadane's algorithm.
  • countSubarraysWithSum(int k) — uses prefix sum + HashMap.
  • groupByValueAnagram(int[] nums) — groups numbers by their sorted-digit signature.

Suggested Java Module Structure

RangeAnalyticsEngine.java   // main engine class
  - int[] data
  - int[] prefixSums
  - void loadData(int[])
  - int rangeSum(int, int)
  - void applyUpdates(int[][])
  - int maxSubarraySum()
  - int countSubarraysWithSum(int)

AnagramGrouper.java         // separate concern: grouping
  - Map<String, List<Integer>> groupByValueAnagram(int[])

RangeAnalyticsEngineTest.java  // unit tests

Testing Ideas

  • Load [3,1,4,1,5,9,2,6,5,3] and verify range sums.
  • Apply [(1,4,+2), (2,6,-1)] and verify final array.
  • Verify Kadane's result matches expected maximum subarray.
  • Test countSubarraysWithSum with negative values and k=0.
  • Group [12, 21, 11, 100, 001] and verify anagram groupings.

Stretch Goals

  • Support 2D range sum queries (sum in rectangle).
  • Replace prefix sums with a Fenwick Tree to support point updates between queries.
  • Add streaming mode: process elements one at a time and maintain a running Kadane's state.

5: Two Pointer Family

Introduction and Context

Two pointers is the first major pattern where optimization starts to look systematic instead of lucky. Rather than rescanning every possible pair or region, you preserve a relationship between moving positions and let that relationship eliminate work. The speedup comes from monotonic movement: each step rules out many impossible answers without revisiting the same state.

The technique is powerful, but only when the invariant is real. Opposite-direction pointers usually need ordering. Same-direction pointers need a well-defined write boundary or valid region. Fast/slow pointers need a structural reason that relative speed reveals information. Most bugs come from moving the wrong pointer, using the pattern without the required guarantee, or failing to define what is true before and after each move.

Core Intuition and Mechanics

The Core Idea: Two Scouts on a Trail

Imagine a hiking trail (your array) with two scouts. You send them out to find something:

  • Opposite-direction scouts: one starts at the trailhead (left), the other at the summit (right). They walk toward each other. When they meet, the search is complete. This works on sorted arrays.
  • Same-direction scouts: both start at the trailhead. One walks faster or jumps ahead. The slower one holds a "position of interest." This works on unsorted arrays and is used to partition, deduplicate, or find windows.
  • Fast and slow scouts: one takes two steps for every one step the other takes. If there is a loop in the trail, the fast scout will lap the slow one. This is cycle detection.

What Makes the Pattern Work

  • Opposite-direction pointers work because ordering lets one comparison discard many impossible pairs.
  • Same-direction pointers work because one pointer marks a stable prefix or a valid region while the other explores new state.
  • Fast/slow pointers work because relative speed exposes hidden structure such as cycles or middle positions.
  • Reversal and partition variants work because each swap or rewrite preserves a growing invariant about which part of the data is already fixed.

Before coding, define four things explicitly: the invariant, the movement rule, the termination rule, and the edge cases. If one of those is fuzzy, the implementation usually becomes a collection of off-by-one repairs instead of a clean linear scan.


Core Concepts and Subtopics


Concept Cluster 1: Two Pointers Pattern and Opposite-Direction Pointers

Topics in this cluster:

  • 5.1 Two Pointers Pattern
  • 5.1 Opposite-direction pointers

Definition

The Two Pointers Pattern maintains two index variables — usually called left and right (or lo and hi, or i and j) — that move through a data structure. Pointer movement is driven by a condition evaluated at each step. The pattern replaces an inner loop, reducing O(n²) to O(n).

Opposite-direction pointers start at opposite ends of an array and converge toward the center. They are most useful when the array is sorted and you are searching for a pair, trio, or partition boundary.


Why It Matters

The brute force for pair-sum on a sorted array checks every pair: O(n²). With two opposite-direction pointers, you scan once: O(n). The sorted order lets you reason: if the current pair sum is too small, move left right; if too large, move right left. You eliminate a whole range of candidates with each step.


How It Works
sorted array: [1, 3, 5, 7, 9, 11]   target = 12

left = 0, right = 5
sum = 1 + 11 = 12  → found!
sorted array: [1, 3, 5, 7, 9, 11]   target = 10

left = 0, right = 5   sum = 12 > 10 → right--
left = 0, right = 4   sum = 10 = 10 → found!
sorted array: [1, 3, 5, 7, 9, 11]   target = 6

left = 0, right = 5   sum = 12 → right--
left = 0, right = 4   sum = 10 → right--
left = 0, right = 3   sum =  8 → right--
left = 0, right = 2   sum =  6 → found!

Loop invariant: at every iteration, if a valid pair exists in the array, at least one endpoint of the pair lies within [left, right].


Internal Mechanics
  • Both pointers start outside each other's range.
  • On each iteration, exactly one pointer moves (or in some variants, both).
  • The movement rule must shrink the search space — the loop must terminate.
  • The search ends when left >= right (pointers cross or meet).

Java Implementation Notes
java
// Two Sum II - sorted array, opposite-direction pointers
public int[] twoSum(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int sum = nums[left] + nums[right];
        if (sum == target) return new int[]{left + 1, right + 1}; // 1-indexed
        if (sum < target) left++;
        else right--;
    }
    return new int[]{-1, -1}; // no pair found
}

Three Sum (extend to triplets):

java
import java.util.*;

public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> result = new ArrayList<>();
    for (int i = 0; i < nums.length - 2; i++) {
        if (i > 0 && nums[i] == nums[i - 1]) continue; // skip duplicates
        int left = i + 1, right = nums.length - 1;
        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];
            if (sum == 0) {
                result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                while (left < right && nums[left] == nums[left + 1]) left++;
                while (left < right && nums[right] == nums[right - 1]) right--;
                left++;
                right--;
            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
}

Clean Code Rules
  • Name pointers for their role: left/right conveys direction better than i/j for a converging scan.
  • State the invariant in a comment before the loop body. It makes the code self-documenting and exposes bugs immediately.
  • Extract the movement condition into a well-named boolean if it gets complex.

Mini Example: Valid Palindrome
java
public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
        while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
        if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Common Mistakes
  1. Using left <= right instead of left < right: For pair-finding, left < right is correct. When left == right you are looking at the same element — not a pair.
  2. Not skipping duplicates in Three Sum: Results in duplicate triplets.
  3. Moving both pointers unconditionally: The logic must move only the pointer that fixes the imbalance.

Debugging Tips
  • Print (left, right, nums[left], nums[right]) at the top of each iteration.
  • Verify the loop invariant holds before and after each pointer move.
  • Test single-element, two-element, and all-same-value arrays.

Practical Note

Sortedness is the key signal here. A hash map also solves pair sum in O(n) time, but opposite-direction pointers keep O(1) extra space and use the ordering directly.


Deeper Note

Opposite-direction pointers generalize to container problems (maximize width × height) and to two-pointer on multiple arrays (merge sorted arrays). The invariant reasoning transfers directly.


  • Binary search (also exploits sorted order, O(log n) per search)
  • Sliding window (same-direction pointers with a dynamic window)

Concept Cluster 2: Same-Direction Pointers and Partitioning

Topics in this cluster:

  • 5.2 Same-direction pointers
  • 5.2 Partitioning and rearrangement

Definition

Same-direction pointers (also called slow/fast or read/write pointers) both travel left-to-right. They serve different roles:

  • write (slow) pointer: marks where the next valid element should be placed.
  • read (fast) pointer: scans through the array looking for valid elements.

This pattern rewrites an array in-place: valid elements move to the front while invalid ones are left behind. No extra array is allocated — O(1) extra space.


Why It Matters

Removing duplicates, filtering zeros, and partitioning by a condition are extremely common interview problems. The naive solution copies to a new array. The in-place solution with two same-direction pointers impresses interviewers because it is space-efficient and clean.


How It Works

Remove duplicates from sorted array:

[1, 1, 2, 3, 3, 4]
write = 0

read = 0: nums[0]=1, always keep first element → write=1
read = 1: nums[1]=1 == nums[write-1]=1 → skip
read = 2: nums[2]=2 != nums[write-1]=1 → nums[write++]=2 → write=2
read = 3: nums[3]=3 != nums[write-1]=2 → nums[write++]=3 → write=3
read = 4: nums[4]=3 == nums[write-1]=3 → skip
read = 5: nums[5]=4 != nums[write-1]=3 → nums[write++]=4 → write=4

Result: [1, 2, 3, 4, _, _]  → return write = 4

Partitioning and Rearrangement

Partitioning separates elements into two groups without necessarily sorting. The classic example: move all zeros to the end while preserving relative order of non-zeros.

[0, 1, 0, 3, 12]

write = 0
read: 0 → skip (zero)
read: 1 → nums[write++] = 1 → write=1
read: 0 → skip
read: 3 → nums[write++] = 3 → write=2
read: 12 → nums[write++] = 12 → write=3

Fill rest with zeros:
nums[3]=0, nums[4]=0

Result: [1, 3, 12, 0, 0]

Dutch National Flag (partition into three groups — 0s, 1s, 2s) uses three pointers:

low=0, mid=0, high=n-1

While mid <= high:
  if nums[mid] == 0: swap(low, mid); low++; mid++
  if nums[mid] == 1: mid++
  if nums[mid] == 2: swap(mid, high); high--   // do NOT increment mid

Java Implementation Notes
java
// Remove duplicates from sorted array
public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int write = 1;
    for (int read = 1; read < nums.length; read++) {
        if (nums[read] != nums[write - 1]) {
            nums[write++] = nums[read];
        }
    }
    return write;
}

// Move zeros to end, preserve relative order
public void moveZeroes(int[] nums) {
    int write = 0;
    for (int read = 0; read < nums.length; read++) {
        if (nums[read] != 0) {
            nums[write++] = nums[read];
        }
    }
    while (write < nums.length) {
        nums[write++] = 0;
    }
}

// Dutch National Flag — sort array containing only 0, 1, 2
public void sortColors(int[] nums) {
    int low = 0, mid = 0, high = nums.length - 1;
    while (mid <= high) {
        if (nums[mid] == 0) {
            int tmp = nums[low]; nums[low] = nums[mid]; nums[mid] = tmp;
            low++;
            mid++;
        } else if (nums[mid] == 1) {
            mid++;
        } else {
            int tmp = nums[mid]; nums[mid] = nums[high]; nums[high] = tmp;
            high--;
            // do not increment mid — the swapped value is unexamined
        }
    }
}

Clean Code Rules
  • The write pointer always points at the next empty slot, not the last written slot. Keep this mental model consistent.
  • Separate the read and write concerns: the read pointer scans; the write pointer records. Do not conflate them.

Mini Example: Remove Element
java
// Remove all occurrences of val from nums in-place
public int removeElement(int[] nums, int val) {
    int write = 0;
    for (int read = 0; read < nums.length; read++) {
        if (nums[read] != val) {
            nums[write++] = nums[read];
        }
    }
    return write;
}

Common Mistakes
  1. Forgetting to fill the tail with zeros after compacting non-zeros.
  2. Incrementing mid after swapping with high in Dutch National Flag — the swapped value is unexamined.
  3. Off-by-one in write initialization: start write at 0, not 1, unless the problem guarantees a non-empty prefix.

Practical Note

Dutch National Flag is a classic. DiIjkstra designed it. Interviewers expect you to know the invariant for all three regions:

  • [0, low) all zeros
  • [low, mid) all ones
  • (high, n-1] all twos
  • [mid, high] unexplored

State the invariant before coding. It earns points.


Concept Cluster 3: Fast and Slow Pointer Technique

Topics in this cluster:

  • 5.3 Fast and slow pointer technique
  • 5.3 Fast and Slow Pointer Pattern

Definition

The Fast and Slow Pointer Pattern (also called Floyd's Tortoise and Hare) uses two pointers where the fast pointer advances at twice the speed of the slow pointer. It is used to:

  1. Detect a cycle in a linked list or sequence.
  2. Find the start of a cycle.
  3. Find the middle of a linked list.
  4. Detect whether a number is a happy number.

Why It Matters

Cycle detection is a prerequisite for linked list problems (Chapter 7), and the mathematical intuition transfers to any sequence with bounded state. The pattern uses O(1) extra space — no visited set needed.


How It Works

Cycle Detection:

List: 1 → 2 → 3 → 4 → 5 → 3 (cycle back to node 3)

slow: 1 → 2 → 3 → 4 → 5 → 3 → 4 ...
fast: 1 → 3 → 5 → 4 → 3 → 5 ...

At some point slow == fast → cycle detected.

Why they must meet: Once fast enters the cycle, the distance between fast and slow decreases by 1 each step. Eventually the gap closes to 0. They must meet inside the cycle.

Finding the start of the cycle:

After detection, reset slow to head. Advance both at speed 1. The node where they meet again is the cycle start. (This relies on a number-theoretic argument about cycle length and entry distance.)

Finding the middle of a linked list:

List: 1 → 2 → 3 → 4 → 5

slow: 1 → 2 → 3        (stops at middle)
fast: 1 → 3 → 5 → null (reaches end)

When fast reaches null or fast.next is null, slow is at the middle.


Internal Mechanics
  • slow moves 1 step per iteration.
  • fast moves 2 steps per iteration.
  • If no cycle: fast reaches null.
  • If cycle: fast laps slow inside the cycle.

Java Implementation Notes
java
// Linked list node
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
}

// Detect cycle
public boolean hasCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}

// Find cycle start
public ListNode detectCycle(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) {
            slow = head; // reset slow to head
            while (slow != fast) {
                slow = slow.next;
                fast = fast.next;
            }
            return slow; // cycle start
        }
    }
    return null; // no cycle
}

// Find middle of linked list
public ListNode middleNode(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

Clean Code Rules
  • The termination guard is fast != null && fast.next != null, not just fast != null. Missing fast.next != null will throw a NullPointerException when the list has even length.
  • Reset slow to head (not to the meeting point) when finding the cycle start.

Mini Example: Happy Number
java
// A number is happy if repeated digit-squaring eventually reaches 1.
// If not happy, it cycles. Use fast/slow on the sequence.
public boolean isHappy(int n) {
    int slow = n, fast = sumOfSquares(n);
    while (fast != 1 && slow != fast) {
        slow = sumOfSquares(slow);
        fast = sumOfSquares(sumOfSquares(fast));
    }
    return fast == 1;
}

private int sumOfSquares(int n) {
    int sum = 0;
    while (n > 0) {
        int digit = n % 10;
        sum += digit * digit;
        n /= 10;
    }
    return sum;
}

Common Mistakes
  1. Initializing both pointers to head.next: The standard initialization is both at head. Starting elsewhere shifts the meeting-point math.
  2. Not checking fast.next != null before fast.next.next: Two-step advance needs both guards.
  3. Returning fast as the cycle start: The meeting point inside the cycle is not necessarily the entry point. Reset slow to head and advance both at speed 1.

Practical Note

Interviewers frequently ask: "Can you solve this without a HashSet?" The fast/slow pointer is the answer. Memorize the two-phase algorithm (detect, then find start). Know how to verbally explain why resetting slow to head finds the entry.


Deeper Note

The same tortoise-and-hare logic detects duplicate numbers in an array when you treat values as "next pointers" (see Floyd's cycle detection applied to Leetcode #287 Find the Duplicate Number).


Concept Cluster 4: In-Place Reversal Pattern and Pointer Workflows

Topics in this cluster:

  • 5.4 In-Place Reversal Pattern
  • 5.4 Partitioning, shrinking, and expanding workflows

Definition

The In-Place Reversal Pattern reverses a sequence (array, string, or linked list) using two opposite-direction pointers with a swap, consuming O(1) extra space. Reversals appear as standalone problems and as sub-steps in rotation, palindrome, and list-reversal algorithms.

Partitioning, shrinking, and expanding workflows covers how pointer pairs work together to either narrow a search space (shrinking) or grow a candidate window (expanding) — the transition concept between two-pointer and sliding window.


How Reversal Works

Array reversal:

[1, 2, 3, 4, 5]

left=0, right=4: swap(1,5) → [5, 2, 3, 4, 1]
left=1, right=3: swap(2,4) → [5, 4, 3, 2, 1]
left=2, right=2: left >= right → stop

Result: [5, 4, 3, 2, 1]

Linked list reversal uses three pointers: prev, curr, next.

null ← 1 ← 2 ← 3 ← 4 ← 5

At each step: save next, reverse curr.next, advance prev and curr.

Partitioning Workflows

Shrinking window: Both pointers start wide and move inward based on a condition. Used when the valid region narrows. Example: Two Sum on sorted array.

Expanding window: Both pointers start narrow (e.g., both at left=0, right=0) and expand outward when a condition is met. Used in sliding window (Chapter 6).

Shrink from one side only: One pointer is fixed while the other moves in. Used in binary search variants and some partition problems.


Java Implementation Notes
java
// Reverse an array in-place
public void reverse(int[] nums) {
    int left = 0, right = nums.length - 1;
    while (left < right) {
        int tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
        left++;
        right--;
    }
}

// Reverse a string in-place (char array)
public void reverseString(char[] s) {
    int left = 0, right = s.length - 1;
    while (left < right) {
        char tmp = s[left];
        s[left] = s[right];
        s[right] = tmp;
        left++;
        right--;
    }
}

// Reverse a linked list iteratively
public ListNode reverseList(ListNode head) {
    ListNode prev = null, curr = head;
    while (curr != null) {
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev; // new head
}

// Rotate array right by k positions using three reversals
public void rotate(int[] nums, int k) {
    int n = nums.length;
    k = k % n; // handle k >= n
    reverse(nums, 0, n - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, n - 1);
}

private void reverse(int[] nums, int left, int right) {
    while (left < right) {
        int tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
        left++;
        right--;
    }
}

Clean Code Rules
  • Extract reverse(int[] nums, int left, int right) as a helper. Rotation uses it three times; inlining creates repetition and bugs.
  • Comment the three-reversal trick: it is not immediately obvious why reversing three segments rotates the array. A one-line comment pays dividends for every reader.

Mini Example: Reverse Words in a String
java
// "the sky is blue" → "blue is sky the"
public String reverseWords(String s) {
    char[] chars = s.trim().toCharArray();
    // Step 1: reverse entire array
    reverse(chars, 0, chars.length - 1);
    // Step 2: reverse each word
    int start = 0;
    for (int end = 0; end <= chars.length; end++) {
        if (end == chars.length || chars[end] == ' ') {
            reverse(chars, start, end - 1);
            start = end + 1;
        }
    }
    // Collapse multiple spaces (simplified — real solution needs more handling)
    return new String(chars);
}

private void reverse(char[] chars, int left, int right) {
    while (left < right) {
        char tmp = chars[left]; chars[left] = chars[right]; chars[right] = tmp;
        left++; right--;
    }
}

Common Mistakes
  1. Forgetting k = k % n in rotation — when k >= n you wrap around.
  2. Losing the next pointer before reversing curr.next in linked list reversal.
  3. Reversing to the wrong boundary in partial reversal — be precise about inclusive vs exclusive endpoints.

Practical Note

Three-reversal array rotation is a classic "clever but simple" trick. Interviewers also test linked list reversal constantly. Know both iterative and recursive forms. Recursive linked list reversal uses the call stack as implicit storage — O(n) space.


Concept Cluster 5: Recognizing Two-Pointer Problems

Topics in this cluster:

  • 5.5 Recognizing two-pointer problems
  • 5.5 Recognition checklist for linear-scan problems

Recognition Signals

Two-pointer problems share common signals. Look for:

Signal Example
Sorted array + pair/triplet target Two Sum II, Three Sum
In-place filter or deduplicate Remove duplicates, Remove element
Palindrome check Valid palindrome
Cycle or middle of linked list Linked list cycle, Middle node
Reverse or rotate Reverse string, Rotate array
Partition by condition Dutch National Flag, Move zeros
Minimize/maximize a value using two ends Container with most water
O(1) space explicitly required Almost any of the above

Recognition Checklist for Linear-Scan Problems

Use this checklist when you see an array or string problem:

  1. Is the input sorted? → Consider opposite-direction two pointers.
  2. Do I need to find a pair or triple that satisfies a sum/product condition? → Sort + two pointers.
  3. Do I need to filter or compact in-place? → Same-direction read/write pointers.
  4. Is there a cycle or "does it repeat" question on a sequence? → Fast and slow pointers.
  5. Do I need to reverse a segment? → In-place reversal.
  6. Is the problem asking for a window or subarray? → Check Sliding Window (Chapter 6) first; if fixed-or-no-state window, two pointers suffice.
  7. Does brute force use two nested loops with indices moving in opposite directions? → Strong sign: two opposite-direction pointers.
  8. Does brute force use two nested loops with one index always ahead of the other? → Strong sign: same-direction pointers.

When NOT to Use Two Pointers
  • When the array is unsorted and you need exact pair sums → Use a HashMap (O(n) time, O(n) space).
  • When you need to track multiple overlapping ranges simultaneously → Use a segment tree or sorted set.
  • When pointer movement depends on non-local state (state from far away in the array) → Might need DP or stack.
  • When the problem asks for the count of all valid pairs (not just existence) → Sometimes O(n²) is unavoidable, but often binary search or prefix sums help.

Practical Note

Stating the recognition checklist out loud signals algorithmic maturity. Say: "The input is sorted and I need a pair sum — that's a two-pointer opportunity. I'll use opposite-direction pointers and the invariant is..." This is exactly what a senior engineer sounds like in an interview.


Concept Cluster 6: Edge Cases, Invariants, and Debugging Strategy

Topics in this cluster:

  • 5.6 Edge cases, invariants, and debugging strategy

Core Invariants to Define Before Coding

Before writing any two-pointer loop, write down:

  1. What does left represent at all times?
  2. What does right represent at all times?
  3. What is the loop's termination condition and why is it correct?
  4. Does every pointer movement shrink the search space? (If not, infinite loop.)

Example invariants:

  • Opposite two-sum: "At all times, if the answer exists, at least one of its elements has an index in [left, right]."
  • Read/write: "All elements in [0, write) are valid. All elements in [read, n) are unexamined."
  • Dutch Flag: "All elements in [0, low) are 0. All in [low, mid) are 1. All in (high, n-1] are 2."

Edge Cases Checklist
Case What to check
Empty array (n == 0) Return immediately, no loop
Single element (n == 1) Most loops do not execute — result is trivially the single element
All elements equal Deduplication reduces to length 1; Dutch Flag has no swaps
All elements satisfy condition Write pointer reaches n; no tail filling needed
No elements satisfy condition Write pointer stays at 0; result is empty
Even vs odd length (palindrome, middle) Even: pointers meet at the gap; odd: pointers meet at center
Duplicate triplets (Three Sum) Skip duplicates after finding a valid triplet
k >= n in rotation Normalize with k % n

Debugging Strategy

Step 1: State your invariant in a comment.

java
// Invariant: nums[0..write-1] contains all non-zero elements seen so far.

Step 2: Add a trace line at the top of the loop.

java
// System.out.printf("left=%d right=%d nums[left]=%d nums[right]=%d%n",
//                    left, right, nums[left], nums[right]);

Step 3: Check the termination condition manually for small inputs.

Run a 2-element array and a 3-element array by hand. If the loop body is correct but the termination is <= instead of <, it shows immediately.

Step 4: Verify pointer movement actually shrinks the search space.

Every path through the loop body must move at least one pointer. If there is a path where neither pointer moves, you have an infinite loop.

Step 5: Verify the final state.

After the loop, what do left, right, and write point at? Is the return value derived correctly from those?


Common Invariant Violations
  • Swapping elements that include the write pointer when read == write (no-op swap but can hide bugs).
  • Advancing mid after swapping with high in Dutch Flag — the newly placed element is unexamined.
  • In cycle detection, initializing slow/fast at different starting points (changes meeting-point math).

Worked Examples


Worked Example 1: Two Sum II — Input Array Is Sorted

Problem or Design Scenario

Given a 1-indexed sorted array numbers and a target integer, return the 1-indexed positions of the two numbers that add to target. Exactly one solution exists.

Technical Value

This is a standard opposite-direction two-pointer problem. The same movement rule also appears inside Three Sum, Four Sum, and related search problems.

Constraints or Assumptions
  • Array is sorted in non-decreasing order.
  • Exactly one valid pair exists.
  • Return 1-indexed positions.
Example Input/Output
Input:  numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]

Input:  numbers = [2, 3, 4], target = 6
Output: [1, 3]
Brute Force Approach

Try every pair (i, j) where i < j. Return when numbers[i] + numbers[j] == target.

  • Time: O(n²) | Space: O(1)
Optimized Approach

Use opposite-direction two pointers. Since the array is sorted:

  • If numbers[left] + numbers[right] < target → move left right (increase sum).
  • If numbers[left] + numbers[right] > target → move right left (decrease sum).
  • If equal → found.
  • Time: O(n) | Space: O(1)
Why the Better Approach Works

Sortedness gives us a monotone property: the sum increases when we move left right and decreases when we move right left. We eliminate an entire column or row of the pair-search matrix with each step.

Decision Process

I see a sorted array and a pair-sum target. That points to opposite-direction two pointers. A hash map would still be O(n) time, but it uses extra space. The invariant is: if the answer exists, at least one of its indices is in [left, right].

Java Solution
java
public class TwoSumII {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        // Invariant: if a valid pair exists, one index is in [left, right]
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left + 1, right + 1}; // 1-indexed
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{-1, -1}; // guaranteed not to reach here per problem statement
    }
}
Dry Run
numbers = [2, 7, 11, 15], target = 9

left=0, right=3: sum = 2+15 = 17 > 9 → right--
left=0, right=2: sum = 2+11 = 13 > 9 → right--
left=0, right=1: sum = 2+7  =  9 == 9 → return [1, 2]
Time and Space Complexity
  • Time: O(n) — each element is visited at most once.
  • Space: O(1) — no auxiliary data structure.
Edge Cases
  • Two-element array: only one pair to check, loop runs once.
  • Target formed by first and last elements: terminates on first iteration.
  • Large values: use long if overflow is possible (numbers[i] up to 10⁹).
Common Mistakes
  • Using left <= right — when left == right, we are looking at the same element, not a pair.
  • Returning 0-indexed instead of 1-indexed.
  • Two Sum on unsorted array → use HashMap.
  • Three Sum → sort, then apply two-pointer in a loop.
  • Four Sum → two nested loops + two-pointer inner loop.
Validation
java
assert Arrays.equals(twoSum(new int[]{2,7,11,15}, 9), new int[]{1,2});
assert Arrays.equals(twoSum(new int[]{2,3,4}, 6), new int[]{1,3});
assert Arrays.equals(twoSum(new int[]{-1,0}, -1), new int[]{1,2});

Worked Example 2: Remove Duplicates from Sorted Array II (Allow at Most 2 Duplicates)

Problem or Design Scenario

Given a sorted array, remove duplicates in-place such that each element appears at most twice. Return the new length. Do not allocate extra space.

Technical Value

It extends "Remove Duplicates I" (allow at most once) to a generalized form. The key insight is parameterizable: the allowed count k generalizes the condition. This teaches you to generalize patterns, not just memorize specific solutions.

Constraints or Assumptions
  • Sorted in non-decreasing order.
  • Modify in-place.
  • Elements beyond the returned length are irrelevant.
Example Input/Output
Input:  [1, 1, 1, 2, 2, 3]
Output: 5    (array becomes [1, 1, 2, 2, 3, _])

Input:  [0, 0, 1, 1, 1, 1, 2, 3, 3]
Output: 7    (array becomes [0, 0, 1, 1, 2, 3, 3, _, _])
Brute Force Approach

Count occurrences of each value, then rebuild. O(n) time, O(n) space (new array).

Optimized Approach

Use a write pointer. Allow writing the current element if write < 2 (not enough written yet) OR if nums[read] != nums[write - 2] (current element differs from the element two positions behind).

Why the Better Approach Works

By comparing nums[read] with nums[write - 2], we know: if they are the same, we have already placed this value twice and must skip. This generalization works for any allowed count k by comparing with nums[write - k].

Decision Process

Same-direction pointers with a write pointer that enforces the invariant. I do not need to count occurrences separately. The invariant: nums[0..write-1] has no element appearing more than twice. I advance write only when the current element passes the at-most-2 check.

Java Solution
java
public class RemoveDuplicatesII {
    public int removeDuplicates(int[] nums) {
        int write = 0;
        for (int read = 0; read < nums.length; read++) {
            // Allow element if fewer than 2 written, or if it differs from 2 positions back
            if (write < 2 || nums[read] != nums[write - 2]) {
                nums[write++] = nums[read];
            }
        }
        return write;
    }
}
Dry Run
nums = [1, 1, 1, 2, 2, 3]

read=0: write=0 < 2 → write nums[0]=1 → write=1  → [1,_,_,_,_,_]
read=1: write=1 < 2 → write nums[1]=1 → write=2  → [1,1,_,_,_,_]
read=2: nums[2]=1 == nums[write-2]=nums[0]=1 → skip
read=3: nums[3]=2 != nums[write-2]=nums[0]=1 → write nums[3]=2 → write=3 → [1,1,2,_,_,_]
read=4: nums[4]=2 != nums[write-2]=nums[1]=1 → write nums[4]=2 → write=4 → [1,1,2,2,_,_]
read=5: nums[5]=3 != nums[write-2]=nums[2]=2 → write nums[5]=3 → write=5 → [1,1,2,2,3,_]

Return 5.
Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • Array with fewer than 2 elements: write < 2 guard handles this.
  • All identical: only first 2 kept.
  • All distinct: all kept.
Common Mistakes
  • Comparing with nums[write - 1] instead of nums[write - 2] (solves the k=1 problem, not k=2).
  • Not handling the write < k base case — array index out of bounds.
  • k=1 (original remove duplicates): nums[read] != nums[write - 1]
  • k=3: nums[read] != nums[write - 3]
  • General k: write < k || nums[read] != nums[write - k]
Validation
java
int[] a = {1,1,1,2,2,3};
assert removeDuplicates(a) == 5;
int[] b = {0,0,1,1,1,1,2,3,3};
assert removeDuplicates(b) == 7;

Worked Example 3: Container With Most Water

Problem or Design Scenario

Given an integer array height of length n, where height[i] is the height of the ith vertical bar, find two bars that together with the x-axis form a container holding the most water.

Technical Value

This is a non-obvious application of opposite-direction two pointers that requires a greedy argument to justify why it is correct. It moves beyond "sorted array + pair sum" to a maximization problem on unsorted data.

Constraints or Assumptions
  • n >= 2
  • Heights are non-negative integers.
  • You cannot slant the container.
Example Input/Output
Input:  height = [1,8,6,2,5,4,8,3,7]
Output: 49   (bars at index 1 and 8, width=7, min height=7, area=49)
Brute Force Approach

Try every pair (i, j). Area = min(height[i], height[j]) * (j - i). Track the maximum.

  • Time: O(n²) | Space: O(1)
Optimized Approach

Start left=0, right=n-1. The area is min(height[left], height[right]) * (right - left). Move the pointer pointing to the shorter bar inward. Shorter bar is the bottleneck; moving it may find a taller bar. Moving the taller bar can only decrease the area.

  • Time: O(n) | Space: O(1)
Why the Better Approach Works

Greedy argument: Suppose height[left] <= height[right]. The area with left fixed and any right' < right is at most height[left] * (right' - left) < height[left] * (right - left). So no future pairing with the current left can be larger. We can safely discard left by moving it inward.

Decision Process

I need to maximize area = width × min-height. The greedy observation is: width shrinks as I bring pointers together, so I need height to grow. Moving the shorter bar inward is the only hope. The taller bar is not the bottleneck. This greedy argument is provable, not just intuitive.

Java Solution
java
public class ContainerWithMostWater {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxWater = 0;
        while (left < right) {
            int water = Math.min(height[left], height[right]) * (right - left);
            maxWater = Math.max(maxWater, water);
            // Move the shorter bar inward — it is the bottleneck
            if (height[left] <= height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxWater;
    }
}
Dry Run
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
indices:   0  1  2  3  4  5  6  7  8

left=0, right=8: water = min(1,7)*8 = 8.   max=8.  height[0]=1 <= height[8]=7 → left++
left=1, right=8: water = min(8,7)*7 = 49.  max=49. height[1]=8 >  height[8]=7 → right--
left=1, right=7: water = min(8,3)*6 = 18.  max=49. height[1]=8 >  height[7]=3 → right--
left=1, right=6: water = min(8,8)*5 = 40.  max=49. height[1]=8 <= height[6]=8 → left++
left=2, right=6: water = min(6,8)*4 = 24.  max=49. left++
left=3, right=6: water = min(2,8)*3 = 6.   max=49. left++
left=4, right=6: water = min(5,8)*2 = 10.  max=49. left++
left=5, right=6: water = min(4,8)*1 = 4.   max=49. left++
left=6: left >= right → stop.

Return 49.
Time and Space Complexity
  • Time: O(n) — each pointer moves inward; total moves ≤ n.
  • Space: O(1)
Edge Cases
  • Two bars: single iteration.
  • All bars same height: width shrinks each step, first pair is largest.
  • One extremely tall bar surrounded by short bars: short bars determine height.
Common Mistakes
  • Moving the taller bar inward (never helps).
  • Using < instead of <= when heights are equal — both give the same result here, but be consistent.
  • Integer overflow: min(h[l], h[r]) * (r - l) can overflow int if heights are up to 10⁴ and n up to 10⁵. Use long or verify bounds.
  • Largest rectangle in histogram: more complex, uses monotonic stack (Chapter 7).
  • Trapping rain water: uses two-pointer or monotonic stack.
Validation
java
assert maxArea(new int[]{1,8,6,2,5,4,8,3,7}) == 49;
assert maxArea(new int[]{1,1}) == 1;
assert maxArea(new int[]{4,3,2,1,4}) == 16;

Solved Problems


Problem 1 (Easy): Squares of a Sorted Array

Problem Statement

Given an integer array sorted in non-decreasing order (may contain negative numbers), return an array of the squares of each number, sorted in non-decreasing order. Do it in O(n) time.

Constraints or Assumptions
  • -10⁴ <= nums[i] <= 10⁴
  • Array is sorted but may contain negatives.
Example
Input:  [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Brute Force Solution

Square all elements, then sort: O(n log n).

Optimized Solution

Use opposite-direction pointers. The largest squares are at the two ends (since the array is sorted by absolute value from the outside in). Fill the result array from the back.

Why the Final Approach Works

The maximum square at any step is the larger of nums[left]² and nums[right]². Place it at the back of the result and advance the corresponding pointer inward.

Decision Process

Sorted array, but negatives make direct squaring unsorted. The outer elements have the largest absolute values. Fill the result from the end — O(n) and O(n) space for the result (unavoidable since we must return a new array).

Java Solution
java
public class SquaresSortedArray {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        int left = 0, right = n - 1, pos = n - 1;
        while (left <= right) {
            int leftSq = nums[left] * nums[left];
            int rightSq = nums[right] * nums[right];
            if (leftSq >= rightSq) {
                result[pos--] = leftSq;
                left++;
            } else {
                result[pos--] = rightSq;
                right--;
            }
        }
        return result;
    }
}
Dry Run
nums = [-4, -1, 0, 3, 10]
left=0, right=4, pos=4: leftSq=16, rightSq=100 → result[4]=100, right-- → pos=3
left=0, right=3, pos=3: leftSq=16, rightSq=9   → result[3]=16,  left++ → pos=2
left=1, right=3, pos=2: leftSq=1,  rightSq=9   → result[2]=9,   right-- → pos=1
left=1, right=2, pos=1: leftSq=1,  rightSq=0   → result[1]=1,   left++ → pos=0
left=2, right=2, pos=0: leftSq=0,  rightSq=0   → result[0]=0,   left++ → stop

Result: [0, 1, 9, 16, 100]
Time and Space Complexity
  • Time: O(n) | Space: O(n) for result
Edge Cases
  • All negatives: pointer moves from left inward.
  • All positives: pointer moves from right inward.
  • Single element: one iteration.
  • Merge two sorted arrays of squares.

Problem 2 (Easy): Palindrome Check Ignoring Non-Alphanumeric Characters

Problem Statement

Given a string s, return true if it is a palindrome when considering only alphanumeric characters and ignoring case.

Constraints or Assumptions
  • 0 <= s.length <= 2 * 10⁵
Example
Input:  "A man, a plan, a canal: Panama"
Output: true

Input:  "race a car"
Output: false
Brute Force Solution

Filter characters into a new string, then check if it equals its reverse: O(n) time, O(n) space.

Optimized Solution

In-place two pointers, skipping non-alphanumeric characters.

Java Solution
java
public class ValidPalindrome {
    public boolean isPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        while (left < right) {
            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
            if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
Dry Run
s = "A man, a plan, a canal: Panama"

left=0('A'), right=29('a'): A==a → advance
left=1(' ') → skip to 2('m')
right=28('m'): m==m → advance
... continues until left >= right → return true
Time and Space Complexity
  • Time: O(n) | Space: O(1)
Edge Cases
  • Empty string: return true.
  • All non-alphanumeric: return true (empty after filtering).
  • Single character: return true.

Problem 3 (Medium): Three Sum — Find All Unique Triplets Summing to Zero

Problem Statement

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j != k and nums[i] + nums[j] + nums[k] == 0.

Constraints or Assumptions
  • Result must not contain duplicate triplets.
  • No ordering requirement on the output.
Example
Input:  [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Brute Force Solution

Three nested loops checking all triples: O(n³). Use a Set to deduplicate.

Optimized Solution

Sort the array. For each index i, apply two-pointer on [i+1, n-1] to find pairs summing to -nums[i]. Skip duplicates after each solution found.

Java Solution
java
import java.util.*;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue; // skip duplicate anchor
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    while (left < right && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return result;
    }
}
Dry Run
nums (sorted) = [-4, -1, -1, 0, 1, 2]

i=0, nums[0]=-4: left=1, right=5
  sum = -4 + (-1) + 2 = -3 < 0 → left++
  sum = -4 + (-1) + 2 = -3 < 0 → left++
  sum = -4 + 0 + 2 = -2 < 0 → left++
  sum = -4 + 1 + 2 = -1 < 0 → left++
  left=5 >= right=5 → stop

i=1, nums[1]=-1: left=2, right=5
  sum = -1 + (-1) + 2 = 0 → add [-1,-1,2], skip dups → left=3, right=4
  sum = -1 + 0 + 1 = 0 → add [-1,0,1], skip dups → left=4, right=3 → stop

i=2, nums[2]=-1 == nums[1] → skip
i=3, nums[3]=0: left=4, right=5
  sum = 0 + 1 + 2 = 3 > 0 → right--
  left >= right → stop

Result: [[-1,-1,2], [-1,0,1]]
Time and Space Complexity
  • Time: O(n²) — outer loop O(n), inner two-pointer O(n)
  • Space: O(log n) for sort stack; O(k) for result where k = number of triplets
Edge Cases
  • Fewer than 3 elements: return empty.
  • All zeros: one triplet [0,0,0].
  • Large duplicate arrays: duplicate-skipping is essential.
  • Four Sum: two nested loops + two-pointer.
  • Three Sum Closest: track minimum difference instead of exact zero.

Problem 4 (Medium): Linked List Cycle II — Find Cycle Entry Point

Problem Statement

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Constraints or Assumptions
  • Do not modify the list.
  • Use O(1) extra space.
Example
List: 3 → 2 → 0 → -4 → (back to node 2)
Output: node with value 2
Brute Force Solution

Use a HashSet<ListNode> to track visited nodes: O(n) time, O(n) space.

Optimized Solution

Floyd's cycle detection: Phase 1 — detect cycle (meet inside cycle). Phase 2 — find entry (reset slow to head, advance both at speed 1 until they meet).

Java Solution
java
public class LinkedListCycleII {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        // Phase 1: detect
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                // Phase 2: find entry
                slow = head;
                while (slow != fast) {
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }
}
Dry Run
List: head→[3]→[2]→[0]→[-4]→(back to [2])
Nodes by position:  0    1    2     3

Phase 1:
step 1: slow=1, fast=2
step 2: slow=2, fast=0
step 3: slow=3, fast=2  (fast wrapped: -4 → 2)
step 4: slow=1, fast=0  (slow: 3→2; fast: 2→0)

Wait — let me redo with node references:
n0=3, n1=2, n2=0, n3=-4; n3.next=n1

slow: n0→n1→n2→n3→n1→n2→...
fast: n0→n2→n1→n3→n2→n1→...

step1: slow=n1, fast=n2
step2: slow=n2, fast=n1
step3: slow=n3, fast=n3  → meet at n3

Phase 2: reset slow=n0=head, fast stays at n3
step1: slow=n1(=2), fast=n1(n3.next=n1) → meet at n1=2

Return n1 (value 2). Correct.
Time and Space Complexity
  • Time: O(n) | Space: O(1)
Edge Cases
  • No cycle: fast reaches null.
  • Cycle at head: cycle starts immediately; phase 2 returns head.
  • Single-node self-loop: fast.next == fast; detected in first iteration.

Problem 5 (Hard): Trapping Rain Water

Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Constraints or Assumptions
  • n >= 0
  • height[i] >= 0
Example
Input:  [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Brute Force Solution

For each index i, scan left and right to find maxLeft and maxRight. Water at i = min(maxLeft, maxRight) - height[i]. O(n²) time.

Optimized Solution

Use opposite-direction two pointers. Maintain leftMax and rightMax — the running max seen from each side. Process the side with the smaller max:

  • If leftMax <= rightMax: water at left = leftMax - height[left]. Advance left.
  • Else: water at right = rightMax - height[right]. Advance right.
Why the Final Approach Works

For index left, if leftMax <= rightMax, then rightMax is at least leftMax, so the water at left is determined entirely by leftMax. We do not need to know the exact right maximum — we know it is at least leftMax. This gives us confidence to process left immediately.

Decision Process

Two-pass prefix max gives O(n) with O(n) space. Two pointers give O(n) time and O(1) space — the optimal solution. The key insight: process the side with the smaller maximum because the water there is bounded by that side, regardless of the other side.

Java Solution
java
public class TrappingRainWater {
    public int trap(int[] height) {
        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0;
        int water = 0;
        while (left < right) {
            if (height[left] <= height[right]) {
                if (height[left] >= leftMax) {
                    leftMax = height[left];
                } else {
                    water += leftMax - height[left];
                }
                left++;
            } else {
                if (height[right] >= rightMax) {
                    rightMax = height[right];
                } else {
                    water += rightMax - height[right];
                }
                right--;
            }
        }
        return water;
    }
}
Dry Run
height = [0,1,0,2,1,0,1,3,2,1,2,1]
           0 1 2 3 4 5 6 7 8 9 ...

left=0, right=11: h[0]=0 <= h[11]=1
  h[0]=0 < leftMax=0? No, 0>=0 → leftMax=0. left++
left=1, right=11: h[1]=1 <= h[11]=1
  h[1]=1 >= leftMax=0 → leftMax=1. left++
left=2, right=11: h[2]=0 <= h[11]=1
  h[2]=0 < leftMax=1 → water += 1-0=1. left++  [water=1]
left=3, right=11: h[3]=2 > h[11]=1
  h[11]=1 >= rightMax=0 → rightMax=1. right--
left=3, right=10: h[3]=2 > h[10]=2? No, equal → h[3] <= h[10]
  h[3]=2 >= leftMax=1 → leftMax=2. left++
left=4, right=10: h[4]=1 <= h[10]=2
  h[4]=1 < leftMax=2 → water += 2-1=1. left++  [water=2]
left=5, right=10: h[5]=0 <= h[10]=2
  h[5]=0 < leftMax=2 → water += 2-0=2. left++  [water=4]
left=6, right=10: h[6]=1 <= h[10]=2
  h[6]=1 < leftMax=2 → water += 2-1=1. left++  [water=5]
left=7, right=10: h[7]=3 > h[10]=2
  h[10]=2 >= rightMax=1 → rightMax=2. right--
left=7, right=9: h[7]=3 > h[9]=1
  h[9]=1 < rightMax=2 → water += 2-1=1. right-- [water=6]
left=7, right=8: h[7]=3 > h[8]=2
  h[8]=2 >= rightMax=2 → rightMax=2. right--
left=7, right=7: left >= right → stop.

Return 6. Correct.
Time and Space Complexity
  • Time: O(n) | Space: O(1)
Edge Cases
  • Empty or single-element: no water.
  • Monotonically increasing or decreasing: no water.
  • All same height: no water.
  • Largest rectangle in histogram (Chapter 7, monotonic stack).
  • Container With Most Water (worked example 3 above).

Recognition Guide

When to Use Two Pointers

Scenario Pointer Style
Sorted array, find pair with target sum Opposite-direction
Sorted array, Three/Four Sum Opposite-direction in outer loop
In-place remove/filter/compact Same-direction (read/write)
Partition array by condition Same-direction or Dutch Flag (3-way)
Check palindrome Opposite-direction
Reverse array or string segment Opposite-direction (swap)
Detect cycle in sequence/linked list Fast and slow
Find middle of linked list Fast and slow
Happy number, Floyd cycle in value-space Fast and slow
Rotate array in-place In-place reversal (3 reversals)
Squeeze water or maximize width × height Opposite-direction, greedy move

Recognition Keywords

  • "in-place," "O(1) extra space," "without extra memory"
  • "sorted array" + "pair/triplet/quadruplet"
  • "remove/filter/deduplicate" + array
  • "palindrome" + string
  • "cycle" + linked list
  • "middle" + linked list
  • "reverse" + O(1) space

Constraint Clues

  • O(1) space: immediately think two pointers or in-place.
  • Sorted input: opposite-direction two pointers is the first candidate.
  • In-place modification required: same-direction (write pointer).
  • Linear time O(n): nested loops are not acceptable — think one-pass with two pointers.

Common Traps

  • Forgetting to skip duplicates in Three Sum → duplicate triplets in output.
  • Using hash map when O(1) space is required.
  • Moving both pointers each step without a condition check.
  • Off-by-one on left < right vs left <= right.
  • Not normalizing k % n in rotation problems.

When NOT to Use Two Pointers

  • Unsorted array, exact pair sum → HashMap (O(n) time, O(n) space).
  • Count all valid subarrays with complex state → Sliding Window or DP.
  • Non-linear data structures (trees, graphs) → BFS/DFS.
  • Multiple independent scans that cannot be merged → may need separate passes.

Comparison Tables

Opposite-Direction Two Pointers vs HashMap (Pair Sum)

Dimension Two Pointers HashMap
Precondition Array must be sorted No sorting needed
Time O(n) O(n)
Space O(1) O(n)
Best use When input is sorted When input is unsorted
Handles duplicates With extra skip logic Naturally
Returns indices Yes, directly Yes, directly

Same-Direction (Write Pointer) vs New Array

Dimension Write Pointer New Array
Space O(1) extra O(n) extra
Time O(n) O(n)
Modifies original Yes No
Preferred when In-place required Original must be preserved

Two-Pointer Styles Comparison

Style Direction Use Case Termination
Opposite-direction ← → Pair sum, palindrome, container left >= right
Same-direction (read/write) → → Filter, compact, partition read >= n
Fast/slow → →→ Cycle, middle fast == null or slow == fast
In-place reversal ← → Reverse, rotate left >= right

Design and Decision Making

Relevant Design Patterns

Two-pointer itself is a coding pattern, not an OOP design pattern. But the design principles around it are important:

  • Single Responsibility: Each pointer has one job. read scans; write records. Do not let them share responsibilities.
  • Invariant as a contract: Define the loop invariant as a contract before coding. This mirrors defensive programming and DbC (Design by Contract).
  • Template Method: The two-pointer loop structure is a template: initialize → check condition → compute → move. The specifics vary, but the skeleton is fixed.

Clean Code Rules for Two-Pointer Code

  1. Declare pointers at the top with meaningful names: left/right for converging; read/write for same-direction; slow/fast for speed-based.
  2. State the invariant in a comment before the loop.
  3. Keep the loop body short: each branch should do one thing — move a pointer, record a result, or both.
  4. Extract helper methods for complex conditions: isValid(nums[read]) instead of nums[read] != 0 && nums[read] != val.
  5. Avoid mixing pointer roles: do not use write as a read index.

Naming Conventions

java
// Opposite-direction
int left = 0, right = nums.length - 1;

// Same-direction
int read = 0, write = 0; // or: int slow = 0, fast = 0;

// Fast/slow (linked list)
ListNode slow = head, fast = head;

// Reversal
int left = start, right = end;

API Design for Reusable Helpers

When reversal is used in multiple problems (rotation, word reversal, palindrome), extract it:

java
private static void reverse(int[] nums, int left, int right) {
    while (left < right) {
        int tmp = nums[left]; nums[left] = nums[right]; nums[right] = tmp;
        left++; right--;
    }
}

This makes the rotation code read like pseudocode:

java
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);

Testability

Two-pointer functions are pure (they either return a value or mutate the input predictably). They are easy to test:

java
@Test
void testRotate() {
    int[] nums = {1, 2, 3, 4, 5};
    rotate(nums, 2);
    assertArrayEquals(new int[]{4, 5, 1, 2, 3}, nums);
}

Always test:

  • Empty array
  • Single element
  • Two elements
  • Array length equals k (rotation wraps completely)
  • Sorted ascending and sorted descending

Practical Applications

Backend Systems

  • Merge sorted result sets: opposite-direction two pointers merge two sorted arrays in O(n+m), used in merge sort and external sort.
  • Deduplication pipelines: same-direction pointers remove duplicates from sorted event logs in O(n) without allocating a new array — memory efficiency matters at scale.

Databases

  • Two-pointer merge in merge sort: every database's sort algorithm uses a two-pointer merge when combining sorted runs from disk.
  • Index scan range queries: a B-tree range scan uses conceptually similar start/end cursor logic.

Operating Systems

  • Memory compaction: OS memory managers use write-pointer-style compaction to move live pages together, freeing contiguous space.

Networking

  • Sliding window TCP: TCP's send/receive window is a sliding window — a direct generalization of the same-direction two-pointer pattern (Chapter 6 connection).

Distributed Systems

  • Dedup in streaming pipelines: a sorted log stream is deduplicated using a write-pointer approach (e.g., deduplicating Kafka topics with sorted keys).

AI and ML

  • Feature filtering: in data preprocessing, same-direction pointers remove rows with missing values in-place.
  • Sequence labeling: sliding windows over sequences (Chapter 6) use the same mental model as same-direction two pointers.

Failure Modes and Trade-offs

Senior Engineer Insights

  1. The invariant IS the algorithm. Once you state the invariant precisely, writing the code is almost mechanical. Senior engineers define the invariant before touching the keyboard.

  2. Two pointers degenerate to binary search. If your pointer movement has a "skip the entire left half" quality, you are doing binary search without naming it. Recognize the overlap.

  3. Multiple two-pointer passes are still O(n). You can run two separate two-pointer passes and the total is O(n) + O(n) = O(n). Do not hesitate to use multiple passes for clarity.

  4. Cycle detection generalizes beyond linked lists. Any function f: S → S on a finite set will eventually cycle. Floyd's algorithm works on any such function — happy numbers, number sequences, polynomial maps.

Hidden Tricks

  • Rotate an array using XOR swap instead of temp variable: saves the temporary, but reduces readability. Prefer clarity.
  • Two-pointer on a sorted 2D matrix: treat row/column as two coordinates; move left/right or up/down based on comparison.
  • Reverse-then-two-pointer for complex rearrangements: reverse the whole array, then apply two-pointer to the sub-problem.

Performance Tuning

  • Avoid unnecessary bounds checks inside hot loops: pre-check nums.length >= 2 before entering the loop.
  • For linked list fast/slow, the early-exit fast == null || fast.next == null avoids the NullPointerException and lets the JIT eliminate the null check in the common path.

Interview Traps

  1. "Why not use a HashMap?" — Two pointers are O(1) space. Be ready to explain the space trade-off.
  2. "What if the array is not sorted?" — Know when to sort first (O(n log n)) vs when to use a hash map (O(n) but O(n) space).
  3. "Find the cycle start, not just detect it." — Most candidates know phase 1 but flub phase 2. Memorize: reset slow to head, advance both at speed 1.
  4. "Prove your greedy choice." — For Container With Most Water, be ready to give the formal argument for why moving the shorter bar is correct.

Failure Modes and Debugging Strategy

  • Infinite loop: some branch does not move any pointer. Add an assertion that at least one pointer moved per iteration.
  • Wrong result on even-length palindrome: the left < right condition is <, not <=. When left == right on an odd palindrome, the center is compared with itself — which passes trivially.
  • Missed edge case in cycle start: drew the picture correctly but confused the reset target. Always reset slow to head, not to the meeting point.

Condensed Notes

Key Rules

  1. Opposite-direction: sorted array, two ends converge. Move the end that cannot possibly be part of the answer.
  2. Same-direction: filter/compact in-place. write points at the next empty slot. read scans.
  3. Fast/slow: cycle detection, middle finding. Fast = 2×slow. Phase 2: reset slow to head.
  4. In-place reversal: swap from both ends inward. Three reversals = rotation.
  5. Loop invariant: define it before coding. Every pointer move must preserve it.

Templates

java
// Opposite-direction
int left = 0, right = n - 1;
while (left < right) {
    if (condition) { left++; }
    else { right--; }
}

// Same-direction (write pointer)
int write = 0;
for (int read = 0; read < n; read++) {
    if (valid(nums[read])) nums[write++] = nums[read];
}

// Fast/slow — cycle detection
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast) { /* cycle detected */ break; }
}

// Reversal helper
private void reverse(int[] a, int l, int r) {
    while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; }
}

Gotchas

  • k = k % n before rotation.
  • fast != null && fast.next != null — both guards needed.
  • Skip duplicates explicitly in Three Sum: advance left and right past equal values after a match.
  • Do NOT increment mid after swapping with high in Dutch National Flag.
  • Termination: left < right (not <=) for pair-finding; left <= right for reversal.

Decision Shortcuts

Input sorted + pair target           → Opposite-direction
Input unsorted + pair target         → HashMap
Filter/compact in-place              → Same-direction write pointer
Partition into groups                → Dutch Flag (3-way) or write pointer
Cycle or middle in linked list       → Fast/slow
Reverse segment                      → Swap from both ends
Rotate array                         → Three reversals
O(1) space required + any above      → Two-pointer (not HashMap)

Additional Problems

Easy

  1. Two Sum II (Sorted)

    • Find indices of two numbers summing to target in sorted array.
    • Pattern: opposite-direction two pointers.
  2. Valid Palindrome

    • Check if string is palindrome ignoring non-alphanumeric characters.
    • Pattern: opposite-direction two pointers with character skipping.
  3. Remove Element

    • Remove all occurrences of a value in-place; return new length.
    • Pattern: same-direction write pointer.
  4. Reverse String

    • Reverse a char array in-place.
    • Pattern: in-place reversal.
  5. Middle of Linked List

    • Find the middle node of a linked list.
    • Pattern: fast and slow pointers.

Medium

  1. Three Sum

    • Find all unique triplets summing to zero.
    • Pattern: sort + opposite-direction two pointers in loop.
  2. Container With Most Water

    • Maximize water held between two bars.
    • Pattern: opposite-direction, greedy pointer movement.
  3. Sort Colors (Dutch National Flag)

    • Sort array of 0s, 1s, 2s in-place in one pass.
    • Pattern: three-pointer partition.
  4. Linked List Cycle II

    • Return the node where the cycle begins.
    • Pattern: fast/slow — two-phase Floyd's algorithm.
  5. Remove Duplicates from Sorted Array II

    • Allow at most 2 occurrences of each element in-place.
    • Pattern: same-direction write pointer with k-position look-back.

Hard

  1. Trapping Rain Water

    • Compute total water trapped in elevation map.
    • Pattern: opposite-direction two pointers with running max.
  2. Minimum Window Substring (preview — full coverage in Chapter 6)

    • Find shortest substring containing all characters of a target.
    • Pattern: two same-direction pointers (sliding window setup).
  3. Four Sum

    • Find all unique quadruplets summing to a target.
    • Pattern: two nested loops + two-pointer inner scan.
  4. Find the Duplicate Number (Floyd's Cycle)

    • Detect duplicate using value-as-pointer cycle detection.
    • Pattern: fast/slow on value space (no extra space).
  5. Palindrome Linked List

    • Determine if linked list values form a palindrome in O(1) space.
    • Pattern: fast/slow to find middle, in-place reversal of second half, compare.

Key Questions

Q1: How do you solve Two Sum on a sorted array more efficiently than O(n²)?

A: Use opposite-direction two pointers. The sorted order gives us a monotone property: moving the left pointer right increases the sum; moving the right pointer left decreases it. We eliminate a column or row of the search space in O(1) per step, achieving O(n) total.


Q2: When would you use a HashMap for pair sum instead of two pointers?

A: When the array is unsorted and sorting it would cost O(n log n) — more than the O(n) we gain from two pointers over hash map. Both are O(n) time; the trade-off is O(n) space for the hash map vs O(1) for two pointers (which requires sorted input). If the input is sorted or can be sorted cheaply, prefer two pointers for space efficiency.


Q3: Explain the fast/slow pointer cycle detection algorithm and why it works.

A: Once both pointers enter a cycle, fast gains on slow by 1 position per step (fast moves 2, slow moves 1). The gap closes to 0 within at most c steps (cycle length). They must meet. For acyclic lists, fast exits via null. The algorithm is O(n) time and O(1) space.


Q4: After detecting a cycle, how do you find the cycle entry node?

A: Reset slow to head. Advance both slow and fast at speed 1. They will meet at the cycle entry. The mathematical proof: if the distance from head to cycle entry is d and cycle length is c, the meeting point inside the cycle is at distance c - (d mod c) from the entry. Resetting slow to head and advancing both at speed 1 neutralizes this offset in exactly d more steps.


Q5: What is the loop invariant in the Three Sum algorithm?

A: For a fixed anchor nums[i], the invariant is: if a valid pair exists in nums[i+1..n-1] summing to -nums[i], both its elements have indices in [left, right]. We maintain this by always moving the pointer that cannot be part of the answer.


Q6: Why does "move the shorter bar inward" work for Container With Most Water?

A: Suppose height[left] <= height[right]. For any pair (left, right') with right' < right, the area is at most height[left] * (right' - left) < height[left] * (right - left). So no future pairing with the current left can exceed the current area bounded by height[left]. We can safely discard left.


Q7: In Dutch National Flag, why do you NOT increment mid after swapping with high?

A: The value swapped from high to mid is unknown — it has not been examined yet. Incrementing mid would move it into the "1s zone" without verification. The invariant requires that every element below mid is classified. After swapping, the element at mid must be re-examined.


Q8: How do you rotate an array right by k positions in O(1) extra space?

A: Three-reversal trick:

  1. Reverse the entire array.
  2. Reverse [0, k-1].
  3. Reverse [k, n-1].

Example: [1,2,3,4,5], k=2 → [4,5,1,2,3]. Normalize k = k % n first to handle k >= n.


Q9: How do you find the middle of a linked list in one pass?

A: Fast and slow pointers, both starting at head. Advance slow by 1 and fast by 2 each step. When fast reaches null (or fast.next is null), slow is at the middle. For even-length lists, slow lands at the first of the two middle nodes.


Q10: What are the two termination conditions in the fast/slow pointer loop, and why are both needed?

A: while (fast != null && fast.next != null). We need fast != null because the list might be empty. We need fast.next != null because the two-step advance fast.next.next would throw a NullPointerException if fast.next is null. Omitting either guard causes a crash on even-length acyclic lists.


Applied Project

Objective

Build a ListUtility library — a small Java class that demonstrates all four two-pointer techniques on both arrays and linked lists.

Required Features

  1. int[] sortedSquares(int[] nums): squares of sorted array, result sorted, two pointers.
  2. int removeDuplicates(int[] nums, int k): remove duplicates allowing at most k occurrences, write pointer.
  3. void rotate(int[] nums, int k): rotate array right using three reversals.
  4. boolean hasCycle(ListNode head): Floyd's cycle detection.
  5. ListNode findCycleStart(ListNode head): two-phase Floyd's.
  6. ListNode middleNode(ListNode head): fast/slow middle.
  7. boolean isPalindromeList(ListNode head): find middle, reverse second half, compare, restore (optional).

Suggested Java Module Structure

list-utility/
├── src/
│   └── main/java/com/tutorials/
│       ├── ListNode.java
│       ├── ArrayTwoPointer.java    // sortedSquares, removeDuplicates, rotate
│       └── ListTwoPointer.java     // hasCycle, findCycleStart, middleNode, isPalindromeList
└── src/
    └── test/java/com/tutorials/
        ├── ArrayTwoPointerTest.java
        └── ListTwoPointerTest.java

Testing Ideas

  • sortedSquares([-4,-1,0,3,10]) → [0,1,9,16,100]
  • removeDuplicates([1,1,1,2,2,3], 2) → 5
  • rotate([1,2,3,4,5], 2) → [4,5,1,2,3]
  • Build a list with a known cycle and verify hasCycle returns true.
  • Build a 5-node list and verify middleNode returns node 3.
  • Build 1→2→1 and verify isPalindromeList returns true.

Stretch Goals

  1. Make removeDuplicates accept a Predicate<Integer> for the validity condition.
  2. Add isPalindromeArray(int[] nums) and benchmark it against the list version.
  3. Implement int trap(int[] height) (Trapping Rain Water) as a bonus method.
  4. Write a cycle-builder test utility: ListNode buildCycle(int[] values, int cycleIndex).

6: Sliding Window Family

Introduction and Context

Sliding window is the technique for contiguous ranges when recomputing state from scratch is the real bottleneck. Instead of treating every substring or subarray as a fresh object, you keep a live summary of the current range and update only what entered or left. That is why so many apparent O(n^2) range problems collapse into linear scans.

The hard part is not moving the boundaries. It is defining the right window state, deciding what makes the window valid, and recording the answer at the correct moment. Most mistakes come from stale frequency maps, shrinking too early or too late, or measuring the window before it has the required shape.

Core Intuition and Mechanics

Think of a window as a camera frame sliding over a road.

  • Fixed-size window: camera size is locked; you move one step and update what enters/leaves.
  • Variable-size window: camera can zoom in/out; you expand to gain information and shrink to restore validity.

What makes sliding window work is not the picture of a moving frame but the bookkeeping behind it:

  1. Define the boundaries: left and right.
  2. Define the maintained state: sum, counts, distinct values, max frequency, or whatever the problem needs.
  3. Define the invariant that tells you whether the current window is valid.
  4. Update state in a fixed order when right expands and when left shrinks.
  5. Record answers only when the window is in the required form.

In a well-formed window solution, each element enters the window once and leaves it once. That is where the linear-time behavior comes from. If the state update or validity check forces you to rescan the window, you have usually lost the main advantage of the technique.

Core Concepts and Subtopics

Concept Cluster: Window Basics and Fixed Size

Topics in this cluster:

  • 6.1 Sliding Window Pattern; Fixed-size window
Definition

Sliding Window Pattern processes contiguous segments by moving boundaries and reusing previous computations instead of recomputing from scratch.
Fixed-size window keeps window length constant at k.

Why It Matters

If you recompute each length-k segment from scratch, cost is usually O(nk).
With incremental updates, cost becomes O(n).

How It Works

For sum-based fixed window:

  • Add incoming element at right.
  • When window size exceeds k, subtract outgoing element at left and increment left.
  • When window size equals k, evaluate answer.
Internal Mechanics

Each element is added once and removed once, giving amortized constant work per index:
T(n) = O(n)

Java Implementation Notes
  • Use int for typical constraints; use long when sum may overflow.
  • Use clear variable names: left, right, windowSum.
  • Keep update order consistent to avoid off-by-one bugs.
Clean Code Rules If Applicable
  • Keep window update logic in one predictable sequence.
  • Name invariant explicitly in comments if not obvious.
  • Avoid hidden state mutation across methods.
Mini Example

Max sum of subarray of length k:

  • Input: [2, 1, 5, 1, 3, 2], k=3
  • Best window: [5, 1, 3], sum = 9
Common Mistakes
  • Checking answer before window reaches size k
  • Forgetting to remove outgoing element
  • Using int for potentially large cumulative sums
Debugging Tips

Log per iteration:

  • right, added value
  • left, removed value
  • current window size
  • window summary
Practical Note

State your invariant first:
“At any point, windowSum equals sum of nums[left..right].”

Deeper Note

Fixed window generalizes to rolling hash and streaming metrics where memory and latency are strict.

Prefix sum, rolling hash, moving average, stream processors.


Concept Cluster: Variable Window, Longest/Shortest Targets, and Frequency State

Topics in this cluster:

  • 6.2 Variable-size window; Longest and shortest subarray patterns
  • 6.3 Window state management; Frequency-based sliding window problems
Definition

Variable-size window adjusts length dynamically to satisfy a condition.
Typical goals:

  • Longest valid window
  • Shortest valid window

Frequency-based windows track element counts in current range.

Why It Matters

Many string/array constraints are not fixed-length:

  • “at most K distinct”
  • “contains all chars of target”
  • “no duplicate chars”

Without variable windows, brute force is often quadratic.

How It Works

Common pattern:

  1. Expand right and update state.
  2. While invalid, shrink left and clean state.
  3. Record best answer when valid.

For shortest window:

  • Expand until valid, then shrink aggressively to minimize length.
    For longest window:
  • Expand greedily and shrink only when invalid.
Internal Mechanics

Critical state examples:

  • freq map: char -> count
  • matchedTypes or matchedChars
  • distinctCount
  • maxFreqInWindow (for replacement-type problems)

The correctness depends on precise synchronization between boundaries and state updates.

Java Implementation Notes
  • Prefer int[128] for ASCII speed.
  • Use HashMap<Character, Integer> for generic Unicode-like cases.
  • Remove keys whose count becomes zero to keep distinct counts accurate.
Clean Code Rules If Applicable
  • Separate helper methods:
    • addChar(c), removeChar(c), isValid()
  • Keep validity logic centralized.
  • Avoid duplicated condition checks across loop bodies.
Mini Example

Longest substring without repeating chars:

  • Expand right and increment frequency.
  • While frequency of current char > 1, move left and decrement.
  • Update max length.
Common Mistakes
  • Shrinking only once when multiple shrinks are required
  • Forgetting zero-count cleanup in map-based distinct tracking
  • Mixing “validity for shortest” with “validity for longest” strategy
Debugging Tips

Track after each boundary move:

  • left, right
  • key counts
  • validity flag
  • current best answer
Practical Note

If problem says “longest/shortest contiguous segment satisfying condition,” sliding window is a top candidate.

Deeper Note

Frequency windows are a special case of incremental constraint maintenance, similar to online algorithms and stream analytics.

Two pointers, hash-based counting, monotonic queue (for max/min windows), event stream processing.


Concept Cluster: Trade-offs, Debugging, Recognition, and Brute-force Upgrade Path

Topics in this cluster:

  • 6.4 Fixed-size window versus variable-size window trade-offs
  • 6.5 Debugging windows; Off-by-one handling and stale state checks
  • 6.6 Window recognition signals and brute-force to linear-scan upgrades
Definition

Trade-off analysis decides whether fixed or variable window is appropriate.
Recognition signals help quickly map problem text to a window strategy.

Why It Matters

Wrong template selection causes:

  • overcomplicated code
  • incorrect logic
  • unnecessary O(n^2) fallback
How It Works

Decision guide:

  • Exact length k requested -> fixed-size window.
  • Constraint-driven window (“at most”, “at least”, “contains all”) -> variable-size.
  • Non-contiguous requirement -> usually not sliding window.

Brute-force upgrade:

  1. Write baseline nested loops.
  2. Identify repeated recomputation.
  3. Replace recomputation with incremental add/remove state.
  4. Prove each element enters/exits limited times.
Internal Mechanics

Off-by-one hot spots:

  • window size formula: right - left + 1
  • shrink loop condition
  • answer update timing (before or after shrink)

Stale state is when map/sum/counter no longer matches actual window boundaries.

Java Implementation Notes
  • Use assertions in debug mode:
    • window size non-negative
    • counts never negative
  • Keep one source of truth for counts.
Clean Code Rules If Applicable
  • One loop for expand, one nested while for shrink.
  • Keep mutation order stable and documented.
  • Do not interleave unrelated logic inside shrink loop.
Mini Example

Problem: shortest subarray with sum >= target (positive numbers)

  • Expand right accumulating sum
  • While sum >= target: update answer, then shrink left
Common Mistakes
  • Updating answer in invalid state
  • Shrinking too early
  • Ignoring positive-only prerequisite for sum-based variable windows
Debugging Tips

When output is wrong:

  1. Print first failing test and full left/right movement trace.
  2. Verify state after each left/right mutation.
  3. Add assertions for map counts and invariants.
Practical Note

Explain not only code, but why each pointer moves and why complexity is linear.

Deeper Note

Amortized argument is often expected: each index is touched by left/right at most once each.

Amortized analysis, invariants, online processing, stream windows.

Worked Examples

Worked Example 1: Maximum Sum Subarray of Size K

Problem or Design Scenario

Given an integer array and integer k, return the maximum sum among all contiguous subarrays of size k.

Technical Value

This is a standard fixed-size sliding window problem and a foundation for rolling analytics.

Constraints or Assumptions
  • 1 <= k <= n
  • Values may be negative
  • Use long if values are large
Example Input/Output or Usage Scenario
  • Input: nums = [2, 1, 5, 1, 3, 2], k = 3
  • Output: 9
Brute Force or Naive Approach

For every start index, sum next k elements.

  • Time: O(nk)
  • Space: O(1)
Better or Optimized Approach

Maintain rolling sum of current length-k window:

  • Add nums[right]
  • If size > k, subtract nums[left], left++
  • If size == k, update max
Why the Better Approach Works

Each element is added once and removed once. No repeated summation.

Decision Process

Start with brute force for correctness.
Then ask: “What recomputation repeats?”
Repeated piece is subarray sum; replace it with incremental updates.

Java Solution
java
import java.util.*;

public class MaxSumFixedWindow {
    public static long maxSumSubarrayOfSizeK(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
            throw new IllegalArgumentException("Invalid input");
        }

        long windowSum = 0L;
        long maxSum = Long.MIN_VALUE;
        int left = 0;

        for (int right = 0; right < nums.length; right++) {
            windowSum += nums[right];

            if (right - left + 1 > k) {
                windowSum -= nums[left];
                left++;
            }

            if (right - left + 1 == k) {
                maxSum = Math.max(maxSum, windowSum);
            }
        }

        return maxSum;
    }

    public static void main(String[] args) {
        int[] nums = {2, 1, 5, 1, 3, 2};
        System.out.println(maxSumSubarrayOfSizeK(nums, 3)); // 9
    }
}
Dry Run

For [2,1,5,1,3,2], k=3:

  • right=0 sum=2
  • right=1 sum=3
  • right=2 sum=8 max=8
  • right=3 sum=9 remove 2 =>7 max=8
  • right=4 sum=10 remove 1 =>9 max=9
  • right=5 sum=11 remove 5 =>6 max=9
Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • k = 1
  • k = n
  • all negatives
  • very large values causing int overflow
Common Mistakes
  • Updating max before window reaches size k
  • Not removing outgoing element when size exceeds k
  • Minimum sum of size k
  • Average over fixed window
  • Count windows meeting threshold
Validation

Test:

  • single element
  • all negative
  • mixed positive/negative
  • max int values with long sum check

Worked Example 2: Longest Substring Without Repeating Characters

Problem or Design Scenario

Find length of the longest substring with all unique characters.

Technical Value

Classic variable-size and frequency/state-maintenance problem.

Constraints or Assumptions
  • String may contain ASCII characters
  • Return only length
Example Input/Output or Usage Scenario
  • Input: "abcabcbb"
  • Output: 3 ("abc")
Brute Force or Naive Approach

Check all substrings; test uniqueness using set.

  • Time: O(n^3) naive, or O(n^2) with optimization
  • Space: up to O(n)
Better or Optimized Approach

Use variable window with frequency array.

  • Expand right, increment freq.
  • While freq[current] > 1, shrink left and decrement.
  • Track max length.
Why the Better Approach Works

Window invariant: all characters in window have frequency at most 1.
Shrink restores validity whenever duplicate appears.

Decision Process

When constraints mention “longest contiguous substring with condition,” prefer grow-and-shrink window, not restart-from-scratch loops.

Java Solution
java
import java.util.*;

public class LongestUniqueSubstring {
    public static int lengthOfLongestUniqueSubstring(String s) {
        if (s == null) {
            throw new IllegalArgumentException("Input string is null");
        }

        int[] freq = new int[128];
        int left = 0;
        int best = 0;

        for (int right = 0; right < s.length(); right++) {
            char rc = s.charAt(right);
            freq[rc]++;

            while (freq[rc] > 1) {
                char lc = s.charAt(left);
                freq[lc]--;
                left++;
            }

            best = Math.max(best, right - left + 1);
        }

        return best;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestUniqueSubstring("abcabcbb")); // 3
        System.out.println(lengthOfLongestUniqueSubstring("bbbbb"));    // 1
        System.out.println(lengthOfLongestUniqueSubstring("pwwkew"));   // 3
    }
}
Dry Run

Input "pwwkew":

  • right=0 'p' valid, best=1
  • right=1 'w' valid, best=2
  • right=2 'w' duplicate -> shrink left until one 'w' remains, window "w", best=2
  • right=3 'k' => "wk", best=2
  • right=4 'e' => "wke", best=3
  • right=5 'w' duplicate -> shrink to "kew", best=3
Time and Space Complexity
  • Time: O(n)
  • Space: O(1) for fixed charset (ASCII), else O(Σ)
Edge Cases
  • Empty string
  • One character
  • All same characters
  • All unique characters
Common Mistakes
  • Shrinking only once instead of while invalid
  • Forgetting to decrement outgoing char count
  • Longest substring with at most K distinct
  • Longest repeating character replacement
Validation

Use randomized tests comparing with brute force for small strings.


Worked Example 3: Minimum Window Substring

Problem or Design Scenario

Given strings s and t, find the smallest substring of s containing all characters of t with multiplicity.

Technical Value

A high-signal interview problem for advanced frequency-based variable windows and stale-state control.

Constraints or Assumptions
  • ASCII input for this implementation
  • If no valid window exists, return empty string
Example Input/Output or Usage Scenario
  • Input: s="ADOBECODEBANC", t="ABC"
  • Output: "BANC"
Brute Force or Naive Approach

Enumerate all substrings and check containment against t frequencies.

  • Time: O(n^3) or O(n^2 · Σ)
  • Space: O(Σ)
Better or Optimized Approach
  • Build need[] from t.
  • Expand right and update window[].
  • Count how many required chars are currently satisfied.
  • When fully satisfied, shrink left to get minimum window.
Why the Better Approach Works

Only minimal work per boundary movement.
Invariant: when matched == t.length(), window is valid.

Decision Process

Use explicit counters rather than repeated map comparison.
This avoids costly full-map checks on every step.

Java Solution
java
import java.util.*;

public class MinimumWindowSubstring {
    public static String minWindow(String s, String t) {
        if (s == null || t == null || t.isEmpty() || s.isEmpty()) {
            return "";
        }

        int[] need = new int[128];
        for (char c : t.toCharArray()) {
            need[c]++;
        }

        int[] window = new int[128];
        int matched = 0;
        int left = 0;
        int minLen = Integer.MAX_VALUE;
        int start = 0;

        for (int right = 0; right < s.length(); right++) {
            char rc = s.charAt(right);
            window[rc]++;

            if (need[rc] > 0 && window[rc] <= need[rc]) {
                matched++;
            }

            while (matched == t.length()) {
                int len = right - left + 1;
                if (len < minLen) {
                    minLen = len;
                    start = left;
                }

                char lc = s.charAt(left);
                if (need[lc] > 0 && window[lc] <= need[lc]) {
                    matched--;
                }
                window[lc]--;
                left++;
            }
        }

        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
    }

    public static void main(String[] args) {
        System.out.println(minWindow("ADOBECODEBANC", "ABC")); // BANC
        System.out.println(minWindow("a", "aa"));              // ""
    }
}
Dry Run

For s="ADOBECODEBANC", t="ABC":

  • Expand until first valid around "ADOBEC"
  • Shrink to minimal valid for that right boundary
  • Continue expansion and shrinking
  • Best final window becomes "BANC"
Time and Space Complexity
  • Time: O(n)
  • Space: O(Σ)
Edge Cases
  • t longer than s
  • repeated chars in t (e.g., "AABC")
  • no valid window
Common Mistakes
  • Using distinct-match count when multiplicity is required
  • Incorrect matched decrement order during shrink
  • Smallest window containing all distinct chars of s
  • Minimum window subsequence (different problem, not standard sliding window)
Validation

Test multiplicity-heavy targets:

  • s="AAABBC", t="AABC" -> "AABBC"

Solved Problems

Problem 1: Maximum Average Subarray I (Easy)

Problem Statement

Find the maximum average value of any contiguous subarray of size k.

Constraints or Assumptions
  • 1 <= k <= n
  • Return double
Example
  • nums=[1,12,-5,-6,50,3], k=4
  • output=12.75
Brute Force or Naive Solution

Compute each length-k sum separately, track max.

  • O(nk)
Optimized or Refactored Solution

Fixed-size rolling sum.

  • O(n)
Why the Final Approach Works

Reuses prior window sum and updates by entry/exit delta.

Decision Process

When only fixed length matters, avoid variable-window complexity.

Java Solution
java
import java.util.*;

public class MaxAverageSubarray {
    public static double findMaxAverage(int[] nums, int k) {
        if (nums == null || nums.length < k || k <= 0) {
            throw new IllegalArgumentException("Invalid input");
        }

        long sum = 0;
        for (int i = 0; i < k; i++) sum += nums[i];
        long maxSum = sum;

        for (int right = k; right < nums.length; right++) {
            sum += nums[right] - nums[right - k];
            maxSum = Math.max(maxSum, sum);
        }

        return (double) maxSum / k;
    }

    public static void main(String[] args) {
        System.out.println(findMaxAverage(new int[]{1, 12, -5, -6, 50, 3}, 4)); // 12.75
    }
}
Dry Run

Initial sum=2 (first 4 elems), then slide and update max at each step; best sum=51.

Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • all negatives
  • k=n
  • minimum average of size k
  • threshold count of windows

Problem 2: Maximum Number of Vowels in a Substring of Given Length (Easy)

Problem Statement

Given string s and integer k, return max vowels in any substring of length k.

Constraints or Assumptions
  • lowercase English letters
Example
  • s="abciiidef", k=3 -> 3
Brute Force or Naive Solution

Count vowels for every length-k substring from scratch.

Optimized or Refactored Solution

Fixed-size window + delta update for entering/leaving chars.

Why the Final Approach Works

Window vowel count remains accurate after each single-step slide.

Decision Process

Prefer simple boolean helper for readability and testability.

Java Solution
java
import java.util.*;

public class MaxVowelsFixedWindow {
    private static boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }

    public static int maxVowels(String s, int k) {
        if (s == null || k <= 0 || k > s.length()) {
            throw new IllegalArgumentException("Invalid input");
        }

        int count = 0;
        for (int i = 0; i < k; i++) {
            if (isVowel(s.charAt(i))) count++;
        }
        int best = count;

        for (int right = k; right < s.length(); right++) {
            if (isVowel(s.charAt(right))) count++;
            if (isVowel(s.charAt(right - k))) count--;
            best = Math.max(best, count);
        }

        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxVowels("abciiidef", 3)); // 3
    }
}
Dry Run

Window "abc" =>1, "bci"=>1, "cii"=>2, "iii"=>3, best=3.

Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • k=1
  • no vowels
  • all vowels
  • max consonants in size k
  • mixed-case vowel handling

Problem 3: Longest Subarray with Sum at Most K (Medium, Positive Numbers)

Problem Statement

Given positive integers nums and target k, find longest contiguous subarray with sum <= k.

Constraints or Assumptions
  • nums contains positive integers only
Example
  • nums=[1,2,1,0,1,1,0], k=4 -> 5
Brute Force or Naive Solution

Try all subarrays, compute sums.

Optimized or Refactored Solution

Variable-size window:

  • Expand right add nums[right]
  • While sum > k shrink left
  • Update max length
Why the Final Approach Works

Positive-only property ensures shrinking reduces sum and expanding increases monotonic accumulation behavior.

Decision Process

Validate positivity assumption first. If negatives allowed, this template may fail.

Java Solution
java
import java.util.*;

public class LongestSubarraySumAtMostK {
    public static int longestAtMostK(int[] nums, int k) {
        if (nums == null || k < 0) {
            throw new IllegalArgumentException("Invalid input");
        }

        int left = 0;
        long sum = 0;
        int best = 0;

        for (int right = 0; right < nums.length; right++) {
            if (nums[right] < 0) {
                throw new IllegalArgumentException("Only positive numbers allowed");
            }
            sum += nums[right];

            while (sum > k && left <= right) {
                sum -= nums[left++];
            }

            best = Math.max(best, right - left + 1);
        }

        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestAtMostK(new int[]{1, 2, 1, 0, 1, 1, 0}, 4)); // 5
    }
}
Dry Run

Grow until sum exceeds 4, then shrink. Best valid length reaches 5.

Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • k=0 with zeros present
  • single element > k
  • empty array
  • shortest subarray with sum >= k (positive numbers)
  • exact sum k with prefix sums

Problem 4: Longest Repeating Character Replacement (Medium)

Problem Statement

Given uppercase string s and integer k, return length of longest substring that can become same character after replacing at most k chars.

Constraints or Assumptions
  • s contains A-Z
  • k >= 0
Example
  • s="AABABBA", k=1 -> 4
Brute Force or Naive Solution

Check all substrings; for each, compute replacements needed from char frequencies.

Optimized or Refactored Solution

Variable window with frequency array and maxFreq in current window:

  • valid if windowSize - maxFreq <= k
  • shrink when invalid
Why the Final Approach Works

Needed replacements are exactly non-majority chars in the window.

Decision Process

Use array over map for fixed alphabet speed and simplicity.

Java Solution
java
import java.util.*;

public class LongestRepeatingReplacement {
    public static int characterReplacement(String s, int k) {
        if (s == null || k < 0) {
            throw new IllegalArgumentException("Invalid input");
        }

        int[] freq = new int[26];
        int left = 0;
        int maxFreq = 0;
        int best = 0;

        for (int right = 0; right < s.length(); right++) {
            int idx = s.charAt(right) - 'A';
            freq[idx]++;
            maxFreq = Math.max(maxFreq, freq[idx]);

            while ((right - left + 1) - maxFreq > k) {
                freq[s.charAt(left) - 'A']--;
                left++;
            }

            best = Math.max(best, right - left + 1);
        }

        return best;
    }

    public static void main(String[] args) {
        System.out.println(characterReplacement("AABABBA", 1)); // 4
    }
}
Dry Run

Window expands to size 5 but invalid, shrinks, best remains 4.

Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • k=0
  • all same chars
  • empty string
  • lowercase/mixed alphabet
  • returning actual substring

Problem 5: Substring with Concatenation of All Words (Hard)

Problem Statement

Given string s and words[] equal-length words, return all start indices where substring is concatenation of all words exactly once, contiguous.

Constraints or Assumptions
  • all words have same length
  • words length may repeat
Example
  • s="barfoothefoobarman", words=["foo","bar"] -> [0,9]
Brute Force or Naive Solution

For each start, split chunks and compare multisets.

Optimized or Refactored Solution

Use sliding windows over aligned offsets:

  • For each offset in [0, wordLen-1], slide by wordLen.
  • Maintain window word frequency.
  • Shrink when a word frequency exceeds allowed count.
  • Record when matched word count equals words.length.
Why the Final Approach Works

Alignment by word length reduces state updates to chunk boundaries and preserves contiguous segmentation validity.

Decision Process

Hard part is not map logic; hard part is index alignment and stale word cleanup.

Java Solution
java
import java.util.*;

public class SubstringConcatWords {
    public static List<Integer> findSubstring(String s, String[] words) {
        List<Integer> result = new ArrayList<>();
        if (s == null || words == null || words.length == 0 || words[0].isEmpty()) {
            return result;
        }

        int wordLen = words[0].length();
        int totalWords = words.length;
        int windowLen = wordLen * totalWords;
        if (s.length() < windowLen) return result;

        Map<String, Integer> target = new HashMap<>();
        for (String w : words) {
            target.put(w, target.getOrDefault(w, 0) + 1);
        }

        for (int offset = 0; offset < wordLen; offset++) {
            int left = offset;
            int count = 0;
            Map<String, Integer> window = new HashMap<>();

            for (int right = offset; right + wordLen <= s.length(); right += wordLen) {
                String word = s.substring(right, right + wordLen);

                if (!target.containsKey(word)) {
                    window.clear();
                    count = 0;
                    left = right + wordLen;
                    continue;
                }

                window.put(word, window.getOrDefault(word, 0) + 1);
                count++;

                while (window.get(word) > target.get(word)) {
                    String leftWord = s.substring(left, left + wordLen);
                    window.put(leftWord, window.get(leftWord) - 1);
                    if (window.get(leftWord) == 0) {
                        window.remove(leftWord);
                    }
                    left += wordLen;
                    count--;
                }

                if (count == totalWords) {
                    result.add(left);

                    String leftWord = s.substring(left, left + wordLen);
                    window.put(leftWord, window.get(leftWord) - 1);
                    if (window.get(leftWord) == 0) {
                        window.remove(leftWord);
                    }
                    left += wordLen;
                    count--;
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(findSubstring("barfoothefoobarman", new String[]{"foo", "bar"})); // [0, 9]
    }
}
Dry Run

Offset 0:

  • read "bar","foo" -> matched 2 words => add 0
  • continue...
  • later "foo","bar" -> add 9
Time and Space Complexity
  • Time: O(n * wordLen) effectively linear in chunks
  • Space: O(m) where m is number of distinct words
Edge Cases
  • repeated words in dictionary
  • no matches
  • overlapping matches
  • variable word lengths (much harder)
  • wildcard dictionary entries

Recognition Guide

Use sliding window when you see:

  • contiguous subarray/substring
  • longest/shortest segment with constraint
  • at most/at least/exactly K style conditions
  • repeated recomputation across overlapping ranges

Recognition signals:

  • “Find maximum/minimum over all contiguous segments”
  • “Contains all required characters”
  • “No duplicates / at most K distinct”
  • “Fixed size K”

Constraint clues:

  • large n (e.g., 10^5 or 10^6), brute force infeasible
  • expected near-linear solution

Invariants to watch:

  • state matches current [left..right]
  • validity condition is always explicit
  • shrink loop restores validity fully, not partially

Common traps:

  • using sliding window when condition is non-monotonic
  • applying positive-number sum window logic to arrays with negatives
  • stale map counts after left moves

When not to use:

  • non-contiguous subsequence problems
  • global reordering problems
  • constraints that do not preserve monotonic validity under shrink/expand

Brute force to linear-scan upgrade checklist:

  1. Write brute force.
  2. Identify overlapping work.
  3. Define window state.
  4. Define validity.
  5. Convert to add/remove updates.
  6. Prove each pointer moves at most n times.

Comparison Tables

Aspect Fixed-Size Window Variable-Size Window
Window length Constant Dynamic
Typical goal best metric for size k longest/shortest valid window
Core operation add right, remove left when size > k add right, shrink while invalid
Complexity usually O(n) usually O(n) amortized
State complexity low to medium medium to high
Common bugs wrong size checks incorrect shrink logic, stale state
Best use cases moving average, max sum of length k min cover, at-most-K distinct
Approach Runtime Space Simplicity Maintainability Notes
Brute force contiguous scan O(n^2) to O(n^3) low high initially low for large constraints good baseline for correctness
Sliding window with sum O(n) O(1) high high requires monotonic condition for variable sum windows
Sliding window with frequency map O(n) O(Σ) medium medium powerful for string constraints
Pattern Use When Not Ideal When
Sliding window contiguous + incremental condition non-contiguous or non-monotonic constraints
Prefix sum + hashmap exact sum targets, count subarrays window validity not monotonic
Monotonic deque window min/max queries generic frequency constraints

Design and Decision Making

Relevant design patterns:

  • Strategy Pattern: select fixed-window or variable-window strategy by problem shape.
  • Template Method style: common skeleton for expand/shrink with custom validity logic.

Clean code rules for this chapter:

  • Keep invariant in one sentence near loop.
  • Use helper methods for add/remove/isValid in complex windows.
  • Separate result update logic from state mutation logic.
  • Prefer descriptive names: requiredCount, matchedCount, distinctCount.

Reusable architecture ideas:

  • Build a small WindowState class for complex problems:
    • add(x), remove(x), isValid()
  • Makes testing easier and reduces duplicated bug-prone map logic.

Pragmatic choices:

  • Start with arrays for fixed alphabets (performance, simpler).
  • Use HashMap for flexible token domains.
  • Avoid over-abstraction on easy problems; add abstraction only once logic repeats.

Class/module organization:

  • problem-specific class per algorithm
  • private helper methods for validation and state updates
  • avoid global mutable state in interview code

Naming conventions:

  • left/right for boundaries
  • need/window for frequency maps
  • best, minLen, maxLen for objective variables

API design:

  • Validate inputs early
  • return neutral values (empty string/list) when no solution
  • throw IllegalArgumentException when misuse is programming error

Testability:

  • deterministic function signatures
  • include brute-force checker for small random tests
  • add edge-case unit tests for empty, single element, repeated chars

Practical Applications

Backend systems:

  • rolling error-rate windows
  • request throughput over last N seconds

Frontend apps:

  • real-time typing analytics over recent keystrokes
  • recent activity summaries

Databases:

  • moving aggregates over time-series partitions
  • stream processing windows in event pipelines

Distributed systems:

  • rate limiter counters in sliding time windows
  • anomaly detection over recent metrics

Operating systems:

  • CPU scheduler metrics across recent time slices

Networking:

  • packet-loss monitoring over recent packets

AI systems:

  • token-window based local statistics
  • streaming feature extraction on recent events

Mobile apps:

  • battery and sensor trend smoothing

Games:

  • damage/heal streak analysis over last k actions
  • latency smoothing windows for matchmaking

Failure Modes and Trade-offs

Senior engineer insights:

  • Most window bugs are state-sync bugs, not algorithm-choice bugs.
  • In hard problems, draw timeline of boundary movement first.

Hidden tricks:

  • For ASCII problems, int[128] is often faster and cleaner than HashMap.
  • For “contains all with multiplicity,” track matched character count, not just distinct types.

Performance tuning:

  • avoid repeated substring creation in hot loops unless necessary
  • avoid map.remove/add churn if count arrays can work

Trade-off thinking:

  • clearer code with small constant overhead is often better than hyper-optimized unreadable loops
  • optimize only after baseline correctness and profiling

Interview traps:

  • claiming O(n) without amortized pointer argument
  • forgetting prerequisites (positive numbers) for sum-based variable windows

Common weak spots:

  • update order in shrink loop
  • off-by-one around right-left+1
  • handling no-solution output

Failure modes and debugging strategy:

  1. Reproduce smallest failing input.
  2. Log every boundary move and state delta.
  3. Assert non-negative counts.
  4. Compare against brute force on random small tests.

Condensed Notes

Key rules:

  • contiguous + optimization pressure -> think sliding window
  • fixed length -> fixed-size template
  • condition-based length -> variable-size template

Templates:

  • Fixed:
    • expand right
    • if size > k remove left
    • if size == k record answer
  • Variable:
    • expand right
    • while invalid shrink left
    • record answer in valid state

Formulas:

  • window size = right - left + 1
  • replacement needed = window size - maxFreq

Gotchas:

  • stale frequency after left++
  • answer updated in wrong phase
  • negative numbers breaking monotonic sum assumptions

Decision shortcuts:

  • “exactly length k” -> fixed
  • “longest/shortest satisfying condition” -> variable
  • “non-contiguous” -> probably not sliding window

Quick checklist:

  1. invariant defined?
  2. add/remove symmetric?
  3. shrink uses while when needed?
  4. edge cases tested?

Additional Problems

Easy (5)

  1. Title: Max Sum Size K
    One-line prompt: Find maximum sum among all subarrays of length k.
    Expected pattern or concept: Fixed-size window with rolling sum.

  2. Title: Min Sum Size K
    One-line prompt: Find minimum sum among all subarrays of length k.
    Expected pattern or concept: Fixed-size window.

  3. Title: Max Vowels Size K
    One-line prompt: Return max vowel count in any substring of size k.
    Expected pattern or concept: Fixed-size + incremental count.

  4. Title: Average Threshold Count
    One-line prompt: Count windows of size k whose average >= threshold.
    Expected pattern or concept: Fixed-size numeric window.

  5. Title: First Negative in Every Window
    One-line prompt: For each size-k window, report first negative element.
    Expected pattern or concept: Fixed-size + auxiliary queue.

Medium (5)

  1. Title: Longest Unique Substring
    One-line prompt: Find longest substring without repeating chars.
    Expected pattern or concept: Variable-size + frequency state.

  2. Title: At Most K Distinct
    One-line prompt: Longest substring with at most k distinct characters.
    Expected pattern or concept: Variable-size + distinct counter.

  3. Title: Fruit Into Baskets
    One-line prompt: Longest subarray containing at most two distinct values.
    Expected pattern or concept: Variable-size map counts.

  4. Title: Character Replacement
    One-line prompt: Longest substring transformable to single char with <=k replacements.
    Expected pattern or concept: Variable-size + maxFreq invariant.

  5. Title: Permutation in String
    One-line prompt: Check if s2 contains a permutation of s1.
    Expected pattern or concept: Fixed-size frequency matching.

Hard (5)

  1. Title: Minimum Window Substring
    One-line prompt: Smallest window containing all chars of target with multiplicity.
    Expected pattern or concept: Variable-size frequency cover.

  2. Title: Substring Concatenation of All Words
    One-line prompt: Find all starts of concatenated dictionary words.
    Expected pattern or concept: Multi-offset chunked sliding window.

  3. Title: Longest Substring with Exactly K Distinct
    One-line prompt: Find longest substring with exactly k distinct chars.
    Expected pattern or concept: At-most trick + careful validity.

  4. Title: Count Subarrays with Product Less Than K
    One-line prompt: Count all contiguous subarrays with product < k.
    Expected pattern or concept: Variable-size multiplicative window.

  5. Title: Minimum Size Subarray Sum
    One-line prompt: Smallest subarray with sum >= target (positive ints).
    Expected pattern or concept: Variable-size shrink-to-minimize.

Key Questions

  1. Question: What distinguishes fixed-size from variable-size sliding window?
    Answer: Fixed-size has constant length and always evicts once size exceeds k. Variable-size adjusts boundaries based on validity conditions and usually shrinks in a while loop.

  2. Question: Why is sliding window often linear?
    Answer: Each element enters and leaves the window at most once, so left and right each move at most n steps.

  3. Question: When does sum-based variable window fail?
    Answer: With negative numbers, monotonic behavior breaks, so shrink/expand rules may skip valid solutions.

  4. Question: How do you prevent stale frequency-map state?
    Answer: Update map exactly when boundaries move; decrement before left++ and remove zero-count keys when distinct counts matter.

  5. Question: What is the key invariant in minimum window substring?
    Answer: Current window is valid when matched required characters count equals target length (with multiplicity).

  6. Question: Why use arrays instead of HashMap in many string windows?
    Answer: For bounded charsets, arrays are faster, simpler, and avoid hashing overhead.

  7. Question: Common off-by-one mistake?
    Answer: Using right-left instead of right-left+1 for current length.

  8. Question: How do you debug wrong output quickly?
    Answer: Compare with brute force on small random inputs and log boundary/state transitions at first mismatch.

  9. Question: Can sliding window solve non-contiguous subsequence problems?
    Answer: Usually no. Sliding window is for contiguous segments.

  10. Question: How do you explain trade-offs in interview?
    Answer: Present brute force baseline, identify repeated work, show incremental state updates, and justify complexity and correctness with invariants.

Applied Project

Objective:

  • Build a Sliding Window Analytics Toolkit for event streams.

Required features:

  • fixed-size metrics: moving sum, moving average, max count condition
  • variable-size detectors: longest stable streak, shortest alert-cover interval
  • string analyzer: min cover and uniqueness windows

Suggested Java module structure:

  • analyzer.core
    • WindowState.java
    • FixedWindowProcessor.java
    • VariableWindowProcessor.java
  • analyzer.metrics
    • MovingAverage.java
    • ThresholdCounter.java
  • analyzer.string
    • UniqueSubstringAnalyzer.java
    • MinCoverAnalyzer.java
  • analyzer.test
    • BruteForceOracleTests.java
    • EdgeCaseTests.java

Testing ideas:

  • deterministic unit tests for known examples
  • randomized differential tests against brute force for small inputs
  • performance test with large synthetic streams

Stretch goals:

  • generic tokenizer support
  • pluggable window state strategies
  • metric export hooks for monitoring dashboards

7: Linked List + Stack + Queue + Deque

Introduction and Context

This chapter moves from plain index-based traversal into structures where correctness depends on disciplined updates at the ends and between nodes. A wrong array index usually produces an obvious bug. A wrong link update or stale stack, queue, or deque state can quietly damage the structure and mislead every later operation.

These structures are useful precisely because they restrict access. Linked lists make rewiring cheap when you already know the position. Stacks and queues keep insertion and removal simple by limiting which end you can touch. Deques open both ends but still avoid the cost of arbitrary middle edits. Monotonic variants go further and remove state that can no longer influence future answers. The recurring failures are lost links, underflow, stale indexes, wrong wraparound math, and cleanup done in the wrong order.

Core Intuition and Mechanics

Think of these structures as controlled-access views over data rather than general-purpose containers.

  • A linked list makes structural edits cheap when the neighboring nodes are already known.
  • A stack stores the most recent unresolved state.
  • A queue stores the oldest pending work.
  • A deque gives both ends while still avoiding arbitrary middle edits.

The mechanics that matter are invariant ownership and cleanup order:

  • For linked lists, know which pointers define the current shape and what must be saved before rewiring.
  • For stacks, queues, and deques, know which end is authoritative and when empty, full, or stale conditions are checked.
  • For monotonic structures, know which elements can no longer influence future answers and must be removed immediately.
  • For simulation problems, know exactly which state persists between steps and what must be reset.

Correctness in this chapter comes from naming the invariant before coding, updating only the state that is supposed to change, and checking edge cases such as empty structures, single elements, or full circular buffers as part of the normal design instead of as afterthought patches.

Core Concepts and Subtopics

Concept Cluster: Linked List Shapes and Navigation

Topics in this cluster:

  • 7.1 Singly linked lists; Doubly linked lists; Circular linked lists
Definition
  • Singly linked list: node has value + next pointer.
  • Doubly linked list: node has value + prev + next pointers.
  • Circular linked list: last node points back to head (or tail loops to head).
Why It Matters

These models enable O(1) inserts/deletes at known positions (like head/tail) without shifting large memory blocks.

How It Works
  • Singly list is minimal memory, simple forward traversal.
  • Doubly list supports backward traversal and easier middle-node deletion.
  • Circular list simplifies repeated round-robin traversal.
Internal Mechanics

Each node is a separate object. Traversal is pointer chasing, so cache locality is weaker than arrays. This affects real-world performance even when asymptotic complexity matches.

Java Implementation Notes
  • Use static nested Node classes when practical.
  • Maintain head and tail when you need O(1) append.
  • For circular lists, define one authority pointer (usually tail) to reduce ambiguity.
Clean Code Rules If Applicable
  • Keep list mutation logic in one method per operation (insertAtHead, deleteByValue, etc.).
  • Do not duplicate pointer fix-up logic across methods.
  • Use explicit null checks early.
Mini Example

Insert 3 values into singly list: 1 -> 2 -> 3 -> null.

Common Mistakes
  • Losing the rest of list by overwriting next too early.
  • Forgetting to update tail when deleting last node.
  • Infinite loop in circular list traversal due to wrong stop condition.
Debugging Tips

Print node identities and values during mutation. For circular lists, add max-step guard in debug traversals.

Practical Note

State both complexity and hidden practical trade-off: linked list has pointer overhead and poor cache locality.

Deeper Note

Circular doubly lists are useful for LRU caches and scheduler loops because removal and insertion at known nodes are O(1).

  • Memory layout
  • object allocation pressure
  • iterator safety

Concept Cluster: Pointer Manipulation and Structural Transformations

Topics in this cluster:

  • 7.2 Reversal techniques; Merge and pointer manipulation problems; Cycle detection
Definition

Pointer manipulation means changing links without losing reachable nodes.

Why It Matters

Many high-value interview and production operations are just careful link rewrites.

How It Works
  • Reversal: reroute each node's next to previous.
  • Merge: progressively connect smaller head among two sorted lists.
  • Cycle detection: Floyd's fast/slow pointers.
Internal Mechanics

For reversal, invariant during iteration:

  • prev is already reversed prefix.
  • curr is current node to process.
  • next stores the not-yet-processed suffix entry.

For cycle detection:

  • If fast pointer catches slow pointer, cycle exists.
  • Reset one pointer to head; move both one step to get cycle start.
Java Implementation Notes
  • Favor iterative reverse for stack safety.
  • For merge, use dummy node to simplify head handling.
  • For cycle problems, keep methods pure and avoid mutating list.
Clean Code Rules If Applicable
  • Use small helper methods: reverse, mergeSorted, findCycleStart.
  • Document pointer invariants in short comments where non-obvious.
Mini Example

Reverse 1->2->3 becomes 3->2->1.

Common Mistakes
  • Not storing next before changing curr.next.
  • Advancing wrong pointer in merge.
  • Mistaking value equality for node identity in cycle detection.
Debugging Tips

Draw 3-pointer table (prev/curr/next) per iteration.

Practical Note

You can derive cycle start proof quickly with distance equations from meeting point.

Deeper Note

Acyclic merge and in-place reverse are examples of local rewiring; similar reasoning appears later in tree rotations.

  • two pointers
  • loop invariants
  • shape preservation

Concept Cluster: Stack Foundations and Simulation Thinking

Topics in this cluster:

  • 7.3 Array-based and linked stacks; Stack Simulation Pattern
Definition

Stack is LIFO. Operations: push, pop, peek.

Why It Matters

Stacks model nested scopes, recursion frames, undo history, expression parsing, and nearest-greater type problems.

How It Works
  • Array stack: contiguous storage + top index.
  • Linked stack: node chain with head as top.
  • Simulation pattern: process stream and keep only required unresolved state on stack.
Internal Mechanics

Array stack benefits from cache locality and fewer allocations. Linked stack avoids resizing cost but allocates per push.

Java Implementation Notes
  • For production Java, prefer ArrayDeque over Stack.
  • Avoid legacy java.util.Stack unless required by environment constraints.
Clean Code Rules If Applicable
  • Encapsulate stack operations in a class when behavior is domain-specific.
  • Prefer descriptive names (operandStack, indexStack) over generic st in production.
Mini Example

Balanced parentheses uses stack of opening brackets.

Common Mistakes
  • Popping from empty stack without guard.
  • Forgetting final stack-empty validation.
Debugging Tips

Log token and stack snapshot each step for parser/simulation bugs.

Practical Note

For nearest greater/smaller, stack usually stores indexes, not values, to compute spans/distances.

Deeper Note

Stack simulation is often a compressed state machine.

  • recursion stack
  • monotonic stack
  • expression evaluation

Concept Cluster: Queue Models and Circular Buffer Discipline

Topics in this cluster:

  • 7.4 Queue and circular queue; Queue Simulation Pattern
Definition

Queue is FIFO. Operations: offer, poll, peek.

Why It Matters

Queues model arrival order: task scheduling, BFS, rate-limiter pipelines.

How It Works
  • Linked queue: head remove, tail add.
  • Circular queue: fixed array with wraparound indexes.
  • Simulation pattern: events processed in insertion order.
Internal Mechanics

Circular queue uses modulo arithmetic. Distinguish empty and full using either:

  • separate size counter, or
  • one reserved slot strategy.
Java Implementation Notes
  • ArrayDeque is usually best general queue.
  • For fixed-capacity high-throughput pipelines, custom circular array is predictable.
Clean Code Rules If Applicable
  • Isolate index math in helpers (inc(index)), reducing off-by-one errors.
Mini Example

Round-robin packet processing queue.

Common Mistakes
  • Overwriting data when full state is not correctly checked.
  • Mixing inclusive/exclusive boundaries for head and tail.
Debugging Tips

Print (head, tail, size) after every operation.

Practical Note

Mention amortized growth behavior of dynamic arrays versus strict O(1) for fixed circular buffers.

Deeper Note

Backpressure systems often combine queue + capacity policy + drop/retry strategy.

  • BFS frontier
  • producer-consumer
  • bounded buffers

Concept Cluster: Deque and Structure Conversions

Topics in this cluster:

  • 7.5 Deque operations and use cases; Queue using stacks; Stack using queues
Definition

Deque supports insertion/removal at both front and back.

Why It Matters

It unifies stack and queue behaviors and powers sliding-window maxima and many simulations.

How It Works
  • addFirst/addLast/removeFirst/removeLast.
  • Queue using two stacks: inbound + outbound transfer.
  • Stack using queues: rotate elements after push or costly pop approach.
Internal Mechanics

Queue using stacks provides amortized O(1) because each element transfers at most once from input stack to output stack.

Java Implementation Notes
  • Use ArrayDeque<Integer> for deque-heavy algorithms.
  • For queue-using-stacks, keep methods small and explicit.
Clean Code Rules If Applicable
  • Name conversion components by role (inStack, outStack).
  • Keep transfer logic private and reusable.
Mini Example

Implement queue with two stacks for interview API class.

Common Mistakes
  • Transferring on every operation instead of only when needed.
  • Breaking order during stack-via-queue rotation.
Debugging Tips

Test alternating operation sequences, not just batched pushes/pops.

Practical Note

Say both worst-case and amortized complexities.

Deeper Note

This is a concrete example of representation independence: same abstract API, different internal structures.

  • amortized analysis
  • adapter-like design

Concept Cluster: Monotonic Structures and Invariants

Topics in this cluster:

  • 7.6 Monotonic Stack Pattern; Monotonic Queue Pattern; Push-pop invariants and state cleanup rules
Definition
  • Monotonic stack keeps elements/indexes in increasing or decreasing order.
  • Monotonic queue does similar maintenance across moving windows.
Why It Matters

Converts many O(n^2) nearest-greater/window-extreme problems into O(n).

How It Works
  • While incoming value violates monotonic order, pop from end.
  • Push current index/value.
  • Remove stale indexes outside allowed range.
Internal Mechanics

Each index is pushed once and popped once at most, so total operations are linear.

Java Implementation Notes

Store indexes to support staleness checks and value lookup.

Clean Code Rules If Applicable
  • Keep invariant in method-level comment.
  • Split cleanup into two phases: order cleanup, then staleness cleanup.
Mini Example

Sliding window maximum in O(n) with decreasing deque.

Common Mistakes
  • Forgetting stale index removal.
  • Using values instead of indexes and losing position context.
  • Cleaning in wrong order causing stale or incorrect maxima.
Debugging Tips

Track deque as (index:value) after each step.

Practical Note

Say the invariant aloud before coding; it prevents 80% of bugs.

Deeper Note

Monotonic structures are local convex hull-like filters over stream prefixes.

  • amortized O(1)
  • deque discipline
  • linear-time optimization

Concept Cluster: Parentheses, Expressions, and Robust Simulation

Topics in this cluster:

  • 7.7 Parentheses, expression, and simulation problems; Simulation mistakes that create stale state bugs
Definition

Simulation problems mimic rule-driven systems step by step with explicit state.

Why It Matters

Many interview tasks appear different but are stack/queue/deque simulations in disguise.

How It Works
  • Parentheses: stack + matching map.
  • Expression evaluation: operator precedence + operand stack(s).
  • Simulation: deterministic updates per event.
Internal Mechanics

Correctness comes from maintaining a complete state model and applying transitions in the proper order.

Java Implementation Notes
  • Tokenize clearly.
  • Separate parse and evaluate stages where possible.
  • Use enums or clear constants for operators in larger evaluators.
Clean Code Rules If Applicable
  • Do not mix parsing with side effects everywhere.
  • Keep invalid-input handling explicit.
Mini Example

Evaluate postfix using operand stack.

Common Mistakes
  • Forgetting to consume all pending operators.
  • Not handling spaces/multi-digit numbers.
  • Stale state from reused buffers between test cases.
Debugging Tips

Log token, action, and stack states after each token.

Practical Note

Mention how you validate malformed input and why.

Deeper Note

Simulation correctness is often equivalent to a finite-state machine with carefully defined transitions.

  • parser design
  • state machines
  • defensive programming

Worked Examples

Worked Example 1: Reverse a Singly Linked List

Problem or Design Scenario

Given the head of a singly linked list, reverse it in-place and return new head.

Technical Value

This is a standard pointer-manipulation problem and a base for many advanced list transformations.

Constraints or Assumptions
  • Number of nodes: 0 .. 10^5
  • Node values fit in int
  • Must be iterative and O(1) extra space
Example Input/Output or Usage Scenario

Input: 1 -> 2 -> 3 -> 4 -> null
Output: 4 -> 3 -> 2 -> 1 -> null

Brute Force or Naive Approach

Copy values to array/list, then rebuild reversed list.

  • Time: O(n)
  • Extra space: O(n)
Better or Optimized Approach

Iteratively reverse links with three pointers (prev, curr, next).

Why the Better Approach Works

At each step, one node is moved from unreversed suffix to reversed prefix while preserving remaining list via next temporary reference.

Decision Process
  • Start with safety: never lose next.
  • Keep loop invariant explicit.
  • Prefer iterative over recursive for large inputs to avoid stack overflow.
Java Solution
java
import java.util.*;

public class ReverseLinkedListExample {
    static class Node {
        int val;
        Node next;

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

    public static Node reverse(Node head) {
        Node prev = null;
        Node curr = head;

        while (curr != null) {
            Node next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public static Node build(int... values) {
        Node dummy = new Node(0);
        Node tail = dummy;
        for (int v : values) {
            tail.next = new Node(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    public static String toString(Node head) {
        StringBuilder sb = new StringBuilder();
        Node cur = head;
        while (cur != null) {
            sb.append(cur.val).append(" -> ");
            cur = cur.next;
        }
        sb.append("null");
        return sb.toString();
    }

    public static void main(String[] args) {
        Node head = build(1, 2, 3, 4);
        Node reversed = reverse(head);
        System.out.println(toString(reversed));
    }
}
Dry Run

For 1 -> 2 -> 3:

  1. prev=null, curr=1, next=2, set 1.next=null, move prev=1, curr=2
  2. next=3, set 2.next=1, move prev=2, curr=3
  3. next=null, set 3.next=2, move prev=3, curr=null
  4. return prev=3
Time and Space Complexity
  • Time: O(n)
  • Space: O(1)
Edge Cases
  • Empty list
  • Single node
  • Very long list
Common Mistakes
  • Forgetting next = curr.next before rewiring.
  • Returning head instead of prev.
  • Reverse sublist between positions m and n
  • Reverse in groups of k
Validation

Test [], [7], [1,2], repeated values, and long random lists.


Worked Example 2: Daily Temperatures with Monotonic Stack

Problem or Design Scenario

Given temperatures array, for each day find how many days until a warmer temperature; otherwise 0.

Technical Value

Classic monotonic stack pattern. Teaches nearest-greater-on-right logic with index stack.

Constraints or Assumptions
  • 1 <= n <= 10^5
  • temperature range small but algorithm should work generally
Example Input/Output or Usage Scenario

Input: [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]

Brute Force or Naive Approach

For each index, scan right until warmer day found.

  • Time: O(n^2)
  • Space: O(1)
Better or Optimized Approach

Use decreasing monotonic stack of indexes.

Why the Better Approach Works

When current temperature is higher than stack top's temperature, current day is the answer for that top index. Each index is pushed once and popped once.

Decision Process
  • Store indexes, not values.
  • Use while-pop to resolve all now-satisfied previous days.
  • Keep answer default 0 to reduce branching.
Java Solution
java
import java.util.*;

public class DailyTemperaturesExample {
    public static int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] ans = new int[n];
        Deque<Integer> stack = new ArrayDeque<>(); // decreasing by temperature

        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                int prev = stack.pop();
                ans[prev] = i - prev;
            }
            stack.push(i);
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] input = {73, 74, 75, 71, 69, 72, 76, 73};
        System.out.println(Arrays.toString(dailyTemperatures(input)));
    }
}
Dry Run

At i=2 (75), stack has [1(74)], 75 > 74, pop 1, set ans[1]=1; then compare with 0(73), pop, set ans[0]=2; push 2.

Time and Space Complexity
  • Time: O(n)
  • Space: O(n)
Edge Cases
  • Strictly decreasing temperatures -> all 0.
  • Single element.
Common Mistakes
  • Using >= instead of > if problem requires strictly warmer.
  • Pushing values instead of indexes.
  • Next greater element in circular array.
  • Stock span.
Validation

Use monotonic increasing, decreasing, equal values, and random arrays.


Worked Example 3: Sliding Window Maximum with Monotonic Queue

Problem or Design Scenario

Given array nums and window size k, return max for each window.

Technical Value

This is a standard monotonic-queue problem and combines deque monotonicity with stale-state cleanup.

Constraints or Assumptions
  • 1 <= k <= n <= 10^5
Example Input/Output or Usage Scenario

Input: nums=[1,3,-1,-3,5,3,6,7], k=3
Output: [3,3,5,5,6,7]

Brute Force or Naive Approach

For each window, scan k elements for max.

  • Time: O(nk)
Better or Optimized Approach

Maintain deque of indexes with decreasing values.

Why the Better Approach Works

Front always holds max index for current window. Back is cleaned so values remain decreasing. Stale indexes (<= i-k) are removed from front.

Decision Process
  • Write operations in fixed order:
    1. drop stale front
    2. drop smaller back
    3. push current index
    4. record answer when first full window forms
Java Solution
java
import java.util.*;

public class SlidingWindowMaximumExample {
    public static int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        if (k == 1) {
            return Arrays.copyOf(nums, n);
        }

        int[] ans = new int[n - k + 1];
        Deque<Integer> dq = new ArrayDeque<>(); // indexes, values decreasing

        for (int i = 0; i < n; i++) {
            while (!dq.isEmpty() && dq.peekFirst() <= i - k) {
                dq.pollFirst();
            }

            while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) {
                dq.pollLast();
            }

            dq.offerLast(i);

            if (i >= k - 1) {
                ans[i - k + 1] = nums[dq.peekFirst()];
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));
    }
}
Dry Run

At i=4 (5) with k=3:

  • Remove stale index 1 for window [2..4].
  • Remove back indexes with smaller values -3 and -1.
  • Push 4.
  • Front points to value 5.
Time and Space Complexity
  • Time: O(n)
  • Space: O(k) worst-case O(n)
Edge Cases
  • k=1
  • k=n
  • duplicate maxima
Common Mistakes
  • Forgetting stale index removal.
  • Recording answer before window is full.
  • Sliding window minimum.
  • Dynamic window extremes in stream processing.
Validation

Validate with duplicate values and alternating high-low patterns.

Solved Problems

Problem 1: Valid Parentheses (Easy)

Problem Statement

Given string containing ()[]{}, return true if brackets are valid.

Constraints or Assumptions
  • Input length up to 10^5
  • Contains only bracket characters
Example

"([{}])" -> true, "([)]" -> false

Brute Force or Naive Solution

Repeatedly remove (), {}, [] until no change. If empty, valid.

  • Can degrade to O(n^2).
Optimized or Refactored Solution

Stack of opening brackets + map for matching closing brackets.

Why the Final Approach Works

Every closing bracket must match the latest unmatched opening bracket.

Decision Process
  • Fast fail on odd length.
  • Use switch for speed/clarity.
Java Solution
java
import java.util.*;

public class ValidParenthesesLab {
    public static boolean isValid(String s) {
        if ((s.length() & 1) == 1) {
            return false;
        }
        Deque<Character> st = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            switch (c) {
                case '(':
                case '[':
                case '{':
                    st.push(c);
                    break;
                case ')':
                    if (st.isEmpty() || st.pop() != '(') return false;
                    break;
                case ']':
                    if (st.isEmpty() || st.pop() != '[') return false;
                    break;
                case '}':
                    if (st.isEmpty() || st.pop() != '{') return false;
                    break;
                default:
                    return false;
            }
        }
        return st.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isValid("([{}])"));
    }
}
Dry Run

([)]: push (, push [, see ), top is [, mismatch -> false.

Time and Space Complexity
  • Time: O(n)
  • Space: O(n)
Edge Cases
  • Empty string (valid)
  • Single char (invalid)
  • Include wildcard *
  • Return index of first mismatch

Problem 2: Implement Queue using Two Stacks (Easy)

Problem Statement

Implement FIFO queue API using only stack operations.

Constraints or Assumptions
  • Many operations
  • Need amortized efficiency
Example

push 1,2,3; pop -> 1; peek -> 2

Brute Force or Naive Solution

On each push, move all elements to temp stack and back to maintain order.

  • O(n) per push.
Optimized or Refactored Solution

Use in and out stacks. Transfer only when out is empty.

Why the Final Approach Works

Each element moves at most once from in to out before removal.

Decision Process

Optimize common path: avoid repeated transfers.

Java Solution
java
import java.util.*;

public class QueueUsingStacksLab {
    static class MyQueue {
        private final Deque<Integer> in = new ArrayDeque<>();
        private final Deque<Integer> out = new ArrayDeque<>();

        public void push(int x) {
            in.push(x);
        }

        public int pop() {
            moveIfNeeded();
            return out.pop();
        }

        public int peek() {
            moveIfNeeded();
            return out.peek();
        }

        public boolean empty() {
            return in.isEmpty() && out.isEmpty();
        }

        private void moveIfNeeded() {
            if (out.isEmpty()) {
                while (!in.isEmpty()) {
                    out.push(in.pop());
                }
            }
        }
    }

    public static void main(String[] args) {
        MyQueue q = new MyQueue();
        q.push(1);
        q.push(2);
        q.push(3);
        System.out.println(q.pop());
        System.out.println(q.peek());
    }
}
Dry Run

After pushing 1,2,3: in=[3,2,1], out=[]. First pop transfers to out=[1,2,3], pop gives 1.

Time and Space Complexity
  • Amortized push/pop/peek: O(1)
  • Worst-case single pop: O(n)
  • Space: O(n)
Edge Cases
  • Pop/peek when empty (would throw; define behavior per API)
  • Queue with generic type
  • Bounded capacity queue

Problem 3: Merge Two Sorted Linked Lists (Medium)

Problem Statement

Merge two sorted singly linked lists and return sorted merged list.

Constraints or Assumptions
  • Total nodes up to 2 * 10^5
Example

1->3->5 and 1->2->4 => 1->1->2->3->4->5

Brute Force or Naive Solution

Copy values to array, sort, rebuild list.

  • O((m+n) log(m+n))
Optimized or Refactored Solution

Two-pointer merge with dummy node.

Why the Final Approach Works

At each step, smallest current node among two list heads must be next in final order.

Decision Process
  • Use dummy head to avoid special handling for first insertion.
  • Reuse existing nodes to avoid extra allocations.
Java Solution
java
public class MergeSortedListsLab {
    static class Node {
        int val;
        Node next;
        Node(int val) { this.val = val; }
    }

    public static Node merge(Node a, Node b) {
        Node dummy = new Node(0);
        Node tail = dummy;

        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }

        tail.next = (a != null) ? a : b;
        return dummy.next;
    }

    public static void main(String[] args) {
        Node a = new Node(1); a.next = new Node(3); a.next.next = new Node(5);
        Node b = new Node(1); b.next = new Node(2); b.next.next = new Node(4);
        Node m = merge(a, b);
        while (m != null) {
            System.out.print(m.val + (m.next == null ? "\n" : " -> "));
            m = m.next;
        }
    }
}
Dry Run

Compare heads repeatedly: pick 1(a), then 1(b), then 2,3,4,5.

Time and Space Complexity
  • Time: O(m+n)
  • Extra space: O(1)
Edge Cases
  • One list empty
  • All equal values
  • Merge k sorted lists (heap/divide-conquer)

Problem 4: Design Circular Queue (Medium)

Problem Statement

Implement fixed-size circular queue with operations enqueue, dequeue, front, rear, isEmpty, isFull.

Constraints or Assumptions
  • Capacity k >= 1
  • O(1) per operation
Example

k=3: enq 1,2,3 -> full; deq; enq 4 -> wraps around.

Brute Force or Naive Solution

Use array and shift on dequeue.

  • O(n) dequeue.
Optimized or Refactored Solution

Circular array + head index + size.

Why the Final Approach Works

Wraparound position for insertion is (head + size) % capacity; deletion advances head by one modulo capacity.

Decision Process

Track size explicitly to simplify empty/full checks.

Java Solution
java
public class CircularQueueLab {
    static class MyCircularQueue {
        private final int[] data;
        private int head;
        private int size;

        MyCircularQueue(int k) {
            this.data = new int[k];
            this.head = 0;
            this.size = 0;
        }

        public boolean enQueue(int value) {
            if (isFull()) return false;
            int tailIndex = (head + size) % data.length;
            data[tailIndex] = value;
            size++;
            return true;
        }

        public boolean deQueue() {
            if (isEmpty()) return false;
            head = (head + 1) % data.length;
            size--;
            return true;
        }

        public int Front() {
            if (isEmpty()) return -1;
            return data[head];
        }

        public int Rear() {
            if (isEmpty()) return -1;
            int idx = (head + size - 1 + data.length) % data.length;
            return data[idx];
        }

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

        public boolean isFull() {
            return size == data.length;
        }
    }

    public static void main(String[] args) {
        MyCircularQueue q = new MyCircularQueue(3);
        System.out.println(q.enQueue(1));
        System.out.println(q.enQueue(2));
        System.out.println(q.enQueue(3));
        System.out.println(q.enQueue(4));
        System.out.println(q.Rear());
        System.out.println(q.isFull());
        System.out.println(q.deQueue());
        System.out.println(q.enQueue(4));
        System.out.println(q.Rear());
    }
}
Dry Run

After enq 1,2,3: head=0,size=3. deq -> head=1,size=2. enq 4 inserts at (1+2)%3=0.

Time and Space Complexity
  • All operations O(1)
  • Space O(k)
Edge Cases
  • Capacity 1
  • Repeated dequeue on empty
  • Circular deque
  • generic queue

Problem 5: Largest Rectangle in Histogram (Hard)

Problem Statement

Given bar heights, return largest rectangle area.

Constraints or Assumptions
  • 1 <= n <= 10^5
  • heights non-negative
Example

[2,1,5,6,2,3] -> 10

Brute Force or Naive Solution

For each bar, expand left/right while bars >= current height.

  • O(n^2)
Optimized or Refactored Solution

Monotonic increasing stack of indexes.

Why the Final Approach Works

When current height is lower than stack top, top bar's maximal width ends at current index minus one. Left boundary is new stack top + 1.

Decision Process

Append virtual zero-height bar to flush remaining stack cleanly.

Java Solution
java
import java.util.*;

public class LargestRectangleHistogramLab {
    public static int largestRectangleArea(int[] heights) {
        int n = heights.length;
        Deque<Integer> st = new ArrayDeque<>();
        int best = 0;

        for (int i = 0; i <= n; i++) {
            int h = (i == n) ? 0 : heights[i];
            while (!st.isEmpty() && h < heights[st.peek()]) {
                int top = st.pop();
                int height = heights[top];
                int left = st.isEmpty() ? -1 : st.peek();
                int width = i - left - 1;
                best = Math.max(best, height * width);
            }
            st.push(i);
        }

        return best;
    }

    public static void main(String[] args) {
        int[] heights = {2, 1, 5, 6, 2, 3};
        System.out.println(largestRectangleArea(heights));
    }
}
Dry Run

At i=4, h=2, pop 6 then 5 bars:

  • pop index 3 (height 6), width 1, area 6
  • pop index 2 (height 5), width 2, area 10 (best)
Time and Space Complexity
  • Time: O(n)
  • Space: O(n)
Edge Cases
  • all equal heights
  • strictly increasing heights
  • zero heights present
  • maximal rectangle in binary matrix
  • online histogram updates

Recognition Guide

Use this chapter's techniques when you see:

  • "nearest greater/smaller", "next warmer day", "span" -> monotonic stack
  • "window max/min" with contiguous range -> monotonic queue
  • "reverse/merge/reorder list" -> pointer manipulation
  • "first-in-first-out events" -> queue
  • "nested/undo/backtrack" -> stack
  • "both ends needed" -> deque
  • "cyclic traversal" -> circular list or circular queue

Recognition signals:

  • need O(n) from O(n^2) comparisons
  • repeated front/back operations
  • order constraints stronger than random access

Constraint clues:

  • large n (10^5 or more) often implies linear or near-linear approach
  • fixed capacity suggests circular buffer

Invariants/design forces to watch:

  • stack monotonicity condition
  • queue staleness rule
  • list connectivity (no orphan nodes)

Common traps:

  • stale indexes not removed
  • pushing values when indexes are required
  • pointer rewiring order mistakes

When NOT to use these techniques:

  • heavy random-index queries -> arrays/segment trees may fit better
  • tiny input where clarity of brute force is enough

Comparison Tables

Structure/Pattern Typical Ops Time Space Strength Trade-off
Singly Linked List insert/delete at head O(1) O(n) simple rewiring no backward traversal
Doubly Linked List insert/delete known node O(1) O(n) + extra pointers bidirectional navigation more memory
Array Stack push/pop top amortized O(1) O(n) cache-friendly resize events
Linked Stack push/pop top O(1) O(n) no resize copy allocation overhead
Queue (ArrayDeque) offer/poll O(1) amortized O(n) practical default in Java no random access
Circular Queue offer/poll fixed capacity O(1) O(k) predictable latency fixed size
Deque both-end operations O(1) O(n) very flexible logic can get complex
Monotonic Stack nearest greater/smaller O(n) O(n) removes nested loops invariant sensitive
Monotonic Queue sliding max/min O(n) O(k) optimal window extremes stale cleanup bugs
Conversion Push Pop Peek Key idea
Queue using 2 stacks O(1) amortized O(1) amortized O(1) lazy transfer
Stack using queues (costly push) O(n) O(1) O(1) rotate queue after push
Stack using queues (costly pop) O(1) O(n) O(n) rotate during pop

Design and Decision Making

Relevant design patterns:

  • Adapter-like idea in queue-using-stacks (same API, different internals)
  • Strategy-like selection between array-backed vs linked-backed representation

Clean code rules that matter:

  • Separate data-structure API from algorithm logic.
  • Keep invariants explicit near mutating code.
  • Prefer descriptive method names: removeStaleIndexes, cleanMonotonicTail.

Clean code structure:

  • datastructures package for custom classes.
  • algorithms package for monotonic/linked-list problems.
  • tests package mirroring class names.

Reusable architecture ideas:

  • Build a reusable MonotonicDeque helper for max/min variants.
  • Build LinkedListUtils with pure static methods for reverse/merge/cycle.

Pragmatic choice of solution shape:

  • Default to JDK collections (ArrayDeque) unless fixed-capacity or memory profile requires custom structure.
  • Choose simple O(n) code over clever constant-factor micro-optimizations unless benchmark proves need.

How experienced engineers choose abstraction level:

  • One-off interview solution: compact function is fine.
  • Reused in service code: encapsulate invariant-heavy logic behind tested APIs.

Naming conventions:

  • pointer names: prev/curr/next, slow/fast
  • monotonic deque names: dq, but include comment // decreasing indexes

API design choices:

  • Decide behavior on empty pop/peek: exception vs sentinel vs optional.
  • Keep behavior consistent across related structures.

Testability considerations:

  • deterministic unit tests for operation sequences
  • property checks for invariants (stack order, queue order, list shape)
  • fuzz tests for random push/pop/offer/poll sequences

Practical Applications

  • Backend systems: job queues, retry buffers, request batching.
  • Frontend apps: undo stack, navigation history stack.
  • Databases: LRU-like page replacement often uses deque/list structures.
  • Distributed systems: message queue consumers and bounded channels.
  • Operating systems: scheduler run queues and circular buffers.
  • Networking: packet ring buffers, sliding metrics windows.
  • AI systems: beam-search candidates often managed with queues/heaps; token parsers use stacks.
  • Mobile apps: recent-actions stack and event queues.
  • Games: event simulation loops and turn queues.

Failure Modes and Trade-offs

Senior engineer insights:

  • Big-O is not enough. Memory layout and allocation rates matter.
  • ArrayDeque beats linked structures in many practical Java workloads due to locality.

Hidden tricks:

  • For monotonic stack/queue, store indexes; values can be read from source array.
  • Add sentinel elements to simplify edge handling.

Performance tuning:

  • avoid boxing/unboxing hot loops where possible
  • pre-size arrays when capacity known

Trade-off thinking:

  • fixed-capacity circular queue gives predictable latency but can drop/reject data when full
  • linked structures avoid resizing but create GC pressure

Interview traps:

  • forgetting stale cleanup in window problems
  • wrong operator strictness (< vs <=)
  • claiming O(1) where only amortized O(1) is true

Common weak spots:

  • pointer order in reverse/merge
  • edge cases empty/single/full

Failure modes and debugging strategy:

  1. Reproduce with minimal failing input.
  2. Log invariant state each step.
  3. Assert structure integrity after mutation in debug builds.
  4. Compare against brute force on random small inputs.

Condensed Notes

  • Stack = LIFO, Queue = FIFO, Deque = both ends.
  • Monotonic stack: push once, pop once -> O(n).
  • Sliding max deque invariant: values decreasing, front always current max.
  • Linked-list reverse template:
    • save next
    • flip curr.next
    • advance prev/curr
  • Floyd cycle detection:
    • meeting implies cycle
    • reset one pointer to head and move both one step to find entry
  • Circular queue formulas:
    • tail index: (head + size) % capacity
    • rear index: (head + size - 1 + capacity) % capacity
  • Decision shortcuts:
    • nearest greater/smaller -> monotonic stack
    • window extrema -> monotonic deque
    • strict FIFO stream -> queue
    • nested matching -> stack
  • Gotchas:
    • stale index cleanup
    • empty structure checks
    • off-by-one in window boundaries

Additional Problems

Easy (5)

  1. Title: Implement Stack with Array
    Prompt: Build push/pop/peek/isEmpty with dynamic resizing.
    Expected pattern or concept: Array-based stack fundamentals.
  2. Title: Valid Parentheses II
    Prompt: Validate mixed brackets and report first mismatch index.
    Expected pattern or concept: Stack simulation pattern.
  3. Title: Queue Basics
    Prompt: Implement queue using linked nodes with O(1) offer/poll.
    Expected pattern or concept: Queue and linked representation.
  4. Title: Reverse Linked List
    Prompt: Reverse singly linked list iteratively.
    Expected pattern or concept: Pointer manipulation and reversal.
  5. Title: Detect Cycle
    Prompt: Return whether linked list contains cycle.
    Expected pattern or concept: Fast and slow pointer technique.

Medium (5)

  1. Title: Next Greater Element
    Prompt: For each element, find next greater on right.
    Expected pattern or concept: Monotonic stack pattern.
  2. Title: Daily Temperatures Variant
    Prompt: Return days until colder temperature instead of warmer.
    Expected pattern or concept: Monotonic stack with operator adjustment.
  3. Title: Sliding Window Maximum
    Prompt: Compute max for each size-k window.
    Expected pattern or concept: Monotonic queue pattern.
  4. Title: Queue Using Two Stacks
    Prompt: Design full queue API with amortized analysis.
    Expected pattern or concept: Deque/stack conversion and amortization.
  5. Title: Merge Two Sorted Lists
    Prompt: Merge without creating new value nodes.
    Expected pattern or concept: Merge and pointer rewiring.

Hard (5)

  1. Title: Largest Rectangle in Histogram
    Prompt: Maximum rectangle area in O(n).
    Expected pattern or concept: Monotonic stack + width boundaries.
  2. Title: Maximal Rectangle in Binary Matrix
    Prompt: Use histogram per row and stack optimization.
    Expected pattern or concept: Stack simulation + row transformation.
  3. Title: Min Queue with O(1) Operations
    Prompt: Support enqueue/dequeue/getMin efficiently.
    Expected pattern or concept: Deque invariants and state cleanup.
  4. Title: Evaluate Infix Expression with Parentheses
    Prompt: Parse multi-digit values and precedence safely.
    Expected pattern or concept: Parentheses/expression simulation.
  5. Title: Circular Deque with Fixed Capacity
    Prompt: Implement all operations in O(1) with wraparound.
    Expected pattern or concept: Circular indexing + deque operations.

Key Questions

  1. Q: When should you prefer ArrayDeque over LinkedList for stack/queue in Java?
    A: In most cases. ArrayDeque has better locality and lower per-element overhead, usually giving better real performance.
  2. Q: Why does monotonic stack give O(n) and not O(n^2)?
    A: Each index is pushed once and popped once at most, so total stack operations are linear.
  3. Q: How do you avoid stale state in sliding-window deque problems?
    A: Remove front indexes outside current window before reading answer.
  4. Q: Explain amortized O(1) for queue using two stacks.
    A: Transfers are occasional and each element moves from input to output at most once before pop.
  5. Q: Difference between singly and doubly linked list trade-offs?
    A: Doubly enables backward traversal and O(1) removal with node reference but uses extra memory.
  6. Q: How do you find cycle start in linked list?
    A: Detect meeting with fast/slow, reset one pointer to head, move both one step until equal.
  7. Q: Common bug in linked-list reversal?
    A: Overwriting curr.next before saving next node.
  8. Q: Queue using stacks or stack using queues: which is more practical?
    A: Queue using stacks is more common and cleaner with amortized O(1) operations.
  9. Q: Why store indexes instead of values in monotonic structures?
    A: Indexes support distance calculations and stale-window checks.
  10. Q: When not to use linked list even if operations are O(1)?
    A: When random access and cache locality matter; arrays may be faster in practice.

Applied Project

Objective

Build a Java "Stream Analyzer" that processes event numbers and supports:

  • enqueue events
  • current max over last k events
  • undo last command
  • validate expression-like control commands

Required Features

  • Circular queue for bounded event intake.
  • Monotonic deque for rolling maximum.
  • Stack for undo history.
  • Parentheses validator for command scripts.

Suggested Java module structure

  • streamanalyzer.core.EventQueue
  • streamanalyzer.core.RollingMax
  • streamanalyzer.core.UndoManager
  • streamanalyzer.parser.CommandValidator
  • streamanalyzer.app.Main

Testing ideas

  • deterministic scenario tests
  • random operation sequence tests
  • invariant assertions after each operation

Stretch goals

  • add rolling minimum too
  • add command replay log
  • expose REST endpoint for enqueue/query

8: Creational Design Patterns

Introduction and Context

Creational patterns solve a fundamental problem: how do you initialize complex objects consistently and flexibly? Naive constructors become unwieldy. Global state breaks testing. Tight coupling to concrete classes stifles extension.

Creational patterns push initialization logic into specialized objects instead of scattering it across your codebase. The result is cleaner APIs, easier testing, safer global state (or its elimination), and the ability to swap implementations without touching client code.

This chapter covers five major patterns: Singleton (controlled global state), Factory Method (delegated creation), Abstract Factory (families of related objects), Builder (step-by-step construction), and Prototype (cloning templates). Each has specific use cases and pitfalls. The most common failure is overuse: applying these patterns when a simple constructor suffices wastes time and confuses readers.

Core Intuition and Mechanics

Think of creational patterns as answering different questions:

  • Singleton: "How do I guarantee exactly one instance?"
  • Factory Method: "How do I let subclasses choose what to create?"
  • Abstract Factory: "How do I create whole families of related objects?"
  • Builder: "How do I construct complex objects step by step?"
  • Prototype: "How do I copy and customize template objects?"

Each pattern takes a different view of the problem. All share the idea that who creates an object and how it is created are separate concerns worth isolating.

Core Concepts and Subtopics

Concept Cluster: Singleton Implementations and Pitfalls

Topics in this cluster:

  • 8.1 Singleton Pattern: Eager singleton, Lazy singleton, Thread-safe singleton, Double-checked locking, Enum singleton
  • 8.2 Singleton pitfalls, global state, and testability concerns, Trade-offs and misuse cases
Definition

A Singleton ensures a class has exactly one instance and provides a global point of access. Common forms are eager initialization (at class load), lazy initialization (on first use), double-checked locking (thread-safe lazy), and enum-based.

Why It Matters

Some objects genuinely should exist only once: loggers, database connections, configuration holders. But Singleton is overused for convenience, creating hidden dependencies and testability nightmares. Know the difference between "exactly one instance is correct" and "I want global access because it is easy."

How It Works

Eager Singleton: instance created when class loads.

java
public class EagerSingleton {
    public static final EagerSingleton INSTANCE = new EagerSingleton();
    private EagerSingleton() {}
}

Lazy Singleton with Double-Checked Locking: instance created on first use, thread-safe without synchronizing every access.

java
public class LazyThreadSafe {
    private static volatile LazyThreadSafe instance;
    
    public static LazyThreadSafe getInstance() {
        if (instance == null) {
            synchronized (LazyThreadSafe.class) {
                if (instance == null) {
                    instance = new LazyThreadSafe();
                }
            }
        }
        return instance;
    }
    private LazyThreadSafe() {}
}

Enum Singleton: Guarantees thread safety and prevents reflection-based instantiation.

java
public enum EnumSingleton {
    INSTANCE;
    
    public void doSomething() { }
}
Pitfalls
  • Hidden dependencies make code harder to trace and test.
  • Reflection can bypass private constructors (not enum).
  • Serialization can create multiple instances if not handled.
  • Global state makes unit tests interdependent.
Clean Code Rules

Prefer dependency injection or enum over Singleton unless the problem truly requires one global instance. If forced to use Singleton, provide a way for tests to reset it.

Common Mistakes
  • Forgetting volatile in double-checked locking (reads may be stale).
  • Assuming all platforms initialize classes the same way.
  • Not serializing correctly, creating duplicate instances after deserialization.

Concept Cluster: Factory Method, Abstract Factory, and Comparison

Topics in this cluster:

  • 8.3 Factory Method Pattern: Product interface, Concrete products, Creator class, Factory method override, Real-world usage, Factory method versus a simple factory helper
  • 8.4 Abstract Factory Pattern: Factory families, Related objects creation, Swappable families, UI toolkit example, Cross-platform factories, Abstract factory versus factory method
Definition

Factory Method defines an interface for creating objects, letting subclasses decide the concrete class. Abstract Factory provides an interface for creating families of related objects without specifying concrete classes.

Why It Matters

Decoupling client code from concrete classes lets you add new products or families without touching client code. This is powerful for multi-platform support, plugin systems, and testing (easy to swap mocks).

How Factory Method Works
java
abstract class DocumentCreator {
    abstract Document createDocument();
    
    void openDocument() {
        Document doc = createDocument();
        doc.open();
    }
}

class PDFCreator extends DocumentCreator {
    @Override
    Document createDocument() { return new PDFDocument(); }
}
How Abstract Factory Works
java
interface UIFactory {
    Button createButton();
    Window createWindow();
}

class WindowsUIFactory implements UIFactory {
    public Button createButton() { return new WindowsButton(); }
    public Window createWindow() { return new WindowsWindow(); }
}

class Application {
    UIFactory factory;
    Application(UIFactory factory) { this.factory = factory; }
    void render() {
        Button btn = factory.createButton();
        Window win = factory.createWindow();
    }
}
Factory Method vs Abstract Factory

Use Factory Method when you have one product hierarchy and subclasses choose the variant. Use Abstract Factory when you have multiple product families and need to ensure consistency across families (all Windows, or all Mac, never mixed).

Common Mistakes
  • Creating a Factory Method when a helper method or switch statement is simpler.
  • Forgetting that Abstract Factory often uses Factory Method internally.
  • Not isolating the factory enough; letting creation logic leak into clients.

Concept Cluster: Builder and Prototype Patterns

Topics in this cluster:

  • 8.5 Builder Pattern: Step builder, Fluent builder, Immutable object builder, Director role, Complex object construction, Validation, defaults, and constructor overload alternatives
  • 8.6 Prototype Pattern: Shallow copy, Deep copy, Clone registry, Object templates, Copy safety and mutability traps, Prototype versus builder for object creation
Definition

Builder constructs a complex object step by step, collecting parts and then assembling them. Prototype creates new objects by copying an existing template.

Why It Matters

Builders replace telescoping constructors with readable, extensible fluent chains. Prototypes enable efficient object copying and let you clone with variations without knowing the class.

Builder Pattern in Java
java
public class DatabaseConnection {
    private final String host;
    private final int port;
    private final String database;
    private final int maxRetries;
    
    private DatabaseConnection(Builder builder) {
        this.host = builder.host;
        this.port = builder.port;
        this.database = builder.database;
        this.maxRetries = builder.maxRetries;
    }
    
    public static class Builder {
        private final String host;
        private final int port;
        private String database = "default";
        private int maxRetries = 3;
        
        public Builder(String host, int port) {
            this.host = host;
            this.port = port;
        }
        
        public Builder database(String db) {
            this.database = db;
            return this;
        }
        
        public Builder maxRetries(int retries) {
            this.maxRetries = retries;
            return this;
        }
        
        public DatabaseConnection build() {
            return new DatabaseConnection(this);
        }
    }
}

// Usage
DatabaseConnection conn = new DatabaseConnection.Builder("localhost", 5432)
    .database("mydb")
    .maxRetries(5)
    .build();
Prototype Pattern in Java
java
public class ConfigClone implements Cloneable {
    private String name;
    private List<String> tags;
    
    @Override
    public ConfigClone clone() throws CloneNotSupportedException {
        ConfigClone cloned = (ConfigClone) super.clone();
        cloned.tags = new ArrayList<>(this.tags); // deep copy mutable fields
        return cloned;
    }
}
Builder vs Prototype

Use Builder for step-by-step construction with validation. Use Prototype when you have a template and want to quickly make variations. Builder is about assembling; Prototype is about copying.

Common Mistakes
  • Forgetting to deep copy mutable fields in Prototype.
  • Making Builder too complex with too many optional parameters (use inheritance if there are many variants).
  • Not validating in build() when preconditions matter.

Worked Examples

Worked Example 1: Enum Singleton with Global Configuration

Problem: Build a thread-safe configuration holder that loads once and supplies values globally.

Solution: Use enum Singleton to hold configuration with thread safety and serialization safety guarantees.

java
public enum AppConfig {
    INSTANCE;
    
    private final Properties props;
    
    AppConfig() {
        props = new Properties();
        try {
            props.load(AppConfig.class.getResourceAsStream("/app.properties"));
        } catch (Exception e) {
            throw new RuntimeException("Failed to load config", e);
        }
    }
    
    public String get(String key, String defaultValue) {
        return props.getProperty(key, defaultValue);
    }
}

// Client
String timeout = AppConfig.INSTANCE.get("timeout", "30");

Worked Example 2: Abstract Factory for Cross-Platform UI

Problem: Support both Windows and macOS UI without client code checking platform.

Solution: Use Abstract Factory to swap UI families.

java
interface Button { void render(); }
class WindowsButton implements Button {
    public void render() { System.out.println("Windows button"); }
}

interface UIFactory {
    Button createButton();
}

class WindowsUIFactory implements UIFactory {
    public Button createButton() { return new WindowsButton(); }
}

public class Application {
    private UIFactory factory;
    
    public Application(UIFactory factory) {
        this.factory = factory;
    }
    
    public void start() {
        Button btn = factory.createButton();
        btn.render();
    }
}

Worked Example 3: Builder for Complex Immutable Objects

Problem: Create a User with many optional fields and validate before instantiation.

Solution: Use Builder with fluent API and validation.

java
public class User {
    private final String email;
    private final String name;
    private final int age;
    private final List<String> roles;
    
    private User(Builder builder) {
        this.email = builder.email;
        this.name = builder.name;
        this.age = builder.age;
        this.roles = Collections.unmodifiableList(builder.roles);
    }
    
    public static class Builder {
        private final String email;
        private String name = "";
        private int age = 0;
        private final List<String> roles = new ArrayList<>();
        
        public Builder(String email) {
            this.email = email;
        }
        
        public Builder name(String name) {
            this.name = name;
            return this;
        }
        
        public Builder addRole(String role) {
            roles.add(role);
            return this;
        }
        
        public User build() {
            if (email == null || email.isEmpty()) {
                throw new IllegalArgumentException("Email is required");
            }
            return new User(this);
        }
    }
}

// Usage
User user = new User.Builder("user@example.com")
    .name("Alice")
    .addRole("admin")
    .build();

Solved Problems

Problem 1 (Easy): Implement thread-safe Lazy Singleton using double-checked locking.

Problem 2 (Easy): Create a simple Document Factory Method that returns PDFDocument or WordDocument based on a string.

Problem 3 (Medium): Build an Abstract Factory for database drivers supporting MySQL and PostgreSQL.

Problem 4 (Medium): Implement Builder for a SQL query object (SELECT, WHERE, ORDER BY, LIMIT).

Problem 5 (Hard): Implement Prototype with deep copy for a graph node structure with circular references.


Recognition Guide

Use Creational patterns when:

  • You need to control how objects are instantiated.
  • Multiple related object families exist and must be kept consistent.
  • Complex initialization needs to be hidden from clients.
  • You want to make unit tests easier by swapping implementations.

Avoid when:

  • A simple constructor and getter/setter suffice.
  • The code introduces too many classes for a tiny problem.

Comparison Tables

Pattern Main Question Strength Common Misuse
Singleton One shared instance? Centralized coordination Hiding dependencies as global state
Factory Method Which subtype should be created? Subclass-controlled creation Replacing a simple helper with too much indirection
Abstract Factory Which product family should be used? Consistent related objects Overengineering when only one product varies
Builder How do I assemble a complex object safely? Readable construction and validation Using it for tiny two-field objects
Prototype How do I clone a template quickly? Fast variation from existing objects Shallow-copy bugs on mutable state

Design and Decision Making

Choose Singleton only when exactly one instance is necessary and global access is the simplest design. For most cases, dependency injection is clearer.

Choose Factory Method when subclasses naturally override creation logic. Choose Abstract Factory for multiple product families that must be swapped as units.

Use Builder when constructors become unreadable (3+ optional parameters). Use Prototype when copy operations dominate and you want to avoid class dependencies.


Practical Applications

  • Application configuration loaders and metrics registries often use Singleton-like ownership, but production code usually wraps them behind interfaces for testability.
  • Cross-platform UI toolkits, cloud provider SDKs, and persistence adapters rely on factory-style creation to keep clients decoupled from concrete drivers.
  • Immutable request objects, HTTP clients, and domain aggregates benefit from Builder when required and optional fields must be combined safely.
  • Game engines, document editors, and simulation tools use Prototype when many objects start from a shared template and then diverge.

Failure Modes and Trade-offs

Singleton creates hidden coupling and makes testing harder. Thread-safe variants add complexity. Factories introduce indirection that can confuse readers. Builders require extra classes. Prototype requires correct deep copy implementation.


Condensed Notes

  • Enum Singleton: simplest, thread-safe, serialization-safe.
  • Factory Method: delegated creation; subclasses decide product type.
  • Abstract Factory: families of objects; ensure consistency across variants.
  • Builder: step-by-step construction; fluent API; immutability.
  • Prototype: copy templates; deep copy mutable fields.

Additional Problems

(5 Easy, 5 Medium, 5 Hard) — Write simple Singleton, Factory, Builder, and Prototype implementations for various domains (logging, configuration, database connection, HTTP client, email service).


Key Questions

  1. When is Singleton better than dependency injection?
  2. What is double-checked locking and why is volatile needed?
  3. How do Factory Method and Abstract Factory differ?
  4. Why use Builder instead of constructor overloading?
  5. What is the difference between shallow and deep copy?
  6. How do you prevent Singleton reflection attacks?
  7. When should you use Prototype over Builder?
  8. How do you test code using Singleton?
  9. What is the Factory Method's role in subclassing?
  10. How do Decorators differ from Builders in extending behavior?

Applied Project

Build a Game Object Factory system: define a GameObject interface, create factories for different enemy types (Goblin, Orc, Dragon), use Builder for complex spell objects with damage, duration, and effect stacking rules, and allow cloning of character templates.

9: Recursion and Backtracking

Introduction and Context

Recursion is the bridge from sequential loops to thinking in smaller, self-similar subproblems. Backtracking extends that idea: explore a decision tree, test partial solutions, undo choices that fail, and report complete valid solutions.

Many problems do not fit a greedy approach or a direct formula. Instead, you must try possible choices, detect failure early, and back out cleanly. Without backtracking, you resort to brute-force enumeration. With it, you prune the search tree aggressively and solve problems that would otherwise time out.

This chapter teaches the mental models and implementation patterns. The central insight is that backtracking is organized exhaustive search with intelligent pruning. Base cases, invariants, and undo logic matter as much as the recursive structure itself.

Core Intuition and Mechanics

Imagine a maze. You enter a corridor, leave a marker, try all doors ahead. If you hit a dead end, erase your work and back up. If you find the exit, record it. That is backtracking.

The key mental model is a decision tree:

  • Each node represents a partial solution state.
  • Each branch is one next choice.
  • A leaf is either a complete solution or a dead end.
  • Pruning cuts off branches before they waste time.

Backtracking works by:

  1. Choosing a position in the search space.
  2. Making one choice and updating state.
  3. Recursing to extend the solution.
  4. Undoing the choice (undo must be exact).
  5. Trying the next choice.

The undo step is critical. If you forget to undo, state persists across branches and you get wrong results or confusing bugs.

Core Concepts and Subtopics

Concept Cluster: Recursion Foundations and Backtracking Basics

Topics in this cluster:

  • 9.1 Base case and recursive case design, Understanding the call stack, Tail recursion
  • 9.2 Recursion Tree Pattern, Pruning, rollback, and search-tree visualization
  • 9.3 Backtracking basics, Search space and decision trees
Definition

A recursive function solves a problem by calling itself on smaller inputs. A base case stops the recursion. The recursive case moves toward that base case. Backtracking adds explicit choice exploration and rollback.

Why It Matters

Recursion naturally models problems with recursive structure: tree traversal, divide-and-conquer, and exhaustive search. Backtracking organizes the search so you do not explore clearly invalid branches.

How Recursion Works
java
// Base case: n == 0
// Recursive case: solve(n-1) first, then use that result
static int factorial(int n) {
    if (n <= 1) return 1;           // base case
    return n * factorial(n - 1);    // recursive case
}
How Backtracking Works
java
static void permute(int[] arr, int start, List<List<Integer>> results) {
    if (start == arr.length) {
        // Base case: full permutation found
        results.add(toList(arr));
        return;
    }
    
    for (int i = start; i < arr.length; i++) {
        // Choose
        swap(arr, start, i);
        // Explore
        permute(arr, start + 1, results);
        // Undo
        swap(arr, start, i);
    }
}
Clean Code Rules
  • State the base case first. It is the exit rule.
  • State what the recursive case assumes. If the subproblem shrinks, what shrinks?
  • Undo immediately after recursion. Do not delay cleanup.
  • Use descriptive variable names. start, index, choices are clearer than i, j.
Common Mistakes
  • Forgetting the base case or making it wrong.
  • Recursive call does not shrink the problem.
  • State leaks across branches because undo was forgotten or incomplete.
  • Off-by-one in base case boundary.

Concept Cluster: Subsets, Permutations, and Combination Sum

Topics in this cluster:

  • 9.4 Subsets, Permutations, Combination sum
Definition

Subsets: generate all 2^n subsets of an array.
Permutations: generate all n! orderings.
Combination Sum: find all unique combinations of elements that sum to a target.

Why It Matters

These are the canonical backtracking problems. Once you see the pattern, many variations become straightforward.

Subsets
java
static void subsets(int[] nums, int idx, List<Integer> current, List<List<Integer>> results) {
    if (idx == nums.length) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    // Include nums[idx]
    current.add(nums[idx]);
    subsets(nums, idx + 1, current, results);
    current.remove(current.size() - 1);
    
    // Exclude nums[idx]
    subsets(nums, idx + 1, current, results);
}
Permutations
java
static void permutations(int[] nums, List<Integer> current, boolean[] used, List<List<Integer>> results) {
    if (current.size() == nums.length) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    for (int i = 0; i < nums.length; i++) {
        if (!used[i]) {
            used[i] = true;
            current.add(nums[i]);
            permutations(nums, current, used, results);
            current.remove(current.size() - 1);
            used[i] = false;
        }
    }
}
Combination Sum
java
static void combinationSum(int[] candidates, int target, int start, List<Integer> current, List<List<Integer>> results) {
    if (target == 0) {
        results.add(new ArrayList<>(current));
        return;
    }
    if (target < 0) return;
    
    for (int i = start; i < candidates.length; i++) {
        current.add(candidates[i]);
        combinationSum(candidates, target - candidates[i], i, current, results);
        current.remove(current.size() - 1);
    }
}
Common Mistakes
  • Not passing start to avoid duplicate combinations.
  • Forgetting to remove from current after recursion.
  • Handling negative remainders incorrectly in Combination Sum.

Concept Cluster: N-Queens and Sudoku Solver

Topics in this cluster:

  • 9.5 N-Queens, Sudoku solver
Definition

N-Queens: place N queens on an N×N board such that no two queens attack each other.
Sudoku: fill a 9×9 grid with digits 1–9 such that each row, column, and 3×3 box has each digit exactly once.

Why It Matters

These are classic backtracking problems that teach constraint validation and efficient pruning.

N-Queens Sketch
java
static void solveNQueens(int n, int row, List<String> current, Set<Integer> cols, Set<Integer> diag1, Set<Integer> diag2, List<List<String>> results) {
    if (row == n) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    for (int col = 0; col < n; col++) {
        if (!cols.contains(col) && !diag1.contains(row - col) && !diag2.contains(row + col)) {
            cols.add(col);
            diag1.add(row - col);
            diag2.add(row + col);
            
            // Place queen at (row, col)
            current.add(buildRow(col, n));
            solveNQueens(n, row + 1, current, cols, diag1, diag2, results);
            current.remove(current.size() - 1);
            
            cols.remove(col);
            diag1.remove(row - col);
            diag2.remove(row + col);
        }
    }
}
Sudoku Sketch
java
static boolean solveSudoku(char[][] board, int row, int col) {
    if (row == 9) return true;
    
    int nextRow = (col == 8) ? row + 1 : row;
    int nextCol = (col == 8) ? 0 : col + 1;
    
    if (board[row][col] != '.') {
        return solveSudoku(board, nextRow, nextCol);
    }
    
    for (char digit = '1'; digit <= '9'; digit++) {
        if (isValid(board, row, col, digit)) {
            board[row][col] = digit;
            if (solveSudoku(board, nextRow, nextCol)) return true;
            board[row][col] = '.';
        }
    }
    
    return false;
}
Pruning Strategy

Both problems use early constraint checking: only explore branches that satisfy board rules.


Concept Cluster: Memoization and Recursion to Iteration

Topics in this cluster:

  • 9.6 Memoization basics, Converting recursion to iteration
Definition

Memoization caches subproblem results to avoid recomputation. Converting recursion to iteration uses explicit stacks to replace call stacks.

Why It Matters

Memoization prevents exponential blowup in recursive code with overlapping subproblems. Iteration avoids stack overflow on deep recursion.

Memoization Example
java
static int fib(int n, Map<Integer, Integer> memo) {
    if (n <= 1) return n;
    if (memo.containsKey(n)) return memo.get(n);
    
    int result = fib(n - 1, memo) + fib(n - 2, memo);
    memo.put(n, result);
    return result;
}
Iterative Conversion
java
static int fibIterative(int n) {
    if (n <= 1) return n;
    
    int a = 0, b = 1;
    for (int i = 2; i <= n; i++) {
        int temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

Worked Examples

Worked Example 1: Generate All Subsets (Power Set)

Problem: Given array [1, 2, 3], return all subsets.

Solution: Backtrack on include/exclude choice for each element.

java
public static List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> results = new ArrayList<>();
    subsets(nums, 0, new ArrayList<>(), results);
    return results;
}

private static void subsets(int[] nums, int idx, List<Integer> current, List<List<Integer>> results) {
    if (idx == nums.length) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    current.add(nums[idx]);
    subsets(nums, idx + 1, current, results);
    current.remove(current.size() - 1);
    
    subsets(nums, idx + 1, current, results);
}

Worked Example 2: Combination Sum (Unique Combinations)

Problem: Find all unique combinations from [2, 3, 6, 7] that sum to 7.

Solution: Backtrack with start index to avoid duplicates; prune when sum exceeds target.

java
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> results = new ArrayList<>();
    Arrays.sort(candidates);
    combinationSum(candidates, target, 0, new ArrayList<>(), results);
    return results;
}

private static void combinationSum(int[] candidates, int remaining, int start, List<Integer> current, List<List<Integer>> results) {
    if (remaining == 0) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    for (int i = start; i < candidates.length && candidates[i] <= remaining; i++) {
        current.add(candidates[i]);
        combinationSum(candidates, remaining - candidates[i], i, current, results);
        current.remove(current.size() - 1);
    }
}

Worked Example 3: N-Queens Board Configuration

Problem: Place 4 queens on a 4×4 board with no conflicts.

Solution: Backtrack row by row; maintain columns and diagonals as constraints.

java
public static List<List<String>> solveNQueens(int n) {
    List<List<String>> results = new ArrayList<>();
    solveNQueens(n, 0, new HashSet<>(), new HashSet<>(), new HashSet<>(), new ArrayList<>(), results);
    return results;
}

private static void solveNQueens(int n, int row, Set<Integer> cols, Set<Integer> diag1, Set<Integer> diag2,
                                 List<String> current, List<List<String>> results) {
    if (row == n) {
        results.add(new ArrayList<>(current));
        return;
    }
    
    for (int col = 0; col < n; col++) {
        if (!cols.contains(col) && !diag1.contains(row - col) && !diag2.contains(row + col)) {
            cols.add(col);
            diag1.add(row - col);
            diag2.add(row + col);
            current.add(buildRow(col, n));
            
            solveNQueens(n, row + 1, cols, diag1, diag2, current, results);
            
            current.remove(current.size() - 1);
            cols.remove(col);
            diag1.remove(row - col);
            diag2.remove(row + col);
        }
    }
}

private static String buildRow(int queenCol, int n) {
    char[] row = new char[n];
    Arrays.fill(row, '.');
    row[queenCol] = 'Q';
    return new String(row);
}

Solved Problems

Problem 1 (Easy): Generate all permutations of [1, 2, 3].

Problem 2 (Easy): Check if a number is "happy" (digit-square sequence reaches 1).

Problem 3 (Medium): Find all unique combinations of a sorted array that sum to a target (allow reuse).

Problem 4 (Medium): Solve Sudoku given a 9×9 grid.

Problem 5 (Hard): Solve N-Queens for arbitrary N and return all board configurations.


Recognition Guide

Use recursion and backtracking when:

  • The problem has a recursive structure (subproblems are smaller versions).
  • You need to explore many possible states or choices.
  • Early pruning can eliminate whole branches.

Avoid when:

  • The problem has no recursive structure (use iteration).
  • Memoization is not applicable and deep recursion risks stack overflow.

Comparison Tables

Technique Best Fit Core State Main Risk
Plain recursion Self-similar decomposition Parameters and call stack Missing or wrong base case
Backtracking Search over choices Partial solution plus rollback State leaks between branches
Memoization Overlapping subproblems Cache keyed by state Wrong state encoding
Iterative simulation Deep recursion or explicit traversal Manual stack/queue More bookkeeping code

Design and Decision Making

Before coding, sketch the decision tree and the base case. Define what state must be maintained and what must be undone. Use memoization if subproblems overlap. Prefer iteration if the recursion depth is unbounded.


Practical Applications

  • File system crawlers, expression evaluators, and dependency walkers all use recursion because their inputs are naturally tree-shaped.
  • Constraint solvers, route planners, and puzzle engines use backtracking with pruning to avoid exploring impossible states.
  • Dynamic-programming implementations often start as recursive formulations with memoization before being flattened into iterative tables.
  • Production services sometimes replace recursive traversal with explicit stacks when input depth is user-controlled and stack overflow is a reliability risk.

Failure Modes and Trade-offs

Forgotten undo logic creates subtle bugs. Deep recursion risks stack overflow. Memoization requires careful state definition. Over-aggressive pruning may miss solutions.


Condensed Notes

  • Base case: when recursion stops.
  • Recursive case: shrink problem and recurse.
  • Backtracking: choice, recurse, undo.
  • Subsets: include/exclude each element.
  • Permutations: try each unused element.
  • Memoization: cache subproblem results.

Additional Problems

Easy

  • Generate balanced parentheses for a small number of pairs.
  • Compute power with fast recursion and explain the base cases.

Medium

  • Partition a string into all palindrome decompositions.
  • Find all subsets when the input contains duplicates.

Hard

  • Word search on a board with pruning and visited-state rollback.
  • Expression add operators with recursive state plus precedence handling.

Key Questions

  1. What is the difference between recursion and backtracking?
  2. How do you define the base case correctly?
  3. Why must you undo changes after recursion?
  4. When should you use memoization?
  5. How do you convert recursion to iteration?
  6. What is the time complexity of subset generation?
  7. How do you prune the search tree?
  8. What is the call stack and why does it matter?
  9. How do you handle duplicates in combination problems?
  10. When is recursion clearer than iteration?

Applied Project

Build a puzzle solver: implement constraint satisfaction for a simple puzzle (like Sudoku or N-Queens), add memoization for overlapping subproblems, measure pruning effectiveness, and visualize the search tree to understand backtracking depth.

10: Binary Search Family

Introduction and Context

Binary search is the gateway technique for turning O(n) linear scans into O(log n) logarithmic searches. It works on sorted data (or sorted answer spaces) by repeatedly eliminating half the remaining possibilities.

Many learners memorize one binary search template and struggle when variations appear: finding the first occurrence, the last, or searching for an answer rather than an exact value. The key insight is that all variants share the same core: maintain a shrinking range where the answer is guaranteed to exist, and preserve that invariant with every comparison and pointer move.

This chapter teaches the canonical patterns and the mental model behind them. You will be able to implement classic binary search, lower and upper bound, binary search on answer, and off-by-one-free templates that work reliably on edge cases.

Core Intuition and Mechanics

Imagine a sorted list of names in a phone book. To find a name, you do not read from the start. You open to the middle. If the target comes before that name alphabetically, discard the right half. Otherwise discard the left half. Repeat until you find the name or confirm it does not exist.

The core model is: maintain a range [left, right] where the answer is guaranteed to exist. Every iteration, use one comparison to cut that range in half. The loop continues while the range is non-empty. When it becomes empty, the answer is either found or does not exist.

The most common pitfall is off-by-one errors. Different templates use different loop conditions and pointer updates. The key is to define and maintain one invariant clearly.

Core Concepts and Subtopics

Concept Cluster: Classic Binary Search, Iterative and Recursive Forms

Topics in this cluster:

  • 10.1 Binary Search Pattern, Classic binary search, Iterative binary search, Recursive binary search
Definition

Binary search finds an exact target in a sorted array in O(log n) time by comparing the middle element and eliminating half the remaining range.

Why It Matters

It is the foundation for all other binary search variants and teaches the mental model of "maintained invariant" that transfers to many algorithms.

java
public int binarySearch(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // not found
}

Invariant: If target exists, it is in [left, right].

java
public int binarySearchRecursive(int[] nums, int target, int left, int right) {
    if (left > right) return -1;
    
    int mid = left + (right - left) / 2;
    if (nums[mid] == target) {
        return mid;
    } else if (nums[mid] < target) {
        return binarySearchRecursive(nums, target, mid + 1, right);
    } else {
        return binarySearchRecursive(nums, target, left, mid - 1);
    }
}
When to Choose

Iterative is safer (no stack overflow) and preferred in production. Recursive is cleaner for divide-and-conquer thinking.

Common Mistakes
  • Using (left + right) / 2 instead of left + (right - left) / 2 (integer overflow).
  • Using left < right as the loop condition when <= is correct.
  • Returning mid without checking if the value matches the target.

Concept Cluster: Lower Bound and Upper Bound

Topics in this cluster:

  • 10.2 Lower bound and upper bound, Lower bound, upper bound, and search invariants
Definition

Lower bound: first index i where nums[i] >= target.
Upper bound: first index i where nums[i] > target.

Why It Matters

These are reusable for counting duplicates, range queries, and insertion-position problems.

Lower Bound Implementation
java
public int lowerBound(int[] nums, int target) {
    int left = 0, right = nums.length;
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] >= target) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    
    return left;
}

Invariant: [0, left) all < target; [left, right) unknown; [right, n) all >= target.

Upper Bound Implementation
java
public int upperBound(int[] nums, int target) {
    int left = 0, right = nums.length;
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] <= target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    
    return left;
}
Counting Duplicates with Bounds
java
int count = upperBound(nums, target) - lowerBound(nums, target);
Common Mistakes
  • Mixing up the comparison operators.
  • Using closed intervals [left, right] instead of half-open [left, right).
  • Returning mid instead of the final boundary.

Concept Cluster: Binary Search on Answer and Monotonic Predicates

Topics in this cluster:

  • 10.3 Binary search on answer, Designing monotonic conditions, Monotonic predicates
  • 10.4 Off-by-one handling and termination rules, Template comparison for inclusive and exclusive ranges
  • 10.5 Templates, invariants, and edge cases
  • 10.6 Binary search as divide and conquer
Definition

Binary search on answer searches not an array, but a range of possible answers [min, max]. The answer space must be monotonic: all values below some threshold fail a test, all above pass (or vice versa).

Why It Matters

Many optimization problems reduce to "find the smallest X such that condition(X) is true." Binary search makes that O(log(answer range)) instead of O(answer range).

Binary Search on Answer Example

Problem: Find minimum hours to eat all bananas at eating speed k.

java
public int minEatingSpeed(int[] piles, int hours) {
    int left = 1, right = maxPile(piles);
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (canEatInTime(piles, mid, hours)) {
            right = mid; // try slower (smaller speed does not work)
        } else {
            left = mid + 1;
        }
    }
    
    return left;
}

private boolean canEatInTime(int[] piles, int speed, int hours) {
    int needed = 0;
    for (int pile : piles) {
        needed += (pile + speed - 1) / speed;
    }
    return needed <= hours;
}

Invariant: speeds in [1, left) cannot eat in time; speeds in [left, right] unknown; speeds in (right, max] can eat in time.

Off-by-One Template Comparison

Inclusive range [left, right], find first true:

java
while (left < right) {
    int mid = left + (right - left) / 2;
    if (condition(mid)) {
        right = mid;
    } else {
        left = mid + 1;
    }
}
return left;

Half-open range [left, right), find first true:

java
while (left < right) {
    int mid = left + (right - left) / 2;
    if (condition(mid)) {
        right = mid;
    } else {
        left = mid + 1;
    }
}
return left;

Both converge to the first true index.

Common Mistakes
  • Applying binary search to non-monotonic answer spaces (condition is true at position 5, false at 10, true again at 15).
  • Using the wrong loop condition or pointer update.
  • Not thinking about what the converged left and right represent.

Worked Examples

Problem: Find the index of target in sorted array [1, 3, 5, 7, 9, 11].

Solution: Compare middle with target; discard half based on comparison.

java
public int search(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1;
}

Worked Example 2: Search for First and Last Occurrence

Problem: Find first and last index of target in [5, 7, 7, 8, 8, 10].

Solution: Use lower bound and upper bound.

java
public int[] searchRange(int[] nums, int target) {
    int first = lowerBound(nums, target);
    int last = upperBound(nums, target) - 1;
    
    if (first == nums.length || nums[first] != target) {
        return new int[]{-1, -1};
    }
    return new int[]{first, last};
}

private int lowerBound(int[] nums, int target) {
    int left = 0, right = nums.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] >= target) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return left;
}

private int upperBound(int[] nums, int target) {
    int left = 0, right = nums.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] <= target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}

Worked Example 3: Binary Search on Answer (Capacity to Ship Packages)

Problem: Ship packages within d days with minimum ship capacity.

Solution: Binary search on capacity; test if capacity allows shipping in d days.

java
public int shipWithinDays(int[] weights, int days) {
    int left = maxWeight(weights);
    int right = sumWeights(weights);
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (canShip(weights, mid, days)) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    
    return left;
}

private boolean canShip(int[] weights, int capacity, int days) {
    int currentLoad = 0, daysNeeded = 1;
    for (int weight : weights) {
        if (currentLoad + weight > capacity) {
            daysNeeded++;
            currentLoad = weight;
        } else {
            currentLoad += weight;
        }
    }
    return daysNeeded <= days;
}

Solved Problems

Problem 1 (Easy): Search for target in sorted array; return index or -1.

Problem 2 (Easy): Find first occurrence of target in sorted array.

Problem 3 (Medium): Search insert position (where target would be inserted to keep array sorted).

Problem 4 (Medium): Minimum capacity to ship all packages within d days.

Problem 5 (Hard): Find minimum number of days to make m bouquets with k adjacent flowers each.


Recognition Guide

Use binary search when:

  • The input is sorted or the answer space is monotonic.
  • Brute force O(n) is too slow and O(log n) is acceptable.

Avoid when:

  • The space is not monotonic (jumbled up and down).
  • The invariant is unclear.

Comparison Tables

Variant Goal Range Style Return Value
Classic binary search Exact match Usually closed [left, right] Index or -1
Lower bound First >= target Often half-open [left, right) Insertion position
Upper bound First > target Often half-open [left, right) Boundary after duplicates
Binary search on answer First feasible value Integer or answer interval Minimum or maximum valid answer

Design and Decision Making

Always state the loop invariant before coding. Decide: inclusive or half-open ranges? Are you searching for exact match, first true, or last true? Different invariants lead to different templates.


Practical Applications

  • Databases use lower-bound style logic for index seeks, pagination anchors, and range filtering.
  • Capacity planning and scheduling problems often use binary search on answer to find the smallest feasible throughput or budget.
  • Search features use upper and lower bounds to find all duplicates or prefix-matching ranges in sorted arrays.
  • Performance-sensitive code prefers iterative binary search because it is branch-light, predictable, and avoids recursion overhead.

Failure Modes and Trade-offs

Off-by-one errors are subtle. Test edge cases: target at position 0, at n-1, not found, single element, all same. Always compute mid safely.


Condensed Notes

  • Iterative safer than recursive.
  • Invariant: answer is in [left, right].
  • Lower bound: first >= target.
  • Upper bound: first > target.
  • Binary search on answer: test monotonic condition.

Additional Problems

Easy

  • Find the floor or ceiling of a target in a sorted array.
  • Return the count of a target using lower and upper bound.

Medium

  • Search a rotated sorted array with no duplicates.
  • Find the minimum element in a rotated sorted array.

Hard

  • Median of two sorted arrays using partition-based binary search.
  • Split array largest sum via binary search on answer.

Key Questions

  1. Why use left + (right - left) / 2 instead of (left + right) / 2?
  2. When is left < right vs left <= right?
  3. How do lower and upper bound differ?
  4. What is a monotonic answer space?
  5. How do you prove binary search correctness?
  6. When should you use binary search on answer?
  7. What happens if left and right never meet?
  8. How do you handle duplicates?
  9. What is the time complexity and why?
  10. How do you convert between inclusive and half-open ranges?

Applied Project

Build a coding problem difficulty estimator: use binary search on the difficulty range to estimate the minimum difficulty level at which a solution passes all test cases; test your estimator against real problem data.

11: Sorting, Selection, Bit Tricks, and Math Tools

Introduction and Context

This chapter covers the tools that transform problems once order is imposed. Sorting rearranges data; heaps extract top elements efficiently; bits compress state; math shortcuts solve counting and factorization tasks. Together, they form a toolkit for optimization beyond basic search and recursion.

The central insight is that different problems call for different tools. Some need stable sorting; some need in-place; some need a stream-based selection without full sort. Bit tricks optimize space; math shortcuts optimize counting. Knowing when to reach for each tool is what separates efficient solutions from slow ones.

Core Intuition and Mechanics

Think of each technique as answering different questions:

  • Sorting: "How do I impose order to see patterns?"
  • Heaps: "How do I get the top k elements without sorting the rest?"
  • Merge intervals: "How do I combine overlapping ranges?"
  • Cyclic sort: "How do I place elements at their target positions?"
  • Greedy: "What is the safest local choice?"
  • Bits: "How do I compress flags into one integer?"
  • Math: "What shortcuts avoid brute force?"

Each solves a different optimization problem. The art is recognizing which applies.

Core Concepts and Subtopics

Concept Cluster: Elementary and Advanced Sorting Algorithms

Topics in this cluster:

  • 11.1 Bubble sort, selection sort, and insertion sort
  • 11.2 Merge sort; Merge sort as a case study; Divide-and-conquer strategy
  • 11.3 Quick sort; Quick sort as a case study
  • 11.4 Heap sort; Counting sort and radix sort; When to use which sorting algorithm
Definition

Elementary sorts (bubble, selection, insertion) are O(n²) but teach fundamentals. Merge sort is stable and O(n log n) but uses O(n) space. Quick sort is average O(n log n), in-place, but unstable and worst-case O(n²). Counting sort and radix sort are linear on small key ranges.

When to Use Which
Algorithm Best For
Insertion sort Small arrays or nearly sorted
Merge sort Stable sort required; guaranteed O(n log n)
Quick sort Average performance; in-place needed
Counting sort Keys are small integers
Radix sort Multi-digit keys; linear time needed
Insertion Sort (In-Place, Stable)
java
public void insertionSort(int[] arr) {
    for (int i = 1; i < arr.length; i++) {
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}
Merge Sort (Stable, O(n log n))
java
public void mergeSort(int[] arr) {
    if (arr.length < 2) return;
    int mid = arr.length / 2;
    int[] left = Arrays.copyOfRange(arr, 0, mid);
    int[] right = Arrays.copyOfRange(arr, mid, arr.length);
    mergeSort(left);
    mergeSort(right);
    merge(arr, left, right);
}

private void merge(int[] arr, int[] left, int[] right) {
    int i = 0, j = 0, k = 0;
    while (i < left.length && j < right.length) {
        arr[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];
    }
    System.arraycopy(left, i, arr, k, left.length - i);
    System.arraycopy(right, j, arr, k, right.length - j);
}
Quick Sort (In-Place, Unstable)
java
public void quickSort(int[] arr) {
    quickSort(arr, 0, arr.length - 1);
}

private void quickSort(int[] arr, int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

private int partition(int[] arr, int low, int high) {
    int pivot = arr[high];
    int i = low;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
        }
    }
    int temp = arr[i];
    arr[i] = arr[high];
    arr[high] = temp;
    return i;
}
Common Mistakes
  • Merge sort: forgetting to copy remaining elements.
  • Quick sort: choosing worst-case pivot (use randomization or median-of-three).
  • Counting sort: forgetting the size of the range.

Concept Cluster: Top K, Heap Pattern, and Streaming

Topics in this cluster:

  • 11.5 Top K Elements Pattern, Heap Pattern, Top K and streaming problems
Definition

Top K asks: find the k largest (or smallest) elements without fully sorting.

Why It Matters

Full sort is O(n log n). Using a heap, you can find top k in O(n log k), much faster when k << n.

Min Heap Approach (Keep Largest k)
java
public List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int num : nums) {
        freq.put(num, freq.getOrDefault(num, 0) + 1);
    }
    
    PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b) -> freq.get(a) - freq.get(b));
    
    for (int num : freq.keySet()) {
        minHeap.offer(num);
        if (minHeap.size() > k) {
            minHeap.poll();
        }
    }
    
    return new ArrayList<>(minHeap);
}

Complexity: O(n log k).

Common Mistakes
  • Using max heap (you want min heap to keep only top k).
  • Not checking heap size before polling.

Concept Cluster: Merge Intervals, Cyclic Sort, and Greedy Patterns

Topics in this cluster:

  • 11.6 Merge Intervals Pattern; Sorting by endpoints and overlap normalization; Interval edge cases with touching and nested ranges
  • 11.7 Cyclic Sort Pattern; Placement-by-index problems and missing-value tricks; When sorting is the real hidden pattern
  • 11.8 Greedy Choice Pattern; Meet in the Middle Pattern; Randomized Algorithm Pattern; Trade-offs between sorting, heap selection, greed, and search splitting
  • 11.9 Greedy-choice property; Activity selection; Fractional knapsack; Interval scheduling; Huffman coding; Proving a greedy strategy
Merge Intervals
java
public int[][] merge(int[][] intervals) {
    if (intervals.length == 0) return new int[0][0];
    
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    
    List<int[]> result = new ArrayList<>();
    int[] current = intervals[0];
    
    for (int i = 1; i < intervals.length; i++) {
        if (intervals[i][0] <= current[1]) {
            current[1] = Math.max(current[1], intervals[i][1]);
        } else {
            result.add(current);
            current = intervals[i];
        }
    }
    result.add(current);
    
    return result.toArray(new int[0][]);
}
Cyclic Sort (Place Element at Its Index)
java
public void cyclicSort(int[] arr) {
    int i = 0;
    while (i < arr.length) {
        int correct = arr[i] - 1;
        if (arr[i] != arr[correct]) {
            int temp = arr[i];
            arr[i] = arr[correct];
            arr[correct] = temp;
        } else {
            i++;
        }
    }
}
Greedy Activity Selection
java
public int maxActivities(int[] start, int[] end) {
    // Sort by end time
    Integer[] indices = new Integer[start.length];
    for (int i = 0; i < indices.length; i++) indices[i] = i;
    Arrays.sort(indices, (i, j) -> Integer.compare(end[i], end[j]));
    
    int count = 1;
    int lastEnd = end[indices[0]];
    
    for (int i = 1; i < indices.length; i++) {
        if (start[indices[i]] >= lastEnd) {
            count++;
            lastEnd = end[indices[i]];
        }
    }
    
    return count;
}

Concept Cluster: Bitwise Operators and Bit Manipulation

Topics in this cluster:

  • 11.10 Bitwise operators, Set/clear/toggle bit operations, Counting bits, XOR tricks, Bitmasking basics, Subset and state-encoding patterns
Definition

Bit operators work directly on binary representation. XOR cancels pairs. Bitmasking stores yes/no state in one integer.

Set, Clear, Toggle Bits
java
// Set bit k
int set(int num, int k) { return num | (1 << k); }

// Clear bit k
int clear(int num, int k) { return num & ~(1 << k); }

// Toggle bit k
int toggle(int num, int k) { return num ^ (1 << k); }

// Test bit k
boolean testBit(int num, int k) { return (num & (1 << k)) != 0; }

// Count set bits
int countBits(int num) {
    int count = 0;
    while (num > 0) {
        num &= num - 1;
        count++;
    }
    return count;
}
XOR Trick (Find Unique Element)
java
int findUnique(int[] arr) {
    int result = 0;
    for (int num : arr) {
        result ^= num;
    }
    return result;
}
Bitmasking Subsets
java
List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    for (int mask = 0; mask < (1 << nums.length); mask++) {
        List<Integer> subset = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if ((mask & (1 << i)) != 0) {
                subset.add(nums[i]);
            }
        }
        result.add(subset);
    }
    return result;
}

Concept Cluster: Math Tools and Shortcuts

Topics in this cluster:

  • 11.11 GCD and LCM, Factorization and divisors, Logarithms in algorithm analysis, Fast exponentiation, Modular arithmetic basics, Math shortcuts for interview problems
  • 11.12 Closest pair problem, Recurrence thinking and solution structure
GCD and LCM
java
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int lcm(int a, int b) {
    return a / gcd(a, b) * b;
}
Fast Exponentiation (Modulo)
java
long power(long base, long exp, long mod) {
    long result = 1;
    base %= mod;
    while (exp > 0) {
        if ((exp & 1) == 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        exp >>= 1;
    }
    return result;
}
Divisors and Factorization
java
List<Integer> getDivisors(int n) {
    List<Integer> divisors = new ArrayList<>();
    for (int i = 1; i * i <= n; i++) {
        if (n % i == 0) {
            divisors.add(i);
            if (i != n / i) {
                divisors.add(n / i);
            }
        }
    }
    return divisors;
}

Worked Examples

Worked Example 1: Merge Sorted Intervals

Problem: Merge overlapping intervals.

Solution: Sort by start; extend current interval if overlapping; record when gap appears.

(See Merge Intervals code above.)


Worked Example 2: Top K Frequent Elements

Problem: Find k most frequent elements in array.

Solution: Count frequencies; use min heap to keep top k.

(See Top K Frequent code above.)


Worked Example 3: Find Missing Number (Cyclic Sort)

Problem: Array contains n distinct numbers from 0 to n. Find missing.

Solution: Place each number at its index; find position without its target.

java
public int missingNumber(int[] nums) {
    int i = 0;
    while (i < nums.length) {
        int correct = nums[i];
        if (correct < nums.length && correct != i && nums[correct] != correct) {
            int temp = nums[i];
            nums[i] = nums[correct];
            nums[correct] = temp;
        } else {
            i++;
        }
    }
    
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != j) return j;
    }
    return nums.length;
}

Solved Problems

Problem 1 (Easy): Sort array by frequency.

Problem 2 (Easy): Find missing number using XOR.

Problem 3 (Medium): Merge overlapping intervals.

Problem 4 (Medium): Top k frequent elements.

Problem 5 (Hard): Median of data stream using two heaps.


Recognition Guide

Use sorting when you need to impose order for pattern recognition. Use heaps for top k without full sort. Use bitwise for state compression. Use math for counting without loops.


Comparison Tables

Tool Best When Time Pattern Main Trade-off
Full sort You need total order Usually O(n log n) More work than necessary for top-k only
Heap You need repeated min/max or top k O(log k) or O(log n) updates No full global order
Cyclic sort Values map naturally to indexes Near-linear Only works for constrained ranges
Bit tricks State fits in bits Constant-time state ops Lower readability
Math shortcut Algebra replaces iteration Often sublinear Requires proof and edge-case care

Design and Decision Making

Choose merge sort if stability matters. Choose quick sort for average performance. Choose counting/radix for small-range keys. Choose heap for streaming top k. Choose bits for state under 64 flags. Choose math for large numbers.


Practical Applications

  • Log-processing pipelines use heaps for streaming top-k queries and medians without sorting the full stream.
  • Scheduling and calendar systems rely on interval sorting and merge logic to normalize overlaps.
  • Compilers, databases, and networking stacks use bit flags for compact state storage and fast checks.
  • Cryptography, hashing, simulations, and distributed systems all depend on modular arithmetic and fast exponentiation.

Failure Modes and Trade-offs

Unstable sorts lose original order on duplicates. Heap operations are log n each. Bit tricks are concise but obscure. Math shortcuts require proof of correctness.


Condensed Notes

  • Insertion sort: small or nearly sorted.
  • Merge sort: stable, guaranteed O(n log n), O(n) space.
  • Quick sort: average O(n log n), O(1) space, unstable.
  • Counting/radix: linear on small key range.
  • Heap: top k in O(n log k).
  • Bitwise: set, clear, toggle, XOR, count.
  • Math: GCD, fast exponentiation, divisors.

Additional Problems

Easy

  • Sort characters by frequency with a heap or bucket array.
  • Find the single non-duplicated number using XOR.

Medium

  • Reorganize string with a max heap and greedy placement.
  • Insert and merge a new interval into a sorted interval list.

Hard

  • Sliding window median with two heaps and lazy deletion.
  • Closest pair of points using divide and conquer.

Key Questions

  1. Which sort is stable?
  2. Why is merge sort guaranteed O(n log n)?
  3. How does quick sort partition work?
  4. When is counting sort better than merge sort?
  5. How do you find top k efficiently?
  6. What does XOR with all elements do?
  7. How do you set a specific bit?
  8. What is the formula for GCD?
  9. Why does bitmasking encode subsets?
  10. When is cyclic sort the right pattern?

Applied Project

Build a data stream analyzer: find top k frequent words in an infinite stream using heaps, track running median, compute statistics (GCD of number sequences), and use bitmasking to represent word-character sets efficiently.

12: Structural Design Patterns I

Introduction and Context

Structural patterns address how objects and classes are combined into larger structures while keeping those structures flexible and efficient. They are less about creation (like Chapter 8) and more about composition: how should objects relate, delegate, and wrap each other?

The central question is: how do you add behavior without tight coupling, without creating a combinatorial explosion of classes, and without breaking existing code? Structural patterns answer this with composition strategies: adapters convert interfaces, facades simplify complexity, proxies control access, bridges decouple abstraction from implementation, composites unify tree and leaf, decorators add behavior dynamically.

This chapter covers the first six major structural patterns. Understanding these teaches composition discipline that transfers to architecture, testing, and long-term maintainability.

Core Intuition and Mechanics

Think of each pattern as answering how objects should relate:

  • Adapter: "How do I make incompatible interfaces work together?"
  • Facade: "How do I simplify a complex subsystem?"
  • Proxy: "How do I control access to another object?"
  • Bridge: "How do I decouple an abstraction from its implementation?"
  • Composite: "How do I treat individual and composite objects uniformly?"
  • Decorator: "How do I add behavior dynamically without inheritance?"

Each uses composition strategically. The result is code that respects open-closed principle: open for extension (new variants), closed for modification (existing code unchanged).

Core Concepts and Subtopics

Concept Cluster: Adapter and Facade Patterns

Topics in this cluster:

  • 12.1 Adapter Pattern: Class adapter, Object adapter, Legacy integration, Interface conversion, Wrapper design trade-offs, Adapter versus facade
  • 12.2 Facade Pattern and simplified interface, Subsystem wrapping and layered access
Definition

Adapter converts one interface into another so incompatible classes can work together. Facade provides a simplified, unified interface to a complex subsystem.

Why It Matters

Adapters let you integrate legacy code without rewriting it. Facades hide subsystem complexity from clients, making systems easier to use and change.

Object Adapter (Preferred in Java)
java
// Existing incompatible interface
interface Target {
    void request();
}

class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee specific request");
    }
}

// Adapter wraps Adaptee and implements Target
class ObjectAdapter implements Target {
    private Adaptee adaptee;
    
    public ObjectAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// Usage
Adaptee adaptee = new Adaptee();
Target target = new ObjectAdapter(adaptee);
target.request();
Facade Pattern
java
// Subsystem classes
class SubsystemA {
    public void operationA() { System.out.println("Subsystem A"); }
}

class SubsystemB {
    public void operationB() { System.out.println("Subsystem B"); }
}

// Facade provides simplified interface
class Facade {
    private SubsystemA a = new SubsystemA();
    private SubsystemB b = new SubsystemB();
    
    public void complexOperation() {
        a.operationA();
        b.operationB();
        System.out.println("Complex operation done");
    }
}

// Client uses only Facade
Facade facade = new Facade();
facade.complexOperation();
Adapter vs Facade

Adapter makes two incompatible things work. Facade simplifies many related things into one. Adapter is one-to-one; facade is many-to-one.

Common Mistakes
  • Using Adapter when Facade would be clearer.
  • Forgetting that Adapter does not change Adaptee's behavior.
  • Making Facade try to do too much (God object).

Concept Cluster: Proxy and Bridge Patterns

Topics in this cluster:

  • 12.3 Proxy Pattern and controlled access, Virtual/protection/remote/caching proxies, Lazy loading proxy and lifecycle control, Facade versus proxy versus adapter
  • 12.4 Bridge Pattern: Abstraction layer, Implementation layer, Decoupling dimensions, Platform variations, Runtime extensibility, Bridge versus strategy
Definition

Proxy provides a surrogate that controls access to another object. Bridge decouples an abstraction from its implementation so they can vary independently.

Why It Matters

Proxies enable lazy initialization, access control, logging, and caching without changing the original object. Bridges avoid combinatorial class explosion when you have two independent dimensions of variation.

Proxy Pattern: Caching Example
java
interface DataService {
    String fetch(String key);
}

class RealDataService implements DataService {
    @Override
    public String fetch(String key) {
        System.out.println("Fetching from network: " + key);
        return "data for " + key;
    }
}

class CachingProxy implements DataService {
    private RealDataService real = new RealDataService();
    private Map<String, String> cache = new HashMap<>();
    
    @Override
    public String fetch(String key) {
        if (!cache.containsKey(key)) {
            cache.put(key, real.fetch(key));
        }
        return cache.get(key);
    }
}

// Client uses proxy; unaware of caching
DataService service = new CachingProxy();
System.out.println(service.fetch("key1")); // fetches
System.out.println(service.fetch("key1")); // cached
Bridge Pattern: Shape and Color
java
// Abstraction
interface DrawAPI {
    void draw(int x, int y, int radius);
}

class RedDraw implements DrawAPI {
    @Override
    public void draw(int x, int y, int radius) {
        System.out.println("Red circle at (" + x + "," + y + ")");
    }
}

// Refined Abstraction
abstract class Shape {
    protected DrawAPI drawAPI;
    
    public Shape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }
    
    abstract void draw();
}

class Circle extends Shape {
    private int x, y, radius;
    
    public Circle(int x, int y, int radius, DrawAPI drawAPI) {
        super(drawAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    
    @Override
    public void draw() {
        drawAPI.draw(x, y, radius);
    }
}

// Usage: vary shape and color independently
Circle redCircle = new Circle(0, 0, 10, new RedDraw());
redCircle.draw();
Proxy vs Bridge

Proxy controls access to one object. Bridge decouples two dimensions (abstraction and implementation). Proxy is a shim; Bridge is structural independence.

Common Mistakes
  • Using Proxy when you really mean inheritance or delegation.
  • Making Bridge too abstract (it is for genuine orthogonal dimensions, not every parameter).

Concept Cluster: Composite and Decorator Patterns

Topics in this cluster:

  • 12.5 Composite Pattern: Tree structure, Leaf nodes, Composite nodes, Recursive operations, Uniform client treatment, Composite plus traversal extensions
  • 12.6 Decorator Pattern: Dynamic behavior addition, Wrapper chaining, Runtime extensions, I/O stream example, Ordering multiple decorators, Decorator versus inheritance
Definition

Composite lets you compose objects into tree structures where clients treat individual and composite objects uniformly. Decorator attaches additional responsibilities to objects dynamically, providing a flexible alternative to inheritance.

Why It Matters

Composite handles variable-depth hierarchies elegantly (file systems, menus, expression trees). Decorator adds features at runtime without class explosion.

Composite Pattern: File System
java
abstract class FileSystemNode {
    protected String name;
    
    public FileSystemNode(String name) {
        this.name = name;
    }
    
    abstract int getSize();
    abstract void display(String indent);
}

class File extends FileSystemNode {
    private int size;
    
    public File(String name, int size) {
        super(name);
        this.size = size;
    }
    
    @Override
    public int getSize() { return size; }
    
    @Override
    public void display(String indent) {
        System.out.println(indent + "File: " + name + " (" + size + " bytes)");
    }
}

class Directory extends FileSystemNode {
    private List<FileSystemNode> children = new ArrayList<>();
    
    public Directory(String name) {
        super(name);
    }
    
    public void add(FileSystemNode node) {
        children.add(node);
    }
    
    @Override
    public int getSize() {
        return children.stream().mapToInt(FileSystemNode::getSize).sum();
    }
    
    @Override
    public void display(String indent) {
        System.out.println(indent + "Dir: " + name);
        for (FileSystemNode child : children) {
            child.display(indent + "  ");
        }
    }
}
Decorator Pattern: I/O Streams Style
java
interface Component {
    void operation();
}

class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("Basic operation");
    }
}

abstract class Decorator implements Component {
    protected Component component;
    
    public Decorator(Component component) {
        this.component = component;
    }
    
    @Override
    public void operation() {
        component.operation();
    }
}

class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }
    
    @Override
    public void operation() {
        System.out.println("Before A");
        component.operation();
        System.out.println("After A");
    }
}

class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }
    
    @Override
    public void operation() {
        System.out.println("Before B");
        component.operation();
        System.out.println("After B");
    }
}

// Usage: stack decorators
Component component = new ConcreteComponent();
component = new ConcreteDecoratorA(component);
component = new ConcreteDecoratorB(component);
component.operation(); // Before B, Before A, Basic, After A, After B
Composite vs Decorator

Composite builds trees; Decorator wraps linearly. Composite unifies leaf and composite; Decorator extends behavior.

Common Mistakes
  • Making Composite nodes responsible for GUI rendering (separate traversal logic).
  • Stacking too many decorators (becomes hard to reason about order).
  • Forgetting to implement all Component methods in Decorator.

Worked Examples

Worked Example 1: Adapter for Legacy Code Integration

Problem: You have an existing PaymentProcessor with incompatible method signatures, but your system expects a PaymentGateway interface.

Solution: Create an Object Adapter.

java
interface PaymentGateway {
    boolean pay(double amount);
}

class LegacyPaymentProcessor {
    public String processPayment(float cost) {
        return "Payment of " + cost + " processed";
    }
}

class PaymentAdapter implements PaymentGateway {
    private LegacyPaymentProcessor legacy;
    
    public PaymentAdapter(LegacyPaymentProcessor legacy) {
        this.legacy = legacy;
    }
    
    @Override
    public boolean pay(double amount) {
        String result = legacy.processPayment((float) amount);
        return result.contains("processed");
    }
}

Worked Example 2: Facade for Database Layer Simplification

Problem: Your database layer has many classes (Connection, Statement, Result, Transaction). Clients should not interact with all of them.

Solution: Create a Facade.

java
class DatabaseFacade {
    private DatabaseConnection conn = new DatabaseConnection();
    
    public List<Map<String, Object>> query(String sql) {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        return convertToMaps(rs);
    }
    
    public boolean execute(String sql) {
        Statement stmt = conn.createStatement();
        return stmt.execute(sql);
    }
    
    private List<Map<String, Object>> convertToMaps(ResultSet rs) {
        // Convert result to list of maps
        return new ArrayList<>();
    }
}

// Client uses only Facade
DatabaseFacade db = new DatabaseFacade();
List<Map<String, Object>> results = db.query("SELECT * FROM users");

Worked Example 3: Composite Directory Tree with Total Size

Problem: Calculate total size of a directory and all nested files.

Solution: Use Composite pattern; recurse on all children.

(See Composite Pattern code above for full example.)


Solved Problems

Problem 1 (Easy): Adapt ArrayList to behave like Stack.

Problem 2 (Easy): Create a Facade for a coffee shop ordering system.

Problem 3 (Medium): Build a Composite file system supporting size and display operations.

Problem 4 (Medium): Implement a caching Proxy for expensive computations.

Problem 5 (Hard): Implement Decorator for I/O streams with encryption and compression.


Recognition Guide

Use Adapter when integrating incompatible libraries. Use Facade to hide complexity. Use Proxy for access control or caching. Use Bridge when two dimensions vary independently. Use Composite for tree hierarchies. Use Decorator for optional behaviors.


Comparison Tables

Pattern Main Use Shape Common Confusion
Adapter Interface conversion One wrapper around one target Mistaken for Facade
Facade Simplified subsystem entry point One front door over many collaborators Turning it into a God object
Proxy Access control, caching, lazy loading Surrogate with same interface Mistaken for Decorator
Bridge Independent abstraction and implementation axes Two-layer delegation Using it for simple parameter choices
Composite Uniform tree operations Recursive parent-child structure Mixing traversal logic into node responsibilities
Decorator Runtime behavior stacking Linear wrapper chain Losing track of wrapper order

Design and Decision Making

Adapter is about interface conversion. Facade is about simplification. Proxy is about control. Bridge is about decoupling. Composite is about uniformity. Decorator is about runtime flexibility. Choose based on the problem shape, not just "I want to wrap something."


Practical Applications

  • SDK integrations and legacy migrations often start with Adapters so the rest of the codebase can keep one internal interface.
  • Facades show up in service layers, payment orchestration, and persistence boundaries where clients need one stable entry point over many moving parts.
  • Proxies power lazy loading in ORM systems, access checks in security wrappers, and cached network calls in API clients.
  • Composite and Decorator are both common in UI systems, document trees, and file explorers where structure and optional behavior both evolve over time.

Failure Modes and Trade-offs

Adapter adds indirection. Facade can become a God object. Proxy adds a layer. Bridge adds classes. Composite requires traversal logic. Decorator stacking becomes complex.


Condensed Notes

  • Adapter: convert incompatible interfaces.
  • Facade: simplify complex subsystem.
  • Proxy: control access or delay creation.
  • Bridge: separate abstraction from implementation.
  • Composite: uniform tree and leaf treatment.
  • Decorator: add behavior at runtime.

Additional Problems

Easy

  • Wrap a legacy logger behind a modern application logging interface.
  • Build a Facade for a video player subsystem.

Medium

  • Implement a virtual proxy for lazy image loading.
  • Design a Composite menu tree with recursive rendering.

Hard

  • Build a Decorator chain for request processing with compression, encryption, and auditing.
  • Refactor a platform-specific drawing API into a Bridge-based design.

Key Questions

  1. When should you use Adapter vs Bridge?
  2. How do you prevent Facade from becoming a God object?
  3. What types of Proxies exist?
  4. Why is Bridge useful when you have 2× variation dimensions?
  5. How does Composite differ from Decorator?
  6. Can you combine Decorator and Composite?
  7. How do you order multiple Decorators?
  8. When is Proxy better than inheritance?
  9. What is the relationship between Adapter and Facade?
  10. How do you test code with Proxy?

Applied Project

Build a file system explorer: implement Composite for nested directories, Adapter for multiple file system types, Facade for a simple API, Proxy for lazy-loading large files, and Decorator for file properties (compression, encryption status).

13: Tree Fundamentals

Introduction and Context

Trees matter because many real systems are hierarchical rather than linear. Filesystems, org charts, HTML documents, and category menus all branch from parent to child. Linear data structures force everything into a sequence; trees capture the actual shape of the problem.

The core challenge is that many learners understand recursion but struggle to match recursion state with tree structure. A wrong return value or a missing base case silently corrupts the entire subtree. Similarly, choosing between DFS and BFS changes what information is available at each step—DFS reveals path context, BFS reveals layer order.

Tree correctness comes from explicitly naming the invariant: what does this recursive call represent? What state enters a node? What state leaves it?

Core Intuition and Mechanics

Think of a tree as a function evaluation chart. The root is the main problem. Subtrees are subproblems. Recursion is not a mysterious loop—it is a restatement of "solve the subtree, combine results."

  • DFS visits deeply; you know the full path from root to current node.
  • BFS visits breadth-first; you know all nodes at the current distance from root.
  • Preorder visits parent before children; useful for copying or writing state.
  • Postorder visits children before parent; useful when the answer depends on child results first.
  • Inorder (on binary trees) visits left, parent, right; useful for sorted traversal in BSTs.

The mechanical invariants that matter:

  • Base case: when a node is null or a leaf, stop.
  • Recursive case: combine results from children in the correct order.
  • Return value: match what the problem actually needs (a count, a node, a path, or nothing).

Core Concepts and Subtopics

Concept Cluster: Tree Terminology and Properties

Topics in this cluster:

  • 13.1 Tree terminology; Height, depth, and degree; Root, internal, and leaf nodes
  • 13.5 Tree properties; Full, complete, perfect, and balanced binary trees
Definition

Root: the topmost node with no parent. Leaf: a node with no children. Internal node: a node with at least one child. Depth: edges from root to a node. Height: edges from a node to its deepest descendant. Degree: number of children. Full binary tree: every node has 0 or 2 children. Complete binary tree: every level full except possibly the last, filled left-to-right. Perfect binary tree: all internal nodes have 2 children and all leaves at the same depth. Balanced binary tree: subtree heights differ by at most 1.

Why It Matters

Tree terminology lets you describe structure precisely. Shape properties like "complete" guarantee array-based efficiency (heaps). Understanding depth vs. height prevents off-by-one bugs in recursion.

Java Implementation Notes
java
class TreeNode {
    int value;
    TreeNode left, right;
    List<TreeNode> children;  // for general trees
    TreeNode(int value) { this.value = value; }
}

For general trees, use List<TreeNode>. For binary trees, use explicit left and right.

Common Mistakes
  • Confusing depth and height.
  • Assuming a node with one child is a leaf.
  • Calling a single-node tree a leaf (it is a root).

Concept Cluster: DFS and BFS Recursion Patterns

Topics in this cluster:

  • 13.3 Recursion on trees; DFS recursion on trees; Tree DFS Pattern
  • 13.4 BFS level order; Tree BFS Pattern; Level-order traversal
  • 13.6 Path state, subtree state, and ancestor queries
Definition

DFS recursion: process subtrees in a single execution chain. BFS: process nodes level by level using a queue. Path state: information about the path from root to current node. Subtree state: information about a fully processed subtree.

How DFS Works

Preorder processes parent before children. Postorder processes children before parent.

java
void dfs(TreeNode node, List<Integer> result) {
    if (node == null) return;
    result.add(node.value);                    // preorder
    dfs(node.left, result);
    dfs(node.right, result);
}
How BFS Works
java
List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        List<Integer> level = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node = queue.poll();
            level.add(node.value);
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        result.add(level);
    }
    return result;
}
Java Notes

For DFS, recursion is clearest. For BFS, use ArrayDeque or LinkedList as the queue. Key insight: measure the queue size at loop start to separate levels.

Common Mistakes
  • Forgetting the null check.
  • Mixing up what the return value means.
  • Not separating levels in BFS.

Worked Examples

Worked Example 1: Maximum Depth (DFS Path State)

java
int maxDepth(TreeNode root) {
    if (root == null) return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Why it works: the height of a subtree is 1 plus the height of the taller child. Base case is null → 0.

Worked Example 2: Level-Order Traversal (BFS)

java
List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    if (root == null) return result;
    Queue<TreeNode> q = new LinkedList<>();
    q.offer(root);
    while (!q.isEmpty()) {
        int size = q.size();
        List<Integer> level = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode n = q.poll();
            level.add(n.value);
            if (n.left != null) q.offer(n.left);
            if (n.right != null) q.offer(n.right);
        }
        result.add(level);
    }
    return result;
}

Key insight: the queue size at the start of each loop iteration is exactly one level.

Worked Example 3: Validate Binary Search Tree (Subtree + Ancestor State)

java
boolean isValidBST(TreeNode root) {
    return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

boolean validate(TreeNode node, long min, long max) {
    if (node == null) return true;
    if (node.value <= min || node.value >= max) return false;
    return validate(node.left, min, node.value) && validate(node.right, node.value, max);
}

Why it works: track the valid range as we descend. The value must be strictly between the bounds.


Solved Problems

Problem 1 (Easy): Invert a binary tree (swap left and right recursively).

Problem 2 (Easy): Check if a tree is symmetric (mirror image).

Problem 3 (Medium): Path sum (root-to-leaf sums; return count where sum equals target).

Problem 4 (Medium): Lowest common ancestor of two nodes in a tree.

Problem 5 (Hard): Serialize and deserialize a binary tree (BFS or preorder with markers).


Recognition Guide

Use tree DFS when the answer depends on subtree results or path-to-root context. Use BFS when you need layer-by-layer processing or shortest edge distance. Choose DFS when combining child results; BFS when processing one level at a time.

Avoid forced recursion on non-tree inputs. Do not mix DFS and BFS in the same traversal unless you have a clear reason.


Comparison Tables

Pattern Use Case Space Time
DFS Recursion subtree summaries, path questions O(height) stack O(n)
BFS Queue level order, shortest distance O(width) queue O(n)
Preorder copy tree, prefix expression O(height) stack O(n)
Postorder aggregate from children O(height) stack O(n)

Design and Decision Making

Before writing any tree code, ask: "What does each recursive call return?" and "What state needs to flow down (ancestors) vs. up (children)?"

For path state, pass arguments downward. For subtree state, return values upward. Mix them when needed, but name both explicitly.

Avoid deep nesting of recursive calls; keep the call chain to 2–3 levels in the main logic.


Practical Applications

  • Filesystems: traverse directories and compute total size using postorder.
  • DOM trees: find elements using BFS and ancestors using DFS with bounds.
  • Org charts: count team size (postorder) or find all reports (DFS).
  • Game trees: minimax uses postorder to compute best move at each level.

Failure Modes and Trade-offs

Deep recursion: stack overflow if height > ~10000. Use iteration + explicit stack for very deep trees.

Wrong base case: returns garbage for single-node trees. Always test null and single-node cases first.

Missing null checks: crashes if pointers are null. Guard every child access or ensure preconditions in documentation.

Returning the wrong type: matching return value to recursive usage is error-prone. Write a comment if unclear.


Condensed Notes

  • Base case: if (node == null) return ...
  • Preorder: parent, left, right.
  • Postorder: left, right, parent.
  • DFS: recursion stack = path state.
  • BFS: queue levels = layer state.
  • Validate BST: track min/max as you descend.
  • Height: 1 + max(left, right).

Additional Problems

Easy: Diameter of binary tree. Same tree. Subtree of another tree. Univalued subtree.

Medium: Binary tree right side view. Maximum path sum. Reconstruct tree from traversals.

Hard: Serialize/deserialize BST. Median of two BSTs. Maximum product path.


Key Questions

  1. What is the difference between depth and height?
  2. When do you use DFS vs. BFS?
  3. Why does postorder suit aggregation problems?
  4. How do you validate a BST using only one pass?
  5. What state flows down in recursive tree algorithms?
  6. How do you avoid stack overflow in very deep trees?
  7. Why does BFS require queue-size measurement at loop start?
  8. How do you reconstruct a tree from preorder and inorder?
  9. What is the invariant for path-state recursion?
  10. How do you handle trees with more than two children?

Applied Project

Build a file system browser: represent directories as a tree, allow traversal, compute total size, and find largest files using DFS and BFS.

14: Binary Trees and BST

Introduction and Context

Binary trees with two children per node simplify traversal and enable strong algorithmic guarantees. When you add the BST property—left subtree smaller, right subtree larger—the tree becomes a searchable data structure, not just a shape.

The core challenge: BST correctness is fragile. A simple mistake in insertion, deletion, or validation can silently create an invalid tree. Similarly, many learners confuse tree shape (what pointers exist) with tree order (what values matter).

The key insight: a binary tree is only as good as its invariant. For BSTs, that invariant is "every node is larger than its left subtree and smaller than its right." Break that, and search fails.

Core Intuition and Mechanics

Think of a BST as a decision tree. To find a value, you ask one question at each node: "Is my target smaller or larger?" That single comparison eliminates an entire half of the tree.

  • Inorder traversal on a BST produces sorted values.
  • Search uses the value ordering to eliminate half the tree at each step.
  • Insertion finds the right spot by following the search path and attaching at the null child.
  • Deletion has three cases: no children, one child, or two children.
  • Validation checks that every node respects the BST property relative to all ancestors, not just its immediate parent.

The mechanical rules:

  • Search left if target < node.value, right if target > node.value.
  • Insert at the first null position found on the search path.
  • Delete by removing the node and promoting the most appropriate child (successor or predecessor).
  • Validate using ancestor bounds, not just parent comparison.

Core Concepts and Subtopics

Concept Cluster: Binary Tree Shapes and Traversals

Topics in this cluster:

  • 14.1 Binary Trees and Traversals: Inorder traversal; Preorder traversal; Postorder traversal
  • 14.2 Morris traversal
Definition

Inorder: left, root, right. Preorder: root, left, right. Postorder: left, right, root. Morris traversal: use right-subtree threads to avoid stack space.

Inorder Recursive
java
void inorder(TreeNode node, List<Integer> result) {
    if (node == null) return;
    inorder(node.left, result);
    result.add(node.value);
    inorder(node.right, result);
}
Morris Inorder (O(1) space)
java
List<Integer> morrisInorder(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 {
                result.add(current.value);
                predecessor.right = null;
                current = current.right;
            }
        }
    }
    return result;
}
Why Morris Matters

Recursion uses O(height) space on the call stack. Morris threads pointers temporarily to achieve O(1) space without recursion.

Java Notes

Recursive traversals are clearest for most interview problems. Morris is advanced but useful when space is tight.


Concept Cluster: BST Property, Search, Insert, Delete

Topics in this cluster:

  • 14.3 BST property and search; BST search, insert, and delete operations
  • 14.4 Validating a BST; Insert and delete operations in practice
Definition

BST property: for every node, all values in the left subtree < node.value < all values in the right subtree.

java
TreeNode search(TreeNode root, int target) {
    if (root == null || root.value == target) return root;
    return target < root.value ? search(root.left, target) : search(root.right, target);
}
Insert
java
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;
}
Delete
java
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 = findMin(root.right);
        root.value = successor.value;
        root.right = delete(root.right, successor.value);
    }
    return root;
}

TreeNode findMin(TreeNode node) {
    while (node.left != null) node = node.left;
    return node;
}
Validate BST
java
boolean isValidBST(TreeNode root) {
    return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

boolean validate(TreeNode node, long min, long max) {
    if (node == null) return true;
    if (node.value <= min || node.value >= max) return false;
    return validate(node.left, min, node.value) && validate(node.right, node.value, max);
}

Key insight: track the valid range as you descend. Parent comparison alone is insufficient.


Concept Cluster: Order-Statistics and Interview Patterns

Topics in this cluster:

  • 14.5 Kth smallest and order-statistics style problems
  • 14.6 Common BST interview questions; Interview patterns
Definition

Kth smallest: find the k-th element in sorted order. Inorder traversal gives sorted values; stop at position k.

java
int kthSmallest(TreeNode root, int k) {
    List<Integer> inorder = new ArrayList<>();
    inorder(root, inorder);
    return inorder.get(k - 1);
}

void inorder(TreeNode node, List<Integer> result) {
    if (node == null) return;
    inorder(node.left, result);
    result.add(node.value);
    inorder(node.right, result);
}
Optimized Kth Smallest (early stop)
java
class KthSmallestCounter {
    int count = 0;
    int result = -1;

    void inorder(TreeNode node, int k) {
        if (node == null || count >= k) return;
        inorder(node.left, k);
        count++;
        if (count == k) {
            result = node.value;
            return;
        }
        inorder(node.right, k);
    }
}

Worked Examples

Worked Example 1: Insert and Maintain BST

java
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;
}

Dry run: Insert 5, 3, 7 into empty tree. Root becomes 5. Insert 3 → goes left. Insert 7 → goes right.

Worked Example 2: Delete with Two Children

Delete 5 from tree with root 5, left 3, right 7.

  • Node has two children.
  • Find successor (6 from right subtree).
  • Replace value and delete the successor.

Complexity: O(log n) average, O(n) worst (skewed).

Worked Example 3: Validate and Correct

Check if tree is valid BST while maintaining bounds for ancestors.

java
boolean isValid(TreeNode root) {
    return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

Key: bounds change as you descend. Left child must be < parent. Right child must be > parent.


Solved Problems

Problem 1 (Easy): Search for value in BST.

Problem 2 (Easy): Convert sorted array to balanced BST.

Problem 3 (Medium): Inorder successor in BST.

Problem 4 (Medium): Recover corrupted BST (two nodes swapped; restore it).

Problem 5 (Hard): Largest BST subtree in a possibly-invalid tree.


Recognition Guide

Use BST when you need both search and sorted iteration. BST problems often hinge on recognizing when inorder produces sorted values or when deletion requires successor logic.

Avoid BST when you only need exact lookup (hash map is simpler) or when range queries matter more than sorted traversal (segment trees are better).


Comparison Tables

Operation Array BST (Balanced) Hash Map
Search O(log n) binary search O(log n) O(1) average
Insert O(n) shift O(log n) O(1) average
Delete O(n) shift O(log n) O(1) average
Inorder O(n) O(n) N/A

Design and Decision Making

Use BSTs when you need sorted traversal and dynamic updates. Use hash maps for pure lookup. Use balanced-tree variants (AVL, Red-Black) when worst-case log n is critical.


Practical Applications

  • Databases: B-trees are BST generalizations for disk-based indexing.
  • Sorted maps: TreeMap in Java uses red-black trees.
  • Expression evaluation: BST for operator precedence.

Failure Modes and Trade-offs

Unbalanced BST: insertion in sorted order creates a chain; O(n) search. Use self-balancing variants or randomize.

Wrong deletion: forgetting successor logic or not updating parent pointer causes corruption.

Validation bug: comparing only with parent, not all ancestors, allows invalid trees.


Condensed Notes

  • Search: go left if target < node, right if target > node.
  • Insert: attach at first null found on search path.
  • Delete: handle 0, 1, or 2 children separately.
  • Inorder: left, root, right → sorted values.
  • Validate: track min/max bounds from ancestors.
  • Successor: leftmost in right subtree.
  • Kth smallest: inorder + early stop at position k.

Additional Problems

Easy: Search in BST. Minimum in BST. Closest value to target.

Medium: Delete node from BST. Range sum of BST. Inorder successor.

Hard: Recover BST from two swapped nodes. All BSTs from preorder. Largest BST subtree.


Key Questions

  1. How do you search a BST?
  2. What is the inorder traversal of a BST?
  3. How do you delete a node with two children?
  4. Why is validation harder than just checking the parent?
  5. When is a BST preferred over a hash map?
  6. How do you find the kth smallest element?
  7. What is the successor of a node in BST?
  8. Why does insertion order affect BST performance?
  9. How do you build a balanced BST from a sorted array?
  10. What is Morris traversal and why use it?

Applied Project

Build a phone contact manager backed by a BST: store (name, phone) pairs sorted by name, support insert, delete, search, and range queries (names starting with a prefix).

15: Heap, Trie, Range Structures

Introduction and Context

This chapter covers three fundamental data structures that seem unrelated but share a core idea: trade structure for speed on specific operations.

Heaps keep the best element always accessible without full sorting. Tries make prefix-based lookup proportional to word length, not dictionary size. Range structures (segment trees, Fenwick trees) answer interval queries in logarithmic time with live updates.

The challenge is recognizing which structure solves which problem. Many learners memorize one solution per problem type; the real skill is seeing the constraint pattern and matching it to the right tool.

Core Intuition and Mechanics

Think of these structures as specialized indices:

  • Heap: a priority-ordered partial sort. Not fully sorted, but the root is always optimal.
  • Trie: a prefix tree. Shared prefixes compress storage; lookup depends on word length, not dictionary size.
  • Range structure: a preprocessed interval store. Interval queries and updates are logarithmic; the preprocessing and update strategy vary by constraint.

The recurring theme: each structure wastes some potential in exchange for fast guaranteed access to a specific pattern.

Core Concepts and Subtopics

Concept Cluster: Min and Max Heaps

Topics in this cluster:

  • 15.1 Min heap and max heap; Heapify and build-heap; PriorityQueue in Java
  • 15.2 Heap sort; Top K and streaming problems; Top K elements in practice
Definition

A min heap is a complete binary tree where every parent ≤ its children. A max heap is the opposite.

Array Representation

For 0-indexed array:

  • Left child of i: 2*i + 1
  • Right child of i: 2*i + 2
  • Parent of i: (i - 1) / 2
Sift-Up (Insert)
java
void siftUp(int[] heap, int index) {
    while (index > 0) {
        int parent = (index - 1) / 2;
        if (heap[parent] <= heap[index]) break;
        swap(heap, parent, index);
        index = parent;
    }
}
Sift-Down (Extract)
java
void siftDown(int[] heap, int index, int size) {
    while (2 * index + 1 < size) {
        int smaller = 2 * index + 1;
        if (2 * index + 2 < size && heap[2 * index + 2] < heap[smaller]) {
            smaller = 2 * index + 2;
        }
        if (heap[index] <= heap[smaller]) break;
        swap(heap, index, smaller);
        index = smaller;
    }
}
Build-Heap (Linear Time)
java
void buildHeap(int[] values) {
    int n = values.length;
    for (int i = n / 2 - 1; i >= 0; i--) {
        siftDown(values, i, n);
    }
}
PriorityQueue in Java
java
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
Top K Pattern
java
int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    for (int num : nums) {
        minHeap.offer(num);
        if (minHeap.size() > k) minHeap.poll();
    }
    return minHeap.peek();
}

Topics in this cluster:

  • 15.3 Trie structure and node design; Trie operations; Insert and search operations
  • 15.4 Prefix search; Prefix Tree Search Pattern; Delete and memory considerations; Dictionary and autocomplete problems
Definition

A trie stores strings by shared prefixes. Each node has a character and a set of children. A flag marks whether the path to a node completes a word.

Node Design
java
class TrieNode {
    TrieNode[] children = new TrieNode[26];  // for lowercase a-z
    boolean isWord;
}
Insert
java
void insert(String word) {
    TrieNode current = root;
    for (char c : word.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) {
            current.children[index] = new TrieNode();
        }
        current = current.children[index];
    }
    current.isWord = true;
}
Search
java
boolean search(String word) {
    TrieNode node = find(word);
    return node != null && node.isWord;
}

TrieNode find(String prefix) {
    TrieNode current = root;
    for (char c : prefix.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) return null;
        current = current.children[index];
    }
    return current;
}
java
List<String> startsWith(String prefix) {
    List<String> result = new ArrayList<>();
    TrieNode node = find(prefix);
    if (node != null) dfs(node, new StringBuilder(prefix), result);
    return result;
}

void dfs(TrieNode node, StringBuilder path, List<String> result) {
    if (node.isWord) result.add(path.toString());
    for (int i = 0; i < 26; i++) {
        if (node.children[i] != null) {
            path.append((char)('a' + i));
            dfs(node.children[i], path, result);
            path.deleteCharAt(path.length() - 1);
        }
    }
}

Concept Cluster: Range Query Structures

Topics in this cluster:

  • 15.5 Why range-query structures matter; Range Query Pattern; Segment tree build and query
  • 15.6 Point updates and range updates; Lazy propagation; Fenwick tree basics; Point updates, range updates, and immutable queries
  • 15.7 Segment tree vs binary indexed tree; Sparse table; Choosing the right query structure by constraints; Choosing the right query structure from the constraints
When Range Queries Matter

If you have 10^5 queries and 10^5 elements, O(n) per query fails. A segment tree answers each query in O(log n).

Segment Tree Build
java
class SegmentTree {
    long[] tree;
    int n;

    SegmentTree(int[] values) {
        n = values.length;
        tree = new long[4 * n];
        build(0, 0, n - 1, values);
    }

    void build(int node, int left, int right, int[] values) {
        if (left == right) {
            tree[node] = values[left];
        } else {
            int mid = (left + right) / 2;
            build(2 * node + 1, left, mid, values);
            build(2 * node + 2, mid + 1, right, values);
            tree[node] = tree[2 * node + 1] + tree[2 * node + 2];
        }
    }

    long query(int left, int right) {
        return query(0, 0, n - 1, left, right);
    }

    long query(int node, int l, int r, int left, int right) {
        if (r < left || l > right) return 0;
        if (left <= l && r <= right) return tree[node];
        int mid = (l + r) / 2;
        return query(2 * node + 1, l, mid, left, right) + 
               query(2 * node + 2, mid + 1, r, left, right);
    }
}
Fenwick Tree (Binary Indexed Tree)

Fenwick trees are compact for sum-style queries and point updates. Use segment trees for range updates or non-additive queries.

Choosing the Right Structure
  • Immutable array, sum queries: prefix sums O(1).
  • Point updates, sum queries: Fenwick tree O(log n).
  • Range updates, arbitrary merge: segment tree with lazy propagation O(log n).
  • Immutable array, min/max queries: sparse table O(1).

Worked Examples

Worked Example 1: Top K Elements

java
int[] topK(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    for (int num : nums) {
        minHeap.offer(num);
        if (minHeap.size() > k) minHeap.poll();
    }
    int[] result = new int[k];
    for (int i = k - 1; i >= 0; i--) {
        result[i] = minHeap.poll();
    }
    return result;
}

Complexity: O(n log k). Space: O(k). Keep a min-heap of size k; the heap holds the k largest.

Worked Example 2: Autocomplete with Trie

java
void insert(String word) {
    TrieNode current = root;
    for (char c : word.toCharArray()) {
        if (current.children[c - 'a'] == null) {
            current.children[c - 'a'] = new TrieNode();
        }
        current = current.children[c - 'a'];
    }
    current.isWord = true;
}

List<String> autocomplete(String prefix) {
    TrieNode node = root;
    for (char c : prefix.toCharArray()) {
        if (node.children[c - 'a'] == null) return new ArrayList<>();
        node = node.children[c - 'a'];
    }
    return allWordsFrom(node, prefix);
}

Why it works: prefix lookup is O(prefix length), not dictionary size.

Worked Example 3: Range Sum Query with Updates

java
long query(int left, int right) {
    return queryRange(0, 0, n - 1, left, right);
}

void update(int index, int value) {
    updateNode(0, 0, n - 1, index, value);
}

Complexity: O(log n) per query and update. Each operation touches only log n nodes.


Solved Problems

Problem 1 (Easy): Kth largest element.

Problem 2 (Easy): Implement a Trie.

Problem 3 (Medium): Merge K sorted lists (use heap).

Problem 4 (Medium): Word search in Trie (prefix matching).

Problem 5 (Hard): Design a data structure supporting range updates and range sum queries.


Recognition Guide

Heap: top K, scheduling, streaming max/min.

Trie: prefix lookup, autocomplete, word search, spell check.

Range structures: interval queries, dynamic updates, aggregation over ranges.


Comparison Tables

Structure Search Insert Delete Prefix
Heap O(n) O(log n) O(log n) N/A
Trie O(m) O(m) O(m) O(m)
Segment Tree O(log n) O(log n) O(log n) N/A
Fenwick O(log n) sum O(log n) N/A N/A

(m = word length; n = array size)


Design and Decision Making

Heaps are first choice for priority and top-K problems. Tries are best for prefix-based string work. Segment trees handle complex interval operations; Fenwick trees are simpler for sums. Choose based on the constraint pattern, not the problem wording.


Practical Applications

  • Heaps: task scheduling, event priority, median-finding, Dijkstra's algorithm.
  • Tries: search engines, IP routing, spell checkers, autocomplete systems.
  • Range structures: SQL range aggregates, monitoring dashboards, version control systems.

Failure Modes and Trade-offs

Heap overflow: unbounded growth in streaming. Set a fixed size for top-K problems.

Trie memory: large alphabets waste space. Use maps instead of arrays for sparse alphabets.

Range tree complexity: lazy propagation is error-prone. Start with simpler structures if constraints allow.


Condensed Notes

  • Heap: parent ≤ children (min heap); O(log n) insert/remove.
  • Trie: character at each node; isWord flag at path end.
  • Segment tree: interval merging; O(log n) query and update.
  • Top K: keep min-heap of size k; optimal is O(n log k).
  • Prefix search: find node, then DFS all children.
  • Range query: choose structure by: immutable? point or range update? operation type?

Additional Problems

Easy: Last K elements. Design a Trie. Kth smallest in BST (reuse from Ch 14).

Medium: Find median from data stream. Search suggestions system. Range sum with point update.

Hard: Merge K sorted lists. Maximum XOR of two numbers in array. Range assignment with lazy propagation.


Key Questions

  1. How does a min-heap maintain its invariant?
  2. Why is build-heap O(n) and not O(n log n)?
  3. How do you find the kth largest element efficiently?
  4. What is a Trie and when is it better than a hash set?
  5. How does prefix search work in a Trie?
  6. What are the differences between segment trees and Fenwick trees?
  7. When should you use lazy propagation?
  8. How do you validate a segment tree?
  9. What is the space-time trade-off in range queries?
  10. How do you handle range updates and range queries together?

Applied Project

Build a real-time dashboard: compute top-10 products, handle live sales, prefix-search by product name, and show range sum queries (total sales in a time window) using a combination of heap, trie, and segment tree.

16: Structural Design Patterns II

Introduction and Context

This chapter covers the remaining structural patterns that control how objects are composed and accessed: Flyweight (sharing state across many similar objects), advanced wrapper strategies, refactoring paths for legacy code, and testing structural designs.

The core challenge: structural patterns can make code cleaner or more convoluted. The wrong pattern choice trades one problem for another. Flyweight saves memory but complicates equality. Proxy adds indirection, which can hurt clarity. The skill is matching the pattern to the real constraint and knowing when simpler is better.

This chapter also emphasizes a pragmatic lens: when do you actually need these patterns? When should you avoid them?

Core Intuition and Mechanics

Structural patterns are about composition and delegation:

  • Flyweight: share immutable state across many objects to save memory.
  • Wrapper composition: use Decorator, Adapter, Proxy, and Facade as building blocks.
  • Refactoring: incrementally introduce structure to legacy code without breaking it.
  • Testing: design for testability by controlling dependencies and seams.

The key tension: every pattern adds indirection and complexity. The payoff must be clear: is the benefit worth the cost?

Core Concepts and Subtopics

Concept Cluster: Flyweight Pattern and Memory Optimization

Topics in this cluster:

  • 16.1 Flyweight Pattern: Shared state; Intrinsic state; Extrinsic state; Memory optimization
  • 16.2 Factory support for flyweights; When object sharing hurts clarity or thread safety
Definition

Intrinsic state is immutable and shared (e.g., character glyphs in a text editor). Extrinsic state is mutable and unique per instance (e.g., position, color). Flyweight extracts intrinsic state into a shared pool, creating new instances only for unique intrinsic values.

Classic Example: Text Editor Character
java
interface Glyph {
    void draw(Graphics g, int x, int y);
}

class Character implements Glyph {
    private final char c;  // intrinsic
    Character(char c) { this.c = c; }
    public void draw(Graphics g, int x, int y) {
        // draw using c, x, y
    }
}

class CharacterFactory {
    private final Map<Character, Glyph> pool = new HashMap<>();
    Glyph getCharacter(char c) {
        return pool.computeIfAbsent(c, Character::new);
    }
}
Why Flyweight Matters

If a document has 1 million characters but only 26 distinct letters (plus punctuation), storing each character separately wastes memory. Sharing the intrinsic state (the character type) across all instances saves orders of magnitude.

When NOT to Use Flyweight

If there are few instances (< 1000), memory savings are negligible. If equality or hashing on extrinsic state is needed, flyweight complicates comparison. If thread safety is critical, sharing state becomes a synchronization headache.

Common Mistakes
  • Storing mutable state in the flyweight; it becomes shared and breaks isolation.
  • Treating extrinsic state as intrinsic; the shared pool is no longer correct.
  • Over-engineering for memory savings that never materialize.

Concept Cluster: Wrapper Composition Strategies

Topics in this cluster:

  • 16.3 Wrapper composition strategies; Pattern comparisons across Adapter, Facade, Proxy, Bridge, Composite, Decorator, and Flyweight
Definition

Adapters, facades, proxies, decorators, and composites all wrap or delegate to other objects. The intent differs:

  • Adapter: convert interface A to interface B.
  • Facade: provide simplified access to a subsystem.
  • Proxy: control access (lazy loading, caching, synchronization).
  • Bridge: separate abstraction from implementation.
  • Composite: treat single and group objects uniformly.
  • Decorator: add responsibilities dynamically.
When Each Fits
java
// Adapter: incompatible interfaces
class LegacyPrinter { void print(String text) {} }
class ModernPrintAdapter implements ModernPrinter {
    private LegacyPrinter legacy = new LegacyPrinter();
    public void printDocument(Document doc) {
        legacy.print(doc.getText());
    }
}

// Decorator: add responsibility
InputStream base = new FileInputStream("file.txt");
InputStream compressed = new GZIPInputStream(base);
InputStream encrypted = new EncryptionInputStream(compressed);

// Proxy: control access
class ExpensiveResourceProxy implements ExpensiveResource {
    private ExpensiveResource real = null;
    public void use() {
        if (real == null) real = new RealExpensiveResource();
        real.use();
    }
}
Composition vs. Inheritance

Prefer composition. It avoids the fragility of deep inheritance hierarchies and allows runtime flexibility.


Concept Cluster: Refactoring and Legacy Structure

Topics in this cluster:

  • 16.4 Refactoring legacy structures; Refactoring paths and extension points
  • 16.5 Memory/performance trade-offs; Scalability impact; Indirection cost
Definition

Refactoring legacy code to introduce patterns incrementally without breaking existing behavior. Key techniques: extract abstraction, introduce interface, apply strategy or decorator.

Refactoring Strategy
  1. Write tests for existing behavior.
  2. Introduce an interface without changing the implementation.
  3. Add a new implementation alongside the old.
  4. Use dependency injection to allow switching.
  5. Migrate call sites gradually.
Example: Adding Caching
java
// Old
public class DataService {
    public Data fetch(String id) {
        return expensiveQuery(id);
    }
}

// Refactored: interface first
public interface DataFetcher {
    Data fetch(String id);
}

public class DataService implements DataFetcher {
    public Data fetch(String id) {
        return expensiveQuery(id);
    }
}

// New: cache decorator
public class CachingDataFetcher implements DataFetcher {
    private final DataFetcher delegate;
    private final Map<String, Data> cache = new HashMap<>();
    
    public CachingDataFetcher(DataFetcher delegate) {
        this.delegate = delegate;
    }
    
    public Data fetch(String id) {
        return cache.computeIfAbsent(id, k -> delegate.fetch(k));
    }
}
Trade-offs
  • Memory vs. speed: caching saves computation but uses memory.
  • Abstraction vs. clarity: patterns enable extension but add layers to read.
  • Batch refactoring vs. incremental: incremental is safer; batch is faster.

Concept Cluster: Testing Structural Designs

Topics in this cluster:

  • 16.6 Testing structural designs; Unit testing patterns and mocking collaborators; Integration testing and testable design
Definition

Structural patterns enable testability by creating seams: points where you can inject dependencies or mocks instead of real implementations.

Testable Design with Injection
java
public class UserRepository {
    private final Database db;
    
    // Dependency injection
    public UserRepository(Database db) {
        this.db = db;
    }
    
    public User findById(String id) {
        return db.query("SELECT * FROM users WHERE id = ?", id);
    }
}

// In tests
class FakeDatabase implements Database {
    private final Map<String, User> store = new HashMap<>();
    public User query(String sql, String id) {
        return store.get(id);
    }
}

@Test
public void testFindById() {
    Database fake = new FakeDatabase();
    ((FakeDatabase) fake).store.put("1", new User("1", "Alice"));
    UserRepository repo = new UserRepository(fake);
    assertEquals("Alice", repo.findById("1").getName());
}
Mocking Frameworks
java
@Test
public void testWithMocks() {
    Database mockDb = mock(Database.class);
    when(mockDb.query(anyString(), eq("1"))).thenReturn(new User("1", "Alice"));
    UserRepository repo = new UserRepository(mockDb);
    assertEquals("Alice", repo.findById("1").getName());
}
Integration Testing

Test multiple layers together; ensure interfaces and contracts hold across boundaries.

Anti-Pattern: Over-Mocking

Too many mocks means the test doesn't exercise real behavior. Keep mocks for external dependencies (databases, APIs); use real implementations for internal logic.


Worked Examples

Worked Example 1: Flyweight in a Game

java
class Tile {
    final int textureId;  // intrinsic: shared
    int x, y;  // extrinsic: unique per instance
    
    Tile(int textureId) { this.textureId = textureId; }
}

class TileFactory {
    Map<Integer, Tile> tiles = new HashMap<>();
    Tile getTile(int textureId, int x, int y) {
        Tile t = tiles.computeIfAbsent(textureId, Tile::new);
        t.x = x; t.y = y;
        return t;
    }
}

Memory savings: 1000x1000 grid with 10 tile types uses 10 Tile objects, not 1 million.

Worked Example 2: Refactoring to Add Caching

java
interface ExpensiveOperation {
    int compute(int x);
}

class CachingDecorator implements ExpensiveOperation {
    final ExpensiveOperation delegate;
    final Map<Integer, Integer> cache = new HashMap<>();
    
    CachingDecorator(ExpensiveOperation delegate) {
        this.delegate = delegate;
    }
    
    public int compute(int x) {
        return cache.computeIfAbsent(x, delegate::compute);
    }
}

Why it works: new responsibility (caching) is independent of the original logic.

Worked Example 3: Mock-Based Unit Test

java
@Test
public void testPaymentProcessor() {
    PaymentGateway mock = mock(PaymentGateway.class);
    when(mock.charge(100.0)).thenReturn(true);
    
    PaymentProcessor processor = new PaymentProcessor(mock);
    assertTrue(processor.processPayment(100.0));
    
    verify(mock).charge(100.0);
}

Why isolation matters: test logic without depending on a real payment service.


Solved Problems

Problem 1 (Easy): Implement Flyweight for a character set.

Problem 2 (Easy): Refactor a legacy class to use dependency injection.

Problem 3 (Medium): Add caching via Decorator to an expensive computation.

Problem 4 (Medium): Write testable code for a file-processing service.

Problem 5 (Hard): Design a system that supports multiple logger implementations via composition (Adapter, Decorator, Proxy).


Recognition Guide

Use Flyweight when instances outnumber distinct intrinsic states and memory is constrained. Use Decorator to add independent responsibilities. Use Proxy for access control or lazy initialization. Refactor incrementally, introducing patterns only where the cost-benefit is clear.

Avoid structural patterns when the codebase is already complex. Do not over-engineer for future flexibility that may never be needed.


Comparison Tables

Pattern Purpose Complexity When to Use
Adapter Interface conversion Low Integrate incompatible interfaces
Facade Simplified access Low Hide subsystem complexity
Proxy Access control Medium Lazy loading, caching, sync
Decorator Add responsibility Medium Dynamic behavior at runtime
Bridge Separate abstraction Medium Multiple implementations matter
Composite Uniform treatment Medium Tree structures
Flyweight Memory optimization High Many similar objects

Design and Decision Making

Start simple. Use structural patterns only when you have a real constraint (memory, performance, testability). Introduce them incrementally via refactoring. Measure before and after. Design for testability from the start: inject dependencies, avoid static factories, use interfaces.


Practical Applications

  • Web frameworks: decorators for middleware chains (logging, auth, compression).
  • Graphics systems: flyweight for textures, glyphs, materials.
  • Database layers: proxy for connection pooling, caching layers via facades.
  • Legacy system integration: adapters to bridge old and new APIs.

Failure Modes and Trade-offs

Flyweight gone wrong: shared state becomes mutable; isolation breaks.

Over-composition: too many wrapper layers; each adds latency and debugging complexity.

Testability illusion: perfect mocks but untested real code paths.

Premature refactoring: introduce patterns before you know the actual constraints.


Condensed Notes

  • Flyweight: share intrinsic, vary extrinsic.
  • Adapter: convert interface A to B.
  • Facade: simplify subsystem access.
  • Proxy: intercept; lazy load, cache, sync.
  • Decorator: add responsibility independently.
  • Refactor incrementally with tests.
  • Inject dependencies; mock at boundaries.
  • Measure trade-offs; not all patterns fit.

Additional Problems

Easy: Cache layer for API calls. Logging decorator. Object pool pattern.

Medium: Multi-level caching (memory, disk). Composite file-system structure. Proxy with lazy initialization.

Hard: Thread-safe flyweight factory. Refactor monolith to plugins. Full testing strategy for complex system.


Key Questions

  1. What is intrinsic vs. extrinsic state in Flyweight?
  2. When is Flyweight worth the complexity?
  3. How do Proxy and Decorator differ in intent?
  4. What refactoring steps introduce a pattern safely?
  5. How do you test code with structural patterns?
  6. When should you NOT use a pattern?
  7. What is the memory overhead of too many wrapper layers?
  8. How do you handle thread safety in shared Flyweight objects?
  9. What dependencies should you mock in unit tests?
  10. How do you measure if a refactoring improved the system?

Applied Project

Build a document rendering system with support for multiple formats (PDF, HTML, Markdown). Use Adapter for format conversion, Decorator for styling and encryption, Flyweight for shared font objects, Proxy for lazy loading of images, and injectable components for testability. Write comprehensive unit and integration tests.

17: Graph Foundations

Introduction and Context

Graphs appear everywhere: social networks, maps, circuit designs, dependency chains, and game states. Yet many learners treat graphs as abstract math rather than practical models. The real power comes from translating a real problem into nodes and edges correctly.

The core challenge is choosing what becomes a node and what becomes an edge. Should we model a person or a friendship? A city or a road? Without clarity, even the simplest algorithm becomes confusing.

A wrong representation forces bad algorithms. A clean representation often makes the solution obvious. This chapter teaches you to see the graph hiding inside the problem statement.

Core Intuition and Mechanics

Think of a graph as a relationship map. Nodes are entities. Edges are relationships. The graph's shape determines what questions are easy to answer.

  • Directed vs. undirected: Does a relationship go both ways?
  • Weighted vs. unweighted: Does each relationship carry a cost, distance, or capacity?
  • Sparse vs. dense: Many edges relative to nodes suggest adjacency lists; few edges fit matrices.
  • Implicit vs. explicit: Some graphs are given as edge lists; others are generated on-the-fly from state rules.

The mental model: before running any algorithm, ask what the nodes represent and what each edge means. One wrong answer breaks everything downstream.

Core Concepts and Subtopics

Concept Cluster: Graph Representation

Topics in this cluster:

  • 17.1 Graph terminology; Adjacency list; Adjacency matrix
  • 17.2 Directed and undirected graphs; Weighted graphs
Definition

A graph is a set of nodes (vertices) and edges connecting them. Terminology:

  • Vertex: an entity in the graph.
  • Edge: a connection between two vertices.
  • Degree: number of edges touching a vertex (in undirected graphs).
  • Indegree / Outdegree: incoming and outgoing edges (in directed graphs).
  • Connected component: a maximal set of mutually reachable vertices.
Adjacency List vs. Adjacency Matrix
java
// Adjacency list: space O(V + E), good for sparse graphs
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
    adj.add(new ArrayList<>());
}
adj.get(0).add(1); // edge 0 -> 1

// Adjacency matrix: space O(V²), good for dense graphs
boolean[][] matrix = new boolean[n][n];
matrix[0][1] = true; // edge 0 -> 1

// Weighted adjacency list
class Edge {
    int to, weight;
    Edge(int to, int weight) { this.to = to; this.weight = weight; }
}
List<List<Edge>> adj = new ArrayList<>();
adj.get(0).add(new Edge(1, 5)); // edge 0 -> 1 with weight 5
Directed vs. Undirected

In undirected graphs, add edges in both directions. In directed graphs, add only the specified direction.

java
void addUndirectedEdge(List<List<Integer>> adj, int u, int v) {
    adj.get(u).add(v);
    adj.get(v).add(u);
}
Common Mistakes
  • Treating directed edges as undirected.
  • Using adjacency matrix when the graph is sparse (memory waste).
  • Forgetting isolated nodes with no edges.

Concept Cluster: Graph Modeling and Traversal Templates

Topics in this cluster:

  • 17.3 Modeling real problems as graphs
  • 17.4 Matrix Traversal Pattern; Boundary checks, visited state, and direction vectors
  • 17.5 Visual walkthroughs for grid problems
  • 17.6 Java traversal templates; Traversal templates
Definition

Modeling is deciding what becomes a node and what becomes an edge. Traversal is visiting all reachable nodes systematically.

Modeling Checklist
  • What entities become nodes? (people, cities, cells, states, tasks)
  • What relationships become edges? (friendships, roads, legal moves, prerequisites)
  • Is the graph directed or undirected?
  • Are edges weighted?
Direction Vectors for Grids

Grids are implicit graphs where neighbors are computed, not stored.

java
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // four directions
for (int[] d : dirs) {
    int nr = row + d[0], nc = col + d[1];
    if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
        // process neighbor (nr, nc)
    }
}
Visited State
java
boolean[][] visited = new boolean[rows][cols];
void dfs(int r, int c, int[][] grid, boolean[][] visited) {
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;
    if (visited[r][c]) return;
    visited[r][c] = true;
    for (int[] d : dirs) {
        dfs(r + d[0], c + d[1], grid, visited);
    }
}
Common Mistakes
  • Swapping row and column indices.
  • Marking visited too late, causing duplicate processing.
  • Forgetting boundary checks.

Worked Examples

Worked Example 1: Build an Adjacency List from Edges

Problem: Given n nodes and a list of directed edges, build an adjacency list.

java
List<List<Integer>> buildGraph(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        adj.add(new ArrayList<>());
    }
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
    }
    return adj;
}

Why it works: Each node gets an empty list initially. For each edge (u, v), append v to u's neighbor list.


Worked Example 2: Flood Fill on a Grid

Problem: Given a grid of colors and a starting cell, change all connected cells of the same color to a new color.

java
void floodFill(int[][] grid, int sr, int sc, int newColor) {
    if (grid[sr][sc] == newColor) return;
    int origColor = grid[sr][sc];
    dfs(grid, sr, sc, origColor, newColor);
}

void dfs(int[][] grid, int r, int c, int orig, int newColor) {
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;
    if (grid[r][c] != orig) return;
    grid[r][c] = newColor;
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (int[] d : dirs) {
        dfs(grid, r + d[0], c + d[1], orig, newColor);
    }
}

Worked Example 3: Count Connected Components

Problem: Given an undirected graph, count the number of connected components.

java
int countComponents(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
        adj.get(e[1]).add(e[0]);
    }
    
    boolean[] visited = new boolean[n];
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            dfs(i, adj, visited);
            count++;
        }
    }
    return count;
}

void dfs(int u, List<List<Integer>> adj, boolean[] visited) {
    visited[u] = true;
    for (int v : adj.get(u)) {
        if (!visited[v]) dfs(v, adj, visited);
    }
}

Solved Problems

Problem 1: Number of Islands (Easy)

Statement: Count islands in a grid of '1' (land) and '0' (water).

Java Solution:

java
int numIslands(char[][] grid) {
    int count = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == '1') {
                dfs(grid, i, j);
                count++;
            }
        }
    }
    return count;
}

void dfs(char[][] grid, int r, int c) {
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return;
    if (grid[r][c] != '1') return;
    grid[r][c] = '0';
    dfs(grid, r + 1, c);
    dfs(grid, r - 1, c);
    dfs(grid, r, c + 1);
    dfs(grid, r, c - 1);
}

Time/Space: O(rows × cols) / O(rows × cols) recursion depth in worst case.


Problem 2: Max Area of Island (Easy)

Statement: Find the largest connected island area.

Java Solution:

java
int maxAreaOfIsland(int[][] grid) {
    int maxArea = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 1) {
                maxArea = Math.max(maxArea, dfs(grid, i, j));
            }
        }
    }
    return maxArea;
}

int dfs(int[][] grid, int r, int c) {
    if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return 0;
    if (grid[r][c] == 0) return 0;
    grid[r][c] = 0;
    return 1 + dfs(grid, r + 1, c) + dfs(grid, r - 1, c)
        + dfs(grid, r, c + 1) + dfs(grid, r, c - 1);
}

Problem 3: Adjacency List from Edges (Medium)

Statement: Build an adjacency list from n nodes and edges, then verify it.

Java Solution:

java
List<List<Integer>> buildGraph(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        if (e[0] != e[1]) { // no self-loops
            adj.get(e[0]).add(e[1]);
        }
    }
    return adj;
}

Problem 4: Check If Graph Is Bipartite (Medium)

Statement: A bipartite graph can be 2-colored such that adjacent nodes have different colors.

Java Solution:

java
boolean isBipartite(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
        adj.get(e[1]).add(e[0]);
    }
    
    int[] color = new int[n];
    for (int i = 0; i < n; i++) {
        if (color[i] == 0 && !isBipartiteDfs(i, 1, color, adj)) {
            return false;
        }
    }
    return true;
}

boolean isBipartiteDfs(int u, int c, int[] color, List<List<Integer>> adj) {
    color[u] = c;
    for (int v : adj.get(u)) {
        if (color[v] == 0) {
            if (!isBipartiteDfs(v, 3 - c, color, adj)) return false;
        } else if (color[v] == c) {
            return false;
        }
    }
    return true;
}

Problem 5: Shortest Path in Grid (Hard)

Statement: Find shortest path from (0,0) to (rows-1, cols-1) in a grid, moving through non-zero cells.

Java Solution:

java
int shortestPath(int[][] grid) {
    int rows = grid.length, cols = grid[0].length;
    if (grid[0][0] == 0 || grid[rows - 1][cols - 1] == 0) return -1;
    
    Queue<int[]> q = new LinkedList<>();
    q.offer(new int[]{0, 0, 1});
    boolean[][] visited = new boolean[rows][cols];
    visited[0][0] = true;
    
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        int r = curr[0], c = curr[1], dist = curr[2];
        
        if (r == rows - 1 && c == cols - 1) return dist;
        
        for (int[] d : dirs) {
            int nr = r + d[0], nc = c + d[1];
            if (nr >= 0 && nr < rows && nc >= 0 && nc < cols 
                && !visited[nr][nc] && grid[nr][nc] != 0) {
                visited[nr][nc] = true;
                q.offer(new int[]{nr, nc, dist + 1});
            }
        }
    }
    return -1;
}

Recognition Guide

When to use this chapter's concepts:

  • You see nodes and edges (explicit or implicit in a grid).
  • You need to build a graph representation before running an algorithm.
  • You're modeling state transitions, relationships, or spatial layouts.
  • Adjacency matters more than sequential order.

When NOT to use:

  • The problem is only about linear sequences (use arrays or linked lists).
  • There are no cycles or multiple paths (it might be a tree).

Comparison Tables

Aspect Adjacency List Adjacency Matrix
Space O(V + E) O(V²)
Find edge (u,v) O(degree) O(1)
Best for Sparse graphs Dense graphs
Building O(V + E) O(V²)

Design and Decision Making

Choosing representation:

  • If E is much smaller than V², use adjacency list.
  • If you need O(1) edge lookups, use adjacency matrix.
  • For grids, use implicit neighbors and direction vectors.

Clean code:

  • Name your nodes and edges clearly.
  • Use enums for graph types (DIRECTED, UNDIRECTED, WEIGHTED).
  • Separate graph construction from traversal logic.

Practical Applications

  • Social networks: Users are nodes; friendships are edges.
  • Maps: Cities are nodes; roads are weighted edges.
  • Web crawling: Pages are nodes; hyperlinks are edges.
  • Game boards: Cells are nodes; legal moves are edges.

Failure Modes and Trade-offs

  • Self-loops and multi-edges: Handle them explicitly or reject them.
  • Very large graphs: Adjacency list saves memory but slower edge checks.
  • Sparse vs. dense misconception: Measure E:V² ratio; don't guess.

Condensed Notes

  • Graph = nodes + edges.
  • Adjacency list: best for sparse graphs.
  • Adjacency matrix: best for dense graphs and edge checks.
  • Direction vectors for grids: avoid repeated neighbor code.
  • Always mark visited to prevent cycles and redundant work.

Additional Problems

Easy: Number of Islands (variant with water edges), Path in Grid, Valid Path, Clone Graph (adjacency list only), Reachable Nodes.

Medium: Longest Increasing Path in Matrix, Walls and Gates, Number of Enclaves, Surrounded Regions, Minimum Height Trees.

Hard: Shortest Path with Obstacles, Minimum Cost to Make at Least One Valid Path, Checking Existence of Edge Length Limited Paths, Reconstruct Itinerary, Redundant Connection.

Key Questions

  1. What is the difference between an adjacency list and adjacency matrix? Lists use O(V + E) space and suit sparse graphs; matrices use O(V²) and suit dense graphs.

  2. How do you handle an undirected edge in code? Add it in both directions: adj[u].add(v) and adj[v].add(u).

  3. Why mark visited before recursing instead of after? Early marking prevents duplicate work and infinite loops in cyclic graphs.

  4. What is a direction vector? An array of (row, col) offsets for neighbor generation in grids, reducing code duplication.

  5. When would you use an implicit graph? When neighbors can be computed (e.g., grids, state-space problems) rather than stored.

  6. How do isolated nodes appear in an adjacency list? As entries with empty neighbor lists; they matter for component counting.

  7. What is a weighted edge, and how is it stored? A relationship with a numeric value (distance, cost). Store it in an Edge class or parallel weight array.

  8. Why is space important in graph choice? A V² matrix on a 10,000-node graph wastes 100 MB; lists use only O(E).

  9. What does directed mean in a graph context? Edges go one way only (u → v); undirected edges go both ways.

  10. How do you detect if a graph has isolated nodes? Check for nodes in the node range that never appear in any edge.

Applied Project

Build a social-network analyzer that:

  • Loads users and friendships from a file.
  • Builds an adjacency list.
  • Counts connected components (groups of mutually connected users).
  • Finds the largest component.
  • Lists all users in each component.

Suggested structure: SocialNetwork class with addFriendship, getConnectedComponents, and printComponents methods. Test on a small sample of 5–10 users.


18: Graph Traversal & Connectivity

Introduction and Context

Once a graph is built, the next step is movement. How do you visit every reachable node? How many separate groups exist? Can you get from A to B? Is there a cycle?

These questions are answered by traversal algorithms—BFS and DFS—and connectivity patterns like union-find. Choosing the right tool prevents redundant work and clarifies the problem structure.

The core challenge is understanding when to use each tool. BFS gives shortest paths in unweighted graphs. DFS reveals structure and cycles. Union-find answers connectivity questions without traversal.

Core Intuition and Mechanics

Think of exploration:

  • BFS: explore layer by layer, like expanding ripples in water. First arrival means shortest distance.
  • DFS: explore one path deeply before backtracking. Reveals reachability and structural properties.
  • Union-find: track merged groups without traversal. Answers "are these two nodes in the same group?"
  • Bipartite check: color nodes with two colors; if colors conflict, the graph is not bipartite.

The mental model: traversal gives you complete information about reachability and structure. Union-find gives you fast incremental connectivity.

Core Concepts and Subtopics

Concept Cluster: BFS and DFS Traversal

Topics in this cluster:

  • 18.1 Breadth-first search; BFS; Graph BFS Pattern
  • 18.2 Depth-first search; DFS; Graph DFS Pattern
Definition

BFS explores nodes level by level using a queue. DFS explores nodes deeply using recursion or a stack.

BFS Template
java
void bfs(int start, List<List<Integer>> adj, boolean[] visited) {
    Queue<Integer> q = new LinkedList<>();
    q.offer(start);
    visited[start] = true;
    while (!q.isEmpty()) {
        int u = q.poll();
        // process u
        for (int v : adj.get(u)) {
            if (!visited[v]) {
                visited[v] = true;
                q.offer(v);
            }
        }
    }
}
DFS Template
java
void dfs(int u, List<List<Integer>> adj, boolean[] visited) {
    visited[u] = true;
    // process u
    for (int v : adj.get(u)) {
        if (!visited[v]) {
            dfs(v, adj, visited);
        }
    }
}
Why BFS for Shortest Unweighted Paths

In BFS, the first time you reach a node is the shortest path from the start. This is because you explore by distance.

Common Mistakes
  • Marking visited too late in BFS (duplicate processing).
  • Assuming DFS gives shortest paths (it doesn't in general).
  • Forgetting to process all components in disconnected graphs.

Concept Cluster: Components, Cycles, and Bipartite Checking

Topics in this cluster:

  • 18.3 Connected components; Cycle detection; Bipartite graph check
  • 18.4 Flood Fill Pattern; Multi-Source BFS Pattern; Layered expansion versus DFS-style exploration
Connected Components

In an undirected graph, a component is a maximal set of mutually reachable nodes.

java
int countComponents(int n, List<List<Integer>> adj) {
    boolean[] visited = new boolean[n];
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            dfs(i, adj, visited);
            count++;
        }
    }
    return count;
}
Cycle Detection in Undirected Graphs

A back edge (an edge to an already-visited non-parent node) indicates a cycle.

java
boolean hasCycle(int n, List<List<Integer>> adj) {
    boolean[] visited = new boolean[n];
    for (int i = 0; i < n; i++) {
        if (!visited[i] && dfsCycle(i, -1, adj, visited)) {
            return true;
        }
    }
    return false;
}

boolean dfsCycle(int u, int parent, List<List<Integer>> adj, boolean[] visited) {
    visited[u] = true;
    for (int v : adj.get(u)) {
        if (!visited[v]) {
            if (dfsCycle(v, u, adj, visited)) return true;
        } else if (v != parent) {
            return true; // back edge found
        }
    }
    return false;
}
Bipartite Check

Color nodes with 0 or 1. If a neighbor has the same color, the graph is not bipartite.

java
boolean isBipartite(int n, List<List<Integer>> adj) {
    int[] color = new int[n];
    for (int i = 0; i < n; i++) {
        if (color[i] == 0 && !dfsBipartite(i, 1, adj, color)) {
            return false;
        }
    }
    return true;
}

boolean dfsBipartite(int u, int c, List<List<Integer>> adj, int[] color) {
    color[u] = c;
    for (int v : adj.get(u)) {
        if (color[v] == 0) {
            if (!dfsBipartite(v, 3 - c, adj, color)) return false;
        } else if (color[v] == c) {
            return false;
        }
    }
    return true;
}
Multi-Source BFS

Start BFS from multiple source nodes simultaneously. First arrival is shortest distance from any source.

java
int nearestDistance(int[][] grid) {
    Queue<int[]> q = new LinkedList<>();
    boolean[][] visited = new boolean[grid.length][grid[0].length];
    
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 1) {
                q.offer(new int[]{i, j, 0});
                visited[i][j] = true;
            }
        }
    }
    
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        for (int[] d : dirs) {
            int nr = curr[0] + d[0], nc = curr[1] + d[1];
            if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length 
                && !visited[nr][nc]) {
                visited[nr][nc] = true;
                q.offer(new int[]{nr, nc, curr[2] + 1});
            }
        }
    }
    // return minimum distance found
    return -1; // or appropriate value
}

Concept Cluster: Union-Find for Connectivity

Topics in this cluster:

  • 18.5 Union Find Pattern; Connected components, dependencies, and cycle modeling
  • 18.6 Strongly Connected Components Pattern; Modeling components, dependencies, and cycles
Definition

Union-Find (Disjoint Set Union) maintains a partition of nodes into groups. Operations:

  • find(x): return the representative of x's group.
  • union(x, y): merge the groups containing x and y.
Basic Implementation
java
class DSU {
    int[] parent, rank;
    
    DSU(int n) {
        parent = new int[n];
        rank = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
    }
    
    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]); // path compression
        }
        return parent[x];
    }
    
    boolean union(int x, int y) {
        int px = find(x), py = find(y);
        if (px == py) return false; // already connected
        
        if (rank[px] < rank[py]) {
            parent[px] = py;
        } else if (rank[px] > rank[py]) {
            parent[py] = px;
        } else {
            parent[py] = px;
            rank[px]++;
        }
        return true;
    }
}
When to Use Union-Find
  • Detecting cycles in undirected graphs.
  • Counting connected components as edges are added.
  • Answering "are two nodes in the same group?" repeatedly.
Strongly Connected Components (Directed Graphs)

A strongly connected component (SCC) is a maximal set of nodes where every node reaches every other. Use Kosaraju's or Tarjan's algorithm.

java
int countSCC(int n, List<List<Integer>> adj) {
    boolean[] visited = new boolean[n];
    Deque<Integer> order = new ArrayDeque<>();
    for (int node = 0; node < n; node++) {
        if (!visited[node]) {
            dfsOrder(node, adj, visited, order);
        }
    }

    List<List<Integer>> reverse = new ArrayList<>();
    for (int node = 0; node < n; node++) {
        reverse.add(new ArrayList<>());
    }
    for (int node = 0; node < n; node++) {
        for (int next : adj.get(node)) {
            reverse.get(next).add(node);
        }
    }

    Arrays.fill(visited, false);
    int components = 0;
    while (!order.isEmpty()) {
        int node = order.pop();
        if (!visited[node]) {
            dfsMark(node, reverse, visited);
            components++;
        }
    }
    return components;
}

void dfsOrder(int node, List<List<Integer>> adj, boolean[] visited, Deque<Integer> order) {
    visited[node] = true;
    for (int next : adj.get(node)) {
        if (!visited[next]) {
            dfsOrder(next, adj, visited, order);
        }
    }
    order.push(node);
}

void dfsMark(int node, List<List<Integer>> reverse, boolean[] visited) {
    visited[node] = true;
    for (int next : reverse.get(node)) {
        if (!visited[next]) {
            dfsMark(next, reverse, visited);
        }
    }
}

Worked Examples

Worked Example 1: Shortest Path with BFS

Problem: Find shortest distance from node s to all nodes in an unweighted graph.

java
int[] shortestDist(int n, int[][] edges, int s) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
        adj.get(e[1]).add(e[0]);
    }
    
    int[] dist = new int[n];
    Arrays.fill(dist, -1);
    dist[s] = 0;
    
    Queue<Integer> q = new LinkedList<>();
    q.offer(s);
    while (!q.isEmpty()) {
        int u = q.poll();
        for (int v : adj.get(u)) {
            if (dist[v] == -1) {
                dist[v] = dist[u] + 1;
                q.offer(v);
            }
        }
    }
    return dist;
}

Worked Example 2: Detect Cycle with Union-Find

Problem: Determine if an undirected graph has a cycle.

java
boolean hasCycleDSU(int n, int[][] edges) {
    DSU dsu = new DSU(n);
    for (int[] e : edges) {
        if (!dsu.union(e[0], e[1])) {
            return true; // union failed, already connected
        }
    }
    return false;
}

Worked Example 3: Rotting Oranges (Multi-Source BFS)

Problem: Rotten oranges spread to adjacent fresh oranges. Return time to rot all, or -1 if impossible.

java
int orangesRotting(int[][] grid) {
    Queue<int[]> q = new LinkedList<>();
    int fresh = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == 2) q.offer(new int[]{i, j});
            else if (grid[i][j] == 1) fresh++;
        }
    }
    
    if (fresh == 0) return 0;
    int time = 0;
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    
    while (!q.isEmpty()) {
        int size = q.size();
        for (int i = 0; i < size; i++) {
            int[] curr = q.poll();
            for (int[] d : dirs) {
                int nr = curr[0] + d[0], nc = curr[1] + d[1];
                if (nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length 
                    && grid[nr][nc] == 1) {
                    grid[nr][nc] = 2;
                    fresh--;
                    q.offer(new int[]{nr, nc});
                }
            }
        }
        if (fresh > 0) time++;
    }
    return fresh == 0 ? time : -1;
}

Solved Problems

Problem 1: Valid Path (Easy)

Statement: Is there a path from source to destination in an undirected graph?

Java Solution:

java
boolean validPath(int n, int[][] edges, int source, int destination) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) {
        adj.get(e[0]).add(e[1]);
        adj.get(e[1]).add(e[0]);
    }
    
    boolean[] visited = new boolean[n];
    return dfs(source, destination, adj, visited);
}

boolean dfs(int u, int target, List<List<Integer>> adj, boolean[] visited) {
    if (u == target) return true;
    visited[u] = true;
    for (int v : adj.get(u)) {
        if (!visited[v] && dfs(v, target, adj, visited)) {
            return true;
        }
    }
    return false;
}

Problem 2: Number of Connected Components (Easy)

Statement: Count connected components using union-find.

Java Solution:

java
int countComponents(int n, int[][] edges) {
    DSU dsu = new DSU(n);
    for (int[] e : edges) {
        dsu.union(e[0], e[1]);
    }
    Set<Integer> roots = new HashSet<>();
    for (int i = 0; i < n; i++) {
        roots.add(dsu.find(i));
    }
    return roots.size();
}

Problem 3: Walls and Gates (Medium)

Statement: Fill each empty cell with distance to nearest gate (using multi-source BFS).

Java Solution:

java
void wallsAndGates(int[][] rooms) {
    Queue<int[]> q = new LinkedList<>();
    for (int i = 0; i < rooms.length; i++) {
        for (int j = 0; j < rooms[0].length; j++) {
            if (rooms[i][j] == 0) q.offer(new int[]{i, j});
        }
    }
    
    int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        for (int[] d : dirs) {
            int nr = curr[0] + d[0], nc = curr[1] + d[1];
            if (nr >= 0 && nr < rooms.length && nc >= 0 && nc < rooms[0].length 
                && rooms[nr][nc] == Integer.MAX_VALUE) {
                rooms[nr][nc] = rooms[curr[0]][curr[1]] + 1;
                q.offer(new int[]{nr, nc});
            }
        }
    }
}

Problem 4: Redundant Connection (Medium)

Statement: Find the edge that, if removed, makes the graph acyclic (using union-find).

Java Solution:

java
int[] findRedundantConnection(int[][] edges) {
    DSU dsu = new DSU(edges.length + 1);
    for (int[] e : edges) {
        if (!dsu.union(e[0], e[1])) {
            return e; // this edge creates a cycle
        }
    }
    return new int[]{};
}

Problem 5: Shortest Path in Weighted DAG (Hard)

Statement: Find shortest path in a directed acyclic graph using topological sort.

Java Solution:

java
int shortestPathDAG(int n, int[][] edges, int src, int dest) {
    List<List<int[]>> adj = new ArrayList<>();
    int[] indeg = new int[n];
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    
    for (int[] e : edges) {
        adj.get(e[0]).add(new int[]{e[1], e[2]});
        indeg[e[1]]++;
    }
    
    Queue<Integer> q = new LinkedList<>();
    for (int i = 0; i < n; i++) {
        if (indeg[i] == 0) q.offer(i);
    }
    
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    
    while (!q.isEmpty()) {
        int u = q.poll();
        for (int[] edge : adj.get(u)) {
            int v = edge[0], w = edge[1];
            dist[v] = Math.min(dist[v], dist[u] + w);
            indeg[v]--;
            if (indeg[v] == 0) q.offer(v);
        }
    }
    return dist[dest] == Integer.MAX_VALUE ? -1 : dist[dest];
}

Recognition Guide

Use BFS when:

  • You need shortest distance in an unweighted graph.
  • You're spreading or expanding from multiple sources.
  • You need layer-by-layer expansion.

Use DFS when:

  • You're exploring deeply for reachability.
  • You need to detect cycles or structure.
  • You prefer recursion.

Use Union-Find when:

  • Components are added dynamically.
  • You answer "are these in the same group?" repeatedly.
  • Cycle detection in undirected graphs is needed.

Comparison Tables

Tool Best For Time (op) Space
BFS Shortest unweighted path O(V + E) O(V)
DFS Cycle, reachability O(V + E) O(V) stack
DSU Dynamic connectivity O(α(V)) amortized O(V)

Design and Decision Making

  • DFS is recursive and natural for structural discovery.
  • BFS is iterative and ideal for shortest paths.
  • Union-Find is best for incremental component changes.
  • Mark visited early to avoid duplicate processing.

Practical Applications

  • Social networks: components are friend groups.
  • Route planning: BFS for shortest unweighted paths.
  • Scheduling: detect cycles with DFS.
  • Network connectivity: union-find for group formation.

Failure Modes and Trade-offs

  • Stack overflow: DFS on very deep graphs (use iterative or BFS).
  • Memory: BFS queues can grow large in dense graphs.
  • Path reconstruction: BFS needs parent tracking; DFS uses recursion.

Condensed Notes

  • BFS: queue, shortest unweighted paths, layer-by-layer.
  • DFS: recursion/stack, structural discovery, all reachable nodes.
  • Union-Find: fast dynamic connectivity, cycle detection.
  • Bipartite: 2-color during BFS/DFS; check for conflicts.

Additional Problems

Easy: Path Exists, Valid Tree, Number of Provinces, Surrounded Regions (variant), Clone Graph (recursive).

Medium: Course Schedule, Network Delay Time, Connecting Cities With Minimum Cost, Word Ladder, Pacific Atlantic Water Flow.

Hard: Alien Dictionary, Minimum Height Trees, Critical Connection (bridges), Count Components, Most Stones Removed.

Key Questions

  1. What is the key difference between BFS and DFS? BFS explores by layers (shortest unweighted path); DFS explores deeply (structural discovery).

  2. Why mark visited in BFS before enqueuing? To prevent duplicate enqueues and redundant processing.

  3. Can DFS find shortest paths? No, only BFS guarantees shortest path in unweighted graphs.

  4. How does union-find detect cycles? If union(u, v) fails (they're already connected), an edge creates a cycle.

  5. What is bipartite checking? Attempting to 2-color the graph; if colors conflict, it's not bipartite.

  6. How are SCC different from regular components? SCCs apply to directed graphs and require mutual reachability.

  7. When is multi-source BFS useful? When multiple sources expand simultaneously, and first arrival is the answer.

  8. Why does path compression speed up union-find? Flattens the tree, making future finds O(1) instead of O(height).

  9. What is an SCC algorithm? Kosaraju or Tarjan; both run DFS twice on original and reversed graphs.

  10. How do you detect directed cycles? Use DFS with a recursion stack (visiting, visited, unvisited states).

Applied Project

Build a social network analyzer that:

  • Loads users and edges from a file.
  • Counts connected components (groups of users).
  • Detects if the network is bipartite (e.g., two competing teams).
  • Finds shortest friend chain between two users.

Suggested structure: SocialNetwork class with methods for component counting, bipartite checking, and shortest path. Test on a 10–20 user sample.


19: Advanced Graph Algorithms

Introduction and Context

Graphs become powerful once you add direction (prerequisites, dependencies), weights (costs, distances), or capacity (flow, bandwidth). A naive traversal no longer answers the real question. You need algorithms that optimize for order, cost, or throughput.

This chapter teaches four critical families: topological sort for dependencies, shortest-path algorithms for costs, minimum spanning trees for global connectivity, and flow networks for capacity. Each solves a different optimization goal.

The core skill is recognizing the optimization objective—order, minimum cost, global connection, or maximum throughput—and choosing the matching algorithm.

Core Intuition and Mechanics

  • Topological sort: order nodes so every prerequisite comes first.
  • Dijkstra: find cheapest route from one source in non-negative weighted graphs.
  • MST: connect all nodes with minimum total edge weight.
  • Max flow: maximize units transferred from source to sink under edge capacities.
  • DSU optimizations: fast incremental connectivity with path compression and union by rank.

The mental model: each algorithm exploits a specific graph structure (DAG, non-negative weights, global connectivity, or flow networks).

Core Concepts and Subtopics

Concept Cluster: Topological Sort and DAG Algorithms

Topics in this cluster:

  • 19.1 Directed acyclic graphs; Topological Sort Pattern; Topological sort; Kahn's algorithm; DFS-based topological sort; Dependency ordering problems
  • 19.2 Shortest paths in DAGs
Definition

A topological order is a linear arrangement where every edge u→v has u before v. A DAG always admits at least one topological order.

Kahn's Algorithm
java
List<Integer> topologicalSort(int n, List<List<Integer>> adj) {
    int[] indeg = new int[n];
    for (int u = 0; u < n; u++) {
        for (int v : adj.get(u)) indeg[v]++;
    }
    
    Queue<Integer> q = new LinkedList<>();
    for (int i = 0; i < n; i++) {
        if (indeg[i] == 0) q.offer(i);
    }
    
    List<Integer> order = new ArrayList<>();
    while (!q.isEmpty()) {
        int u = q.poll();
        order.add(u);
        for (int v : adj.get(u)) {
            if (--indeg[v] == 0) q.offer(v);
        }
    }
    return order.size() == n ? order : new ArrayList<>(); // empty if cycle
}
DFS-Based Topological Sort
java
void dfsTopo(int u, List<List<Integer>> adj, boolean[] visited, Stack<Integer> st) {
    visited[u] = true;
    for (int v : adj.get(u)) {
        if (!visited[v]) dfsTopo(v, adj, visited, st);
    }
    st.push(u);
}

List<Integer> topologicalSortDFS(int n, List<List<Integer>> adj) {
    boolean[] visited = new boolean[n];
    Stack<Integer> st = new Stack<>();
    for (int i = 0; i < n; i++) {
        if (!visited[i]) dfsTopo(i, adj, visited, st);
    }
    List<Integer> order = new ArrayList<>();
    while (!st.isEmpty()) order.add(st.pop());
    return order;
}
Shortest Path in DAG
java
int shortestPathDAG(int n, List<List<int[]>> adj, int src) {
    List<Integer> topo = topologicalSort(n, adj); // modified to return Integer list
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    
    for (int u : topo) {
        if (dist[u] != Integer.MAX_VALUE) {
            for (int[] edge : adj.get(u)) {
                dist[edge[0]] = Math.min(dist[edge[0]], dist[u] + edge[1]);
            }
        }
    }
    return dist[n - 1];
}

Concept Cluster: Shortest-Path Algorithms

Topics in this cluster:

  • 19.2 (continued) Dijkstra's algorithm; Bellman-Ford algorithm; Floyd-Warshall algorithm; 0-1 BFS; Choosing the right shortest-path algorithm
Dijkstra's Algorithm
java
int[] dijkstra(int n, List<List<int[]>> adj, int src) {
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    pq.offer(new int[]{0, src});
    
    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int d = curr[0], u = curr[1];
        
        if (d > dist[u]) continue; // stale
        
        for (int[] edge : adj.get(u)) {
            int v = edge[0], w = edge[1];
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.offer(new int[]{dist[v], v});
            }
        }
    }
    return dist;
}
Bellman-Ford Algorithm (Negative Edges)
java
int[] bellmanFord(int n, int[][] edges, int src) {
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    
    for (int i = 0; i < n - 1; i++) {
        for (int[] e : edges) {
            if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]]) {
                dist[e[1]] = dist[e[0]] + e[2];
            }
        }
    }
    return dist;
}
Floyd-Warshall (All-Pairs Shortest Paths)
java
void floydWarshall(int[][] dist) {
    int n = dist.length;
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }
}

Concept Cluster: Minimum Spanning Tree and Kruskal/Prim

Topics in this cluster:

  • 19.3 Minimum Spanning Tree Pattern; Greedy view of minimum spanning trees; Kruskal's algorithm; Prim's algorithm
Kruskal's Algorithm with Union-Find
java
int kruskal(int n, int[][] edges) {
    Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
    DSU dsu = new DSU(n);
    int cost = 0, count = 0;
    
    for (int[] e : edges) {
        if (dsu.union(e[0], e[1])) {
            cost += e[2];
            count++;
            if (count == n - 1) break;
        }
    }
    return count == n - 1 ? cost : -1; // -1 if not fully connected
}
Prim's Algorithm
java
int prim(int n, List<List<int[]>> adj) {
    boolean[] inMST = new boolean[n];
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    pq.offer(new int[]{0, 0});
    
    int cost = 0;
    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int w = curr[0], u = curr[1];
        
        if (inMST[u]) continue;
        inMST[u] = true;
        cost += w;
        
        for (int[] edge : adj.get(u)) {
            int v = edge[0], wt = edge[1];
            if (!inMST[v]) pq.offer(new int[]{wt, v});
        }
    }
    return cost;
}

Concept Cluster: DSU Optimizations and Advanced Topics

Topics in this cluster:

  • 19.4 DSU / Union Find; Find and union operations; Path compression and union by rank; Connectivity and offline query problems; Offline query processing
  • 19.5 Strongly connected components; Kosaraju's algorithm; Tarjan's algorithm; Bridges in graphs; Articulation points; Failure analysis and graph-cut intuition
  • 19.6 Advanced Graph Flow Pattern; Flow network basics; Ford-Fulkerson; Edmonds-Karp; Max flow min cut; Relaxation and cut-based intuition; Residual thinking and network transformation basics; Shortest path with state; Advanced graph modeling; Choosing between traversal, shortest path, MST, and flow
Optimized DSU
java
class DSU {
    int[] parent, rank;
    DSU(int n) {
        parent = new int[n];
        rank = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
    }
    
    int find(int x) {
        if (parent[x] != x) parent[x] = find(parent[x]);
        return parent[x];
    }
    
    boolean union(int x, int y) {
        int px = find(x), py = find(y);
        if (px == py) return false;
        if (rank[px] < rank[py]) { int tmp = px; px = py; py = tmp; }
        parent[py] = px;
        if (rank[px] == rank[py]) rank[px]++;
        return true;
    }
}
SCC via Kosaraju (Sketch)
  1. DFS on original graph, push nodes in finish order.
  2. Create reverse graph.
  3. DFS on reverse in finish order; each DFS tree is one SCC.
Flow Networks (Conceptual)

Max flow finds maximum units that can move from source to sink under edge capacities. Use Ford-Fulkerson or Edmonds-Karp with residual networks.


Worked Examples

Worked Example 1: Course Schedule Ordering

Problem: Given n courses and prerequisites, output a valid course order or empty if impossible.

java
int[] findOrder(int n, int[][] prereq) {
    List<List<Integer>> adj = new ArrayList<>();
    int[] indeg = new int[n];
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    
    for (int[] p : prereq) {
        adj.get(p[1]).add(p[0]);
        indeg[p[0]]++;
    }
    
    Queue<Integer> q = new LinkedList<>();
    for (int i = 0; i < n; i++) {
        if (indeg[i] == 0) q.offer(i);
    }
    
    int[] order = new int[n];
    int idx = 0;
    while (!idx.isEmpty()) {
        int u = q.poll();
        order[idx++] = u;
        for (int v : adj.get(u)) {
            if (--indeg[v] == 0) q.offer(v);
        }
    }
    return idx == n ? order : new int[]{};
}

Worked Example 2: Minimum Spanning Tree

Problem: Find the minimum cost to connect all nodes with MST using Kruskal.

java
int minimumCost(int n, int[][] connections) {
    Arrays.sort(connections, (a, b) -> Integer.compare(a[2], b[2]));
    DSU dsu = new DSU(n + 1);
    int cost = 0, edges = 0;
    
    for (int[] c : connections) {
        if (dsu.union(c[0], c[1])) {
            cost += c[2];
            edges++;
            if (edges == n - 1) return cost;
        }
    }
    return -1; // not all connected
}

Worked Example 3: Dijkstra on Weighted Graph

Problem: Find shortest distance from source to all nodes in a weighted graph.

java
int[] shortestPath(int n, List<List<int[]>> graph, int src) {
    int[] dist = new int[n];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[src] = 0;
    
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    pq.offer(new int[]{0, src});
    
    while (!pq.isEmpty()) {
        int[] c = pq.poll();
        int d = c[0], u = c[1];
        if (d > dist[u]) continue;
        
        for (int[] e : graph.get(u)) {
            int v = e[0], w = e[1];
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.offer(new int[]{dist[v], v});
            }
        }
    }
    return dist;
}

Solved Problems

Problem 1: Minimum Ladder (Easy)

Statement: Find shortest word ladder from beginWord to endWord using a word list.

Java Solution (uses BFS):

java
int ladderLength(String begin, String end, List<String> words) {
    Set<String> dict = new HashSet<>(words);
    if (!dict.contains(end)) return 0;
    
    Queue<String> q = new LinkedList<>();
    q.offer(begin);
    int level = 1;
    
    while (!q.isEmpty()) {
        int size = q.size();
        for (int i = 0; i < size; i++) {
            String curr = q.poll();
            if (curr.equals(end)) return level;
            
            for (String next : neighbors(curr, dict)) {
                q.offer(next);
                dict.remove(next);
            }
        }
        level++;
    }
    return 0;
}

List<String> neighbors(String s, Set<String> dict) {
    List<String> res = new ArrayList<>();
    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        char old = chars[i];
        for (char c = 'a'; c <= 'z'; c++) {
            chars[i] = c;
            String candidate = new String(chars);
            if (dict.contains(candidate)) res.add(candidate);
        }
        chars[i] = old;
    }
    return res;
}

Problem 2: Network Delay Time (Easy)

Statement: Time for all nodes to receive a signal from node k using Dijkstra.

Java Solution:

java
int networkDelayTime(int[][] times, int n, int k) {
    List<List<int[]>> graph = new ArrayList<>();
    for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
    for (int[] t : times) {
        graph.get(t[0]).add(new int[]{t[1], t[2]});
    }
    
    int[] dist = new int[n + 1];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[k] = 0;
    
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    pq.offer(new int[]{0, k});
    
    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int d = curr[0], u = curr[1];
        if (d > dist[u]) continue;
        
        for (int[] edge : graph.get(u)) {
            int v = edge[0], w = edge[1];
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                pq.offer(new int[]{dist[v], v});
            }
        }
    }
    
    int maxDist = 0;
    for (int i = 1; i <= n; i++) {
        if (dist[i] == Integer.MAX_VALUE) return -1;
        maxDist = Math.max(maxDist, dist[i]);
    }
    return maxDist;
}

Problem 3: Connecting Cities (Medium)

Statement: Minimum cost to connect all cities using Kruskal's algorithm.

Java Solution:

java
int minimumCost(int n, int[][] connections) {
    Arrays.sort(connections, (a, b) -> Integer.compare(a[2], b[2]));
    DSU dsu = new DSU(n);
    int cost = 0, edges = 0;
    
    for (int[] c : connections) {
        if (dsu.union(c[0] - 1, c[1] - 1)) {
            cost += c[2];
            edges++;
            if (edges == n - 1) return cost;
        }
    }
    return -1;
}

Problem 4: Offline Queries (Medium)

Statement: Answer connectivity queries offline by processing edges in reverse and using union-find.

Java Solution (sketch):

java
int[] offlineQueries(int n, int[][] queries, int[][] edges) {
    int q = queries.length;
    int[] result = new int[q];
    DSU dsu = new DSU(n);
    
    // Reverse-process queries; add edges when needed
    // This is a sketch; full implementation involves index management
    return result;
}

Problem 5: Max Flow (Hard)

Statement: Find maximum flow from source to sink using Edmonds-Karp (BFS-based Ford-Fulkerson).

Java Solution (sketch):

java
int maxFlow(int n, int[][] edges, int src, int sink) {
    // Build residual graph
    // While augmenting path exists, push flow and update residuals
    // Return total flow
    return 0; // sketch
}

Recognition Guide

Use topological sort when:

  • The graph is directed and acyclic.
  • You need to order nodes respecting prerequisites.

Use Dijkstra when:

  • All edge weights are non-negative.
  • You need single-source shortest paths.

Use MST when:

  • You need to connect all nodes with minimum total cost.
  • It's an undirected weighted graph.

Use DSU when:

  • Edges are added dynamically.
  • You answer connectivity repeatedly.

Comparison Tables

Algorithm Best For Time Space Constraints
Kahn's DAG ordering O(V + E) O(V) No cycles
Dijkstra Shortest path O((V + E) log V) O(V) Non-neg weights
Floyd-Warshall All-pairs shortest O(V³) O(V²) Small V
Kruskal MST O(E log E) O(V) Undirected
Prim MST O(E log V) O(V) Undirected

Design and Decision Making

  • Choose representation carefully: adjacency list for sparse, matrix for dense.
  • Precompute: topological order before processing DAG queries.
  • Path reconstruction: track parents during Dijkstra if needed.

Practical Applications

  • Job scheduling: topological sort for task order.
  • Maps: Dijkstra for route planning.
  • Network design: MST for minimum cost wiring.
  • Traffic flow: max flow for capacity analysis.

Failure Modes and Trade-offs

  • Negative cycles: Dijkstra fails; use Bellman-Ford instead.
  • All-pairs overhead: Floyd-Warshall is O(V³); use single-source if few queries.
  • Disconnected graphs: Kruskal returns false; Prim finds a component MST.

Condensed Notes

  • Topological: Kahn (queue indegrees) or DFS (post-order).
  • Dijkstra: priority queue, non-negative weights only.
  • MST: Kruskal (edge sort + DSU) or Prim (frontier).
  • DSU: path compression + union by rank = near O(1) per operation.

Additional Problems

Easy: Topological Sort, Relabel to Valid Sequence, Network Delay Time (variant), Minimum Height Trees (variant), Earthquake Seismic Activity.

Medium: Optimal Account Balancing, Minimum Cost to Connect All Points, Path With Maximum Probability, Designing an Expression With Operators, Reconstruct Itinerary.

Hard: As Above So Below (SCC), Critical Server (bridges), Reorder Routes for Network Flow, Max Network Rank, Expensive Visits and Exits.

Key Questions

  1. When is topological sort impossible? When the DAG has a directed cycle.

  2. Why does Dijkstra fail on negative edges? Greedy extraction of minimum distance can be invalidated by later negative edges.

  3. What is a residual graph? A graph of remaining capacities after flow is pushed; used in max-flow algorithms.

  4. How is MST different from shortest-path trees? MST minimizes global edge weight; shortest-path minimizes distance from one source.

  5. Can an MST have multiple valid answers? Yes, if multiple edges have the same weight.

  6. What is an augmenting path in max flow? A path from source to sink with available capacity.

  7. How does union by rank speed up DSU? Attaching smaller tree to larger keeps the height logarithmic.

  8. What is path compression in DSU? Flattening the parent chain during find so future finds are faster.

  9. When should you choose Kruskal over Prim? Kruskal is simpler when edges are given; Prim when adjacency list is given.

  10. What is a cut in a graph? A partition of vertices; the minimum cut equals max flow (max-flow min-cut theorem).

Applied Project

Build a network optimizer that:

  • Loads nodes and weighted edges (flight routes with cost).
  • Finds shortest path between two cities (Dijkstra).
  • Computes minimum spanning tree (Kruskal).
  • Checks if courses can be taken given prerequisites (topological sort).

Suggested structure: Graph class with methods for Dijkstra, Kruskal, and topological sort. Test on a 20-node example.


20: Behavioral Design Patterns

Introduction and Context

Behavioral patterns define how objects interact and delegate responsibility. They are about communication and flexibility rather than structure. The core challenge is knowing when to apply them—over-engineering leads to code that is harder to follow, not easier.

This chapter covers six families: Strategy (switchable algorithms), Chain of Responsibility (request forwarding), Command (encapsulated actions), Mediator and Observer (decoupled communication), State and Memento (state management), and Interpreter/Iterator/Template Method/Visitor (traversal and computation).

The key skill is recognizing when to extract and defer behavior versus keeping it simple.

Core Intuition and Mechanics

Behavioral patterns answer: "Who does what, and how do we communicate?"

  • Strategy: switch algorithms at runtime.
  • Chain of Responsibility: pass a request down a chain until handled.
  • Command: encapsulate an action so it can be queued, undone, or replayed.
  • Mediator/Observer: decouple components via a central coordinator or event system.
  • State: behavior changes when internal state changes.
  • Memento: capture and restore state.
  • Visitor: apply operations to elements without modifying them.

The mental model: extract responsibility into separate objects so behavior is decoupled, testable, and reusable.

Core Concepts and Subtopics

Concept Cluster: Strategy and Chain of Responsibility

Topics in this cluster:

  • 20.1 Strategy Pattern; Algorithm family and runtime switching; Policy injection and payment-style examples
  • 20.2 Chain of Responsibility: Handler chain; Request propagation; Dynamic chains
Strategy Pattern

Encapsulate an algorithm so it can be swapped at runtime.

java
interface PaymentStrategy {
    void pay(double amount);
}

class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;
    public CreditCardPayment(String cardNumber) { this.cardNumber = cardNumber; }
    public void pay(double amount) {
        System.out.println("Paying " + amount + " via credit card " + cardNumber);
    }
}

class PayPalPayment implements PaymentStrategy {
    private String email;
    public PayPalPayment(String email) { this.email = email; }
    public void pay(double amount) {
        System.out.println("Paying " + amount + " via PayPal " + email);
    }
}

class ShoppingCart {
    private PaymentStrategy strategy;
    public void setPaymentStrategy(PaymentStrategy strategy) { this.strategy = strategy; }
    public void checkout(double amount) { strategy.pay(amount); }
}
Chain of Responsibility

Pass a request down a chain of handlers until one processes it.

java
abstract class Handler {
    protected Handler next;
    public void setNext(Handler next) { this.next = next; }
    public void handle(Request req) {
        if (canHandle(req)) {
            process(req);
        } else if (next != null) {
            next.handle(req);
        }
    }
    protected abstract boolean canHandle(Request req);
    protected abstract void process(Request req);
}

class Manager extends Handler {
    protected boolean canHandle(Request req) { return req.amount <= 1000; }
    protected void process(Request req) { System.out.println("Manager approves"); }
}

class Director extends Handler {
    protected boolean canHandle(Request req) { return req.amount <= 10000; }
    protected void process(Request req) { System.out.println("Director approves"); }
}

Concept Cluster: Command and Action Encapsulation

Topics in this cluster:

  • 20.3 Command Pattern: Command interface, invoker, and receiver; Undo, redo, and queueable commands; Middleware and action history examples
Definition

Encapsulate an action (method call) as an object so it can be queued, logged, or undone.

java
interface Command {
    void execute();
    void undo();
}

class LightOnCommand implements Command {
    private Light light;
    public LightOnCommand(Light light) { this.light = light; }
    public void execute() { light.on(); }
    public void undo() { light.off(); }
}

class RemoteControl {
    private Command lastCommand;
    public void pressButton(Command cmd) {
        cmd.execute();
        lastCommand = cmd;
    }
    public void pressUndo() { lastCommand.undo(); }
}

Concept Cluster: Mediator and Observer

Topics in this cluster:

  • 20.4 Mediator and Observer: Central coordinator; Decoupled communication; Chat room example; UI components coordination; Publisher subscriber, event listener, push, and pull models; Mediator versus observer in event-driven systems
Mediator Pattern

Central coordinator handles all communication between components.

java
interface Mediator {
    void notify(Component sender, String event);
}

class ChatRoomMediator implements Mediator {
    private List<User> users = new ArrayList<>();
    public void registerUser(User user) { users.add(user); }
    public void notify(Component sender, String event) {
        for (User user : users) {
            if (user != sender) {
                user.receive(event);
            }
        }
    }
}

class User extends Component {
    private String name;
    public User(String name, Mediator mediator) { 
        super(mediator); 
        this.name = name;
    }
    public void send(String msg) {
        mediator.notify(this, name + ": " + msg);
    }
    public void receive(String msg) {
        System.out.println(msg);
    }
}
Observer Pattern

Components register as listeners to a publisher.

java
interface Observer {
    void update(String event);
}

class EventPublisher {
    private List<Observer> observers = new ArrayList<>();
    public void subscribe(Observer obs) { observers.add(obs); }
    public void unsubscribe(Observer obs) { observers.remove(obs); }
    public void publish(String event) {
        for (Observer obs : observers) {
            obs.update(event);
        }
    }
}

class EventListener implements Observer {
    private String name;
    public EventListener(String name) { this.name = name; }
    public void update(String event) {
        System.out.println(name + " received: " + event);
    }
}

Concept Cluster: State and Memento

Topics in this cluster:

  • 20.5 State and Memento: Snapshot state; Undo history; State restore and encapsulation safety; State objects and transitions; Behavior by state and finite state machines; Memento versus command versus state
State Pattern

Behavior depends on internal state; state logic is in separate state objects.

java
interface State {
    void handle(TrafficLight light);
}

class RedState implements State {
    public void handle(TrafficLight light) {
        System.out.println("Red light");
        light.setState(new GreenState());
    }
}

class GreenState implements State {
    public void handle(TrafficLight light) {
        System.out.println("Green light");
        light.setState(new YellowState());
    }
}

class TrafficLight {
    private State state = new RedState();
    public void setState(State state) { this.state = state; }
    public void change() { state.handle(this); }
}
Memento Pattern

Capture and restore snapshots of state.

java
class Memento {
    private String state;
    public Memento(String state) { this.state = state; }
    public String getState() { return state; }
}

class TextEditor {
    private String text = "";
    public void setText(String text) { this.text = text; }
    public String getText() { return text; }
    public Memento createSnapshot() { return new Memento(text); }
    public void restore(Memento m) { text = m.getState(); }
}

class UndoManager {
    private Stack<Memento> history = new Stack<>();
    public void save(Memento m) { history.push(m); }
    public Memento undo() { return history.pop(); }
}

Concept Cluster: Iterator, Template Method, and Visitor

Topics in this cluster:

  • 20.6 Interpreter, Iterator, Template Method, and Visitor: Grammar rules; Expression tree structure; Parsing basics; Forward iterator; Reverse, custom, and lazy iterators; When a simple parser or loop is enough; Algorithm skeleton and hook methods; Fixed steps and extensible steps; Double dispatch and external operations; AST traversal and extending behavior cleanly
Iterator Pattern

Traverse a collection without exposing its structure.

java
interface Iterator<T> {
    boolean hasNext();
    T next();
}

interface Iterable<T> {
    Iterator<T> iterator();
}

class ListIterator<T> implements Iterator<T> {
    private List<T> list;
    private int index = 0;
    public ListIterator(List<T> list) { this.list = list; }
    public boolean hasNext() { return index < list.size(); }
    public T next() { return list.get(index++); }
}
Template Method Pattern

Define algorithm skeleton; subclasses fill in specific steps.

java
abstract class ReportGenerator {
    public final void generate() {
        collectData();
        analyzeData();
        formatReport();
        printReport();
    }
    protected abstract void collectData();
    protected abstract void analyzeData();
    protected abstract void formatReport();
    protected void printReport() { System.out.println("Report printed"); }
}

class SalesReportGenerator extends ReportGenerator {
    protected void collectData() { System.out.println("Collecting sales data"); }
    protected void analyzeData() { System.out.println("Analyzing sales trends"); }
    protected void formatReport() { System.out.println("Formatting as table"); }
}
Visitor Pattern

Apply operations to elements without modifying them.

java
interface Visitor {
    void visit(Circle c);
    void visit(Square s);
}

interface Shape {
    void accept(Visitor v);
}

class Circle implements Shape {
    public double radius;
    public Circle(double radius) { this.radius = radius; }
    public void accept(Visitor v) { v.visit(this); }
}

class AreaCalculator implements Visitor {
    public void visit(Circle c) { System.out.println("Area: " + (Math.PI * c.radius * c.radius)); }
    public void visit(Square s) { System.out.println("Area: " + (s.side * s.side)); }
}

Worked Examples

Worked Example 1: Strategy Pattern for Payment

Problem: Support multiple payment methods without hardcoding.

java
PaymentStrategy creditCard = new CreditCardPayment("1234-5678");
PaymentStrategy paypal = new PayPalPayment("user@example.com");

ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(creditCard);
cart.checkout(100.0); // uses credit card

cart.setPaymentStrategy(paypal);
cart.checkout(50.0); // uses PayPal

Worked Example 2: Command Pattern with Undo

Problem: Encapsulate light control so it can be undone.

java
Light light = new Light();
Command on = new LightOnCommand(light);
Command off = new LightOffCommand(light);

RemoteControl remote = new RemoteControl();
remote.pressButton(on);  // light is on
remote.pressUndo();      // light is off
remote.pressButton(off); // light is off

Worked Example 3: Observer for UI Updates

Problem: Multiple UI components listen to a data model.

java
EventPublisher publisher = new EventPublisher();
EventListener listener1 = new EventListener("UI Component 1");
EventListener listener2 = new EventListener("UI Component 2");

publisher.subscribe(listener1);
publisher.subscribe(listener2);
publisher.publish("Data changed"); // both listeners notified

Solved Problems

Problem 1: Simple Strategy Selection (Easy)

Statement: Create a sorting strategy that can be swapped.

Java Solution:

java
interface SortStrategy {
    void sort(int[] arr);
}

class BubbleSort implements SortStrategy {
    public void sort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                }
            }
        }
    }
}

class Sorter {
    private SortStrategy strategy;
    public void setStrategy(SortStrategy strategy) { this.strategy = strategy; }
    public void sort(int[] arr) { strategy.sort(arr); }
}

Problem 2: Chain of Responsibility for Approvals (Easy)

Statement: Route purchase requests through an approval chain.

Java Solution:

java
class Request {
    int amount;
    Request(int amount) { this.amount = amount; }
}

abstract class Approver {
    protected Approver next;
    public void setNext(Approver next) { this.next = next; }
    public void approve(Request req) {
        if (canApprove(req)) {
            System.out.println(getClass().getSimpleName() + " approves");
        } else if (next != null) {
            next.approve(req);
        }
    }
    protected abstract boolean canApprove(Request req);
}

class Manager extends Approver {
    protected boolean canApprove(Request req) { return req.amount <= 1000; }
}

class Director extends Approver {
    protected boolean canApprove(Request req) { return req.amount <= 10000; }
}

Problem 3: Command Pattern for Text Editor (Medium)

Statement: Implement copy, paste, undo using commands.

Java Solution:

java
interface EditorCommand {
    void execute();
    void undo();
}

class CopyCommand implements EditorCommand {
    private TextEditor editor;
    public CopyCommand(TextEditor editor) { this.editor = editor; }
    public void execute() { editor.copy(); }
    public void undo() { editor.clearClipboard(); }
}

class TextEditor {
    private String text, clipboard;
    public void copy() { clipboard = text; System.out.println("Copied"); }
    public void clearClipboard() { clipboard = ""; }
}

Problem 4: Observer for Event Notifications (Medium)

Statement: Multiple objects listen to user login/logout events.

Java Solution:

java
interface UserObserver {
    void onLogin(String username);
    void onLogout(String username);
}

class LoggingObserver implements UserObserver {
    public void onLogin(String username) { System.out.println("Logged in: " + username); }
    public void onLogout(String username) { System.out.println("Logged out: " + username); }
}

class UserService {
    private List<UserObserver> observers = new ArrayList<>();
    public void subscribe(UserObserver obs) { observers.add(obs); }
    public void login(String username) {
        for (UserObserver obs : observers) obs.onLogin(username);
    }
}

Problem 5: State Machine for Order (Hard)

Statement: Model order status transitions (pending → processing → shipped → delivered).

Java Solution:

java
interface OrderState {
    void process(Order order);
}

class PendingState implements OrderState {
    public void process(Order order) {
        System.out.println("Processing order");
        order.setState(new ProcessingState());
    }
}

class ProcessingState implements OrderState {
    public void process(Order order) {
        System.out.println("Shipping order");
        order.setState(new ShippedState());
    }
}

class Order {
    private OrderState state = new PendingState();
    public void setState(OrderState state) { this.state = state; }
    public void process() { state.process(this); }
}

Recognition Guide

Use Strategy when:

  • Multiple algorithms solve the same problem.
  • You need to switch algorithms at runtime.

Use Chain of Responsibility when:

  • A request passes through multiple handlers.
  • Handler choice is dynamic.

Use Command when:

  • You need to queue, log, or undo actions.
  • Requests are encapsulated as objects.

Use Observer when:

  • Many components listen to a single source.
  • Notifications are one-to-many.

Use State when:

  • Behavior changes with state.
  • State transitions are complex.

Comparison Tables

Pattern Purpose Complexity
Strategy Switchable algorithms Low
Chain Request forwarding Medium
Command Encapsulated actions Medium
Observer Event notifications Medium
State State-dependent behavior Medium
Visitor External operations High

Design and Decision Making

  • Don't over-engineer: simple if-else is fine for 2–3 choices.
  • Dependency injection: inject strategies, not create them.
  • Testability: mock observers or strategies for unit testing.
  • Single responsibility: each pattern extracts one concern.

Practical Applications

  • E-commerce: Strategy for payment methods.
  • Logging: Chain of Responsibility for log levels.
  • Undo/redo: Command pattern for transactions.
  • UI: Observer for button clicks and model updates.
  • State machines: State pattern for workflow.

Failure Modes and Trade-offs

  • Over-complexity: too many patterns obscure intent.
  • Memory overhead: extra objects from Command and Observer.
  • Indirection: harder to trace execution with Mediator or Visitor.

Condensed Notes

  • Strategy: swap algorithms.
  • Chain: forward until handled.
  • Command: encapsulate actions (undo, queue).
  • Observer: notify many listeners.
  • State: behavior by state.
  • Visitor: external operations.

Additional Problems

Easy: Simple Factory Strategy, Notification Chain, Undo History, Event Listener, Temperature State.

Medium: Payment Pipeline, Document Approval Workflow, Notification System, Trading State Machine, Discount Calculator.

Hard: Complex State Transitions, Multi-Observer Coordination, Visitor Over AST, Command Batch Processing, Event-Driven Architecture.

Key Questions

  1. When should you use Strategy instead of if-else? When choices are 3+, or will grow, or need plugin architecture.

  2. How does Chain of Responsibility differ from a simple if-else chain? CoR is for dynamic handlers; if-else is static.

  3. What is the Invoker in Command pattern? The object that triggers command execution (like a remote control).

  4. Why use Observer instead of direct method calls? Decoupling: publisher doesn't know about subscribers.

  5. What is a state in State pattern? An object encapsulating behavior for one state.

  6. How is Memento different from Command? Memento stores state snapshots; Command stores actions.

  7. What is double dispatch in Visitor? Two dynamic method calls: visitor type and element type determine behavior.

  8. When is Template Method better than inheritance? When subclasses need to customize only specific steps.

  9. Can Observer be used with pull instead of push? Yes; subscribers call methods on publisher to get data.

  10. How do you test behavioral patterns? Mock dependencies; verify method calls and state transitions.

Applied Project

Build a notification system that:

  • Sends notifications via email, SMS, and in-app using Strategy.
  • Routes notifications through approval chains (Chain of Responsibility).
  • Logs actions (Command pattern with undo).
  • Notifies multiple UI components (Observer pattern).

Suggested structure: NotificationService with NotificationStrategy, ApprovalChain, CommandHistory, and NotificationObserver interfaces. Test with 5 notification types and 3 delivery methods.


21: DP Foundations

Introduction and Context

Dynamic programming answers one core question: when does solving a big problem require solving the same smaller problem many times? The naive answer is "recursively branch and hope." The smarter answer is "store the answer once, reuse it everywhere."

This chapter teaches the foundational mental model for DP: recognizing overlapping subproblems, defining state precisely, writing correct transitions, and choosing between memoization (top-down caching) and tabulation (bottom-up filling). The core skill is not implementing loops. The core skill is making sure the state definition captures exactly what remains to be solved, no more, no less.

Learners often confuse DP with just using an array. DP is really about three things: identifying repeated work, storing answers to avoid repeating that work, and computing answers in an order where dependencies are already known. Arrays and maps are only the tools.

Core Intuition and Mechanics

A problem has overlapping subproblems when many branches of a recursion ask for the same smaller question. A problem has optimal substructure when the best answer to a bigger problem can be built from best answers to smaller problems. When both exist, DP fits.

The mental model: state names what still needs solving, transition describes how to build that state from smaller ones, base case is the smallest state with an immediate answer, and memoization or tabulation avoids recomputing.

Two styles: memoization recursively asks for smaller states and caches results; tabulation fills states in dependency order using loops.

Core Concepts and Subtopics

Concept Cluster: Recognizing Overlapping Work and Optimal Structure

Topics in this cluster:

  • 21.1 Overlapping subproblems; Optimal substructure
Why Overlapping Matters

In Fibonacci, fib(5) asks for fib(4) and fib(3), and fib(4) also asks for fib(3). That repeated fib(3) is overlap. Brute-force recursion recomputes it multiple times. Memoization computes it once.

Why Optimal Structure Matters

If the best answer to reaching step i is "best answer reaching step i-1 plus cost(i)" or "minimum of best reaching step i-2 plus cost(i)", then best answers to smaller problems build the larger answer. Not every problem has this property. Greedy choices on local decisions do not guarantee global optimality unless optimal substructure is proven.

How to Check

Draw the recursion tree on a small input. Count how many times the same state label appears. If it appears many times, overlap exists. Ask whether the best solution can always use best subsolutions. If yes, optimal structure probably holds.

Common Mistakes
  • assuming that any recursive problem has optimal substructure
  • confusing "a smaller problem appears in the recurrence" with "overlap helps"
  • ignoring whether local greedy choices prevent optimal assembly

Concept Cluster: Two Execution Styles

Topics in this cluster:

  • 21.2 Memoization; Tabulation; Memoization Pattern revisited; Tabulation versus recursion trade-offs
Memoization: Top-Down Caching

Recursively ask for the answer to a state. Before returning, cache it. On future calls to the same state, return the cached value.

java
int[] memo;

int fib(int n) {
    if (n <= 1) return n;
    if (memo[n] != -1) return memo[n];
    return memo[n] = fib(n - 1) + fib(n - 2);
}

Pros: Matches the problem's recursive structure directly; only computes needed states. Cons: Recursion depth limits; call-stack overhead.

Tabulation: Bottom-Up Filling

Decide an order where dependencies come first. Initialize base cases. Loop through states in order, building each from already-computed states.

java
int fib(int n) {
    if (n <= 1) return n;
    int[] dp = new int[n + 1];
    dp[1] = 1;
    for (int i = 2; i <= n; i++) {
        dp[i] = dp[i - 1] + dp[i - 2];
    }
    return dp[n];
}

Pros: No recursion depth limit; tight loop control. Cons: Must decide order upfront; may compute unnecessary states.

Trade-Offs

Choose memoization when the state graph is sparse (not all states are needed). Choose tabulation when all states are likely needed and recursion depth is a concern.

Concept Cluster: State Design and Transitions

Topics in this cluster:

  • 21.3 1D Dynamic Programming Pattern; 2D Dynamic Programming Pattern; State Representation; State design
  • 21.4 Defining state correctly; Transition logic; Designing transitions
1D DP Pattern

One index or progress measure defines the subproblem. Example: dp[i] = best answer using elements up to index i, or ways to reach step i.

java
// Climbing stairs: ways to reach step i using 1 or 2 steps
int[] dp = new int[n + 1];
dp[0] = 1; dp[1] = 1;
for (int i = 2; i <= n; i++) {
    dp[i] = dp[i - 1] + dp[i - 2];
}

Key: One sentence defines the meaning of dp[i]. Stick to it throughout.

2D DP Pattern

Two coordinates define the subproblem. Example: dp[i][j] = best answer for first i items and first j capacity, or grid paths to row i, column j.

java
// Grid paths: ways to reach (i, j) moving right or down
int[][] dp = new int[rows][cols];
for (int i = 0; i < rows; i++) dp[i][0] = 1;
for (int j = 0; j < cols; j++) dp[0][j] = 1;
for (int i = 1; i < rows; i++) {
    for (int j = 1; j < cols; j++) {
        dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
    }
}

Key: Both axes must represent real progress dimensions. If one axis is redundant, simplify to 1D.

Transition Logic

Every state must depend only on already-computed states. Identify which earlier states contribute. Write one sentence: "dp[i] equals ...". Then code it exactly.

java
// House robber: max money up to house i
for (int i = 1; i < n; i++) {
    dp[i] = Math.max(dp[i - 1], nums[i] + (i >= 2 ? dp[i - 2] : 0));
}

Concept Cluster: Recurrence Discipline

Topics in this cluster:

  • 21.5 Recurrence mistakes, invalid states, and base-case design
  • 21.6 Move from brute force to recurrence to optimized implementation
Common Recurrence Mistakes
  1. Vague state meaning: "best answer" is not complete. "best answer using items up to index i under capacity w" is.
  2. Wrong dependency order: In tabulation, use a state before it is computed.
  3. Mixing two state definitions: dp[i] sometimes means "ending at i", sometimes "up to i". Pick one.
Invalid States

Some states may be unreachable or impossible. Mark them explicitly with a sentinel value like Integer.MAX_VALUE (for minimization) or -1 (if positive is always valid).

java
// Knapsack: impossible capacities start at Integer.MAX_VALUE
int[] dp = new int[capacity + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0; // base: 0 capacity, 0 items, 0 cost
for (int i = 0; i < items; i++) {
    for (int c = capacity; c >= weight[i]; c--) {
        if (dp[c - weight[i]] != Integer.MAX_VALUE) {
            dp[c] = Math.min(dp[c], dp[c - weight[i]] + value[i]);
        }
    }
}
Base Cases

Base cases are the smallest valid states. Derive them from the state meaning, not from convenience.


Worked Examples

Worked Example 1: Fibonacci with Memoization vs Tabulation

Problem: Compute the nth Fibonacci number efficiently.

Brute Force:

java
int fib(int n) {
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2); // O(2^n)
}

Memoization:

java
int fibMemo(int n, int[] memo) {
    if (n <= 1) return n;
    if (memo[n] != -1) return memo[n];
    return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
}

Tabulation:

java
int fibTab(int n) {
    if (n <= 1) return n;
    int[] dp = new int[n + 1];
    dp[1] = 1;
    for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

Dry Run (n=4): dp[0]=0, dp[1]=1, dp[2]=1, dp[3]=2, dp[4]=3. ✓

Complexity: Time O(n), Space O(n).

Decision: Tabulation avoids recursion depth limits. Memoization matches the math. Both are correct here.

Worked Example 2: Climbing Stairs (1D DP)

Problem: Climb n stairs. Each move is 1 or 2 steps. Count total ways.

State: dp[i] = ways to reach step i.

Base: dp[1] = 1, dp[2] = 2.

Transition: dp[i] = dp[i-1] + dp[i-2] (come from step i-1 or i-2).

java
int climbStairs(int n) {
    if (n <= 2) return n;
    int[] dp = new int[n + 1];
    dp[1] = 1; dp[2] = 2;
    for (int i = 3; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

Dry Run (n=4): dp[1]=1, dp[2]=2, dp[3]=3, dp[4]=5. ✓

Complexity: Time O(n), Space O(n); can reduce to O(1) with two variables.

Worked Example 3: 0/1 Knapsack (2D to 1D)

Problem: Select items with max value under weight limit.

2D State: dp[i][w] = max value using first i items, weight limit w.

java
int knapsack2D(int[] weights, int[] values, int capacity) {
    int n = weights.length;
    int[][] dp = new int[n + 1][capacity + 1];
    
    for (int i = 1; i <= n; i++) {
        for (int w = 0; w <= capacity; w++) {
            dp[i][w] = dp[i - 1][w]; // skip item i
            if (w >= weights[i - 1]) {
                dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
            }
        }
    }
    return dp[n][capacity];
}

1D Optimization: Note that each row depends only on the previous row.

java
int knapsack1D(int[] weights, int[] values, int capacity) {
    int[] dp = new int[capacity + 1];
    
    for (int i = 0; i < weights.length; i++) {
        for (int w = capacity; w >= weights[i]; w--) {
            dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]);
        }
    }
    return dp[capacity];
}

Key: Reverse iteration ensures each item is used at most once. Forward iteration allows unbounded reuse.

Complexity: Time O(n * capacity), Space O(capacity).


Solved Problems

Problem 1 (Easy): Maximum subarray sum.

java
int maxSubarray(int[] nums) {
    int maxHere = nums[0], maxSoFar = nums[0];
    for (int i = 1; i < nums.length; i++) {
        maxHere = Math.max(nums[i], maxHere + nums[i]);
        maxSoFar = Math.max(maxSoFar, maxHere);
    }
    return maxSoFar;
}

Problem 2 (Easy): Count number of ways to decode a string of digits (base case: "12" -> "1,2" or "12").
Recurrence: if current digit is valid, add ways to previous; if last two digits form valid code, add those ways too.

Problem 3 (Medium): Longest increasing subsequence (LIS).

java
int lengthOfLIS(int[] nums) {
    int n = nums.length;
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
        }
    }
    return Arrays.stream(dp).max().orElse(0);
}

Problem 4 (Medium): Edit distance (minimum edits to transform one string to another).
State: dp[i][j] = edits to transform first i chars of s1 to first j chars of s2. Transitions: match (no edit), insert, delete, or replace.

Problem 5 (Hard): Distinct subsequences of s that equal t.
State: dp[i][j] = count of distinct t[0..j-1] using s[0..i-1]. If s[i-1] == t[j-1], add ways without s[i-1].


Recognition Guide

Use DP when:

  • brute-force recursion repeats the same subproblem many times
  • the answer for a state depends on best/count for smaller states
  • the input size rules out complete enumeration but DP states are manageable

Do not use DP when:

  • a greedy choice provably gives the optimal answer
  • the state space is too large (exponential or very high dimension)
  • a simpler linear scan or sorting algorithm already solves it

Comparison Tables

Aspect Memoization Tabulation
Order Top-down, on-demand Bottom-up, predetermined
Recursion depth Can hit stack limit No stack overhead
Clarity Matches math closely Requires loop order design
Sparsity Only computed states All states computed
Debugging Trace recurrence directly Print table at each step

Design and Decision Making

When to choose state dimensions: Ask "what information does the future need?" Not "what information does the past have?" If position alone is enough, use 1D. If position and budget matter differently, use 2D.

When to compress memory: After the full-state solution works, check if only a window of prior states matter. Many 2D problems compress to rolling 1D arrays.

When to use memoization: Non-linear state graphs, sparse states, problem structure that branches unpredictably.

When to use tabulation: Dense regular grids, all states likely needed, large input sizes.


Practical Applications

  • Finance: shortest cost path, max profit sequences
  • Bioinformatics: string alignment, sequence matching
  • Manufacturing: optimal production schedules under constraints
  • Scheduling: task ordering, resource allocation

Failure Modes and Trade-offs

Silent wrong answers from incorrect state meaning are the worst. Always prove the recurrence on a small example by hand first.

Stack overflow in memoization is real. Test recursion depth on large inputs.

TLE (Time Limit Exceeded) happens when the DP state space is larger than expected. Count states before coding.

MLE (Memory Limit Exceeded) happens with dense large tables. Compress immediately if only a window matters.


Condensed Notes

  • Overlap: Same state computed multiple times → memoize
  • Optimal substructure: Best solution uses best subsolutions
  • 1D: dp[i] = answer for first i items or up to position i
  • 2D: dp[i][j] = answer for first i items with second param j
  • Base cases: Derive from state meaning, not convenience
  • Transitions: Write one sentence; then code it

Additional Problems

Easy: (1) Fibonacci, (2) Climbing stairs, (3) Min cost climbing stairs, (4) House robber 1, (5) Is subsequence.

Medium: (1) LIS, (2) Edit distance, (3) Distinct subsequences, (4) Max product subarray, (5) Coin change ways.

Hard: (1) Palindrome partitions DP, (2) Burst balloons, (3) Integer break, (4) Regular expression matching, (5) Wildcard matching.


Key Questions

  1. What does "overlapping subproblems" mean? When recursive calls ask for the same state many times, wasting computation.

  2. When is DP not the right tool? When a greedy choice works or the state space is exponential even after DP.

  3. How do you choose between 1D and 2D DP? 1D if one progress measure suffices; 2D if two independent coordinates matter.

  4. Why reverse iteration in 0/1 knapsack? To ensure each item is used at most once (can't use the same item row twice).

  5. How do you detect wrong state meaning? Run the recurrence on a tiny example by hand and compare the output.

  6. What is the difference between memoization and tabulation? Memoization is recursive top-down; tabulation is iterative bottom-up.

  7. How do you compress 2D DP to 1D? If each row depends only on the previous row, keep only two rows or even one.

  8. What is a base case? The smallest state where the answer is known immediately without further recursion.

  9. When should you use Integer.MAX_VALUE for impossible states? In minimization problems where no valid answer exists for some states.

  10. How do you avoid off-by-one errors? Use one clear sentence for state meaning (e.g., "first i items, not index i") and stick to it.


Applied Project

Project: Build a cost-optimized flight itinerary planner.

Features:

  • Find cheapest path from origin to destination with up to k stops
  • Handle multiple airlines, prices, and schedules
  • Compute in reasonable time even for many flights

Suggested structure:

  • State: dp[stops][destination] = min cost to reach destination using at most stops flights
  • Base: dp[0][origin] = 0
  • Transition: For each stop, try extending to each neighbor
  • Compress to rolling array if memory is tight

Testing: Verify on small city networks; compare against all-paths brute force for correctness.

22: Core DP Families

Introduction and Context

Once DP foundations are solid, the real skill is recognizing which DP family a problem belongs to. A knapsack problem is not solved the same way as a string-comparison problem, even though both use DP.

This chapter teaches five major DP families: linear sequences (stairs, house robber, LIS), grids (unique paths, minimum cost), knapsack (capacity-constrained choices), strings (LCS, edit distance), and interval/state-machine DP (range decisions, mode transitions).

Each family has a standard state design and transition shape. Learning these families does not mean memorizing formulas. It means recognizing the structure of a new problem, fitting it into a known family, and adapting the template correctly.

Core Intuition and Mechanics

  • Sequence DP: Progress left to right; each state depends on earlier positions.
  • Grid DP: Two axes; fill in dependency order (top-left to bottom-right).
  • Knapsack: Items and capacity; each item chosen at most once (0/1) or many times (unbounded).
  • String DP: Prefix pairs; compare or align two strings.
  • Interval DP: Split a range; recur on subranges and combine.
  • State Machine DP: Small set of modes; transitions between them over time.

Core Concepts and Subtopics

Concept Cluster: Sequence Decisions and Transitions

Topics in this cluster:

  • 22.1 Fibonacci and introductory recurrences; Climbing stairs; House robber
  • 22.2 Longest increasing subsequence; Decode ways; Space optimization techniques
Fibonacci and Climbing Stairs

fib(n) = fib(n-1) + fib(n-2) is the simplest recurrence. Climbing stairs with 1 or 2 steps uses the same recurrence because you can reach step i from steps i-1 and i-2.

java
int climb(int n) {
    if (n <= 2) return n;
    int a = 1, b = 2;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }
    return b;
}
House Robber

State: dp[i] = max money robbing houses up to index i. Decision: rob house i or skip it.

java
int rob(int[] nums) {
    int prev2 = 0, prev1 = 0;
    for (int num : nums) {
        int curr = Math.max(prev1, num + prev2);
        prev2 = prev1;
        prev1 = curr;
    }
    return prev1;
}
Longest Increasing Subsequence (LIS)

State: dp[i] = length of LIS ending at index i. Transition: for all j < i where nums[j] < nums[i], dp[i] = max(dp[i], dp[j] + 1).

java
int lis(int[] nums) {
    int n = nums.length;
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
        }
    }
    return Arrays.stream(dp).max().orElse(0);
}

Complexity: O(n²) DP; O(n log n) with patience sorting.

Decode Ways

State: dp[i] = ways to decode first i characters. Transition: if char at i-1 is '1'-'9', add dp[i-1]; if chars at i-2 and i-1 form '10'-'26', add dp[i-2].

java
int numDecodings(String s) {
    int n = s.length();
    int[] dp = new int[n + 1];
    dp[0] = 1;
    dp[1] = s.charAt(0) != '0' ? 1 : 0;
    
    for (int i = 2; i <= n; i++) {
        int one = Integer.parseInt(s.substring(i - 1, i));
        int two = Integer.parseInt(s.substring(i - 2, i));
        
        if (one != 0) dp[i] += dp[i - 1];
        if (two >= 10 && two <= 26) dp[i] += dp[i - 2];
    }
    return dp[n];
}
Space Optimization

If only k prior states matter, keep k variables instead of a full array. Check after the full solution works.

java
// Rolling two variables instead of dp array
int maxRob = 0, prevMax = 0;
for (int num : nums) {
    int curr = Math.max(prevMax, num + maxRob);
    maxRob = prevMax;
    prevMax = curr;
}

Concept Cluster: Grid and Interval Problems

Topics in this cluster:

  • 22.3 Grid dynamic programming; Unique paths; Minimum path sum
  • 22.4 0/1 knapsack; Knapsack Pattern
Unique Paths

State: dp[i][j] = ways to reach (i,j) moving only right or down. Base: first row and first column are all 1. Transition: dp[i][j] = dp[i-1][j] + dp[i][j-1].

java
int uniquePaths(int m, int n) {
    int[][] dp = new int[m][n];
    for (int i = 0; i < m; i++) dp[i][0] = 1;
    for (int j = 0; j < n; j++) dp[0][j] = 1;
    
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        }
    }
    return dp[m - 1][n - 1];
}
Minimum Path Sum

Same structure, but sum costs instead of counting.

java
int minPathSum(int[][] grid) {
    int m = grid.length, n = grid[0].length;
    int[][] dp = new int[m][n];
    dp[0][0] = grid[0][0];
    
    for (int i = 1; i < m; i++) dp[i][0] = dp[i - 1][0] + grid[i][0];
    for (int j = 1; j < n; j++) dp[0][j] = dp[0][j - 1] + grid[0][j];
    
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
        }
    }
    return dp[m - 1][n - 1];
}
0/1 Knapsack

State: dp[w] = max value achievable with weight limit w. For each item, iterate capacities backward to ensure each item is used at most once.

java
int knapsack(int[] weights, int[] values, int capacity) {
    int[] dp = new int[capacity + 1];
    
    for (int i = 0; i < weights.length; i++) {
        for (int w = capacity; w >= weights[i]; w--) {
            dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]);
        }
    }
    return dp[capacity];
}

Concept Cluster: String and State-Machine Families

Topics in this cluster:

  • 22.5 Subsequence DP; String DP; Longest common subsequence; Edit distance
  • 22.6 Interval DP; State machine DP
Longest Common Subsequence (LCS)

State: dp[i][j] = LCS length for first i chars of s1, first j chars of s2.

java
int lcs(String s1, String s2) {
    int m = s1.length(), n = s2.length();
    int[][] dp = new int[m + 1][n + 1];
    
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[m][n];
}
Edit Distance

State: dp[i][j] = min edits to transform s1[0..i-1] to s2[0..j-1].

java
int editDistance(String s1, String s2) {
    int m = s1.length(), n = s2.length();
    int[][] dp = new int[m + 1][n + 1];
    
    for (int i = 0; i <= m; i++) dp[i][0] = i;
    for (int j = 0; j <= n; j++) dp[0][j] = j;
    
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
            }
        }
    }
    return dp[m][n];
}
State Machine DP (Stock Trading)

State: dp[i][0] = max profit holding stock at day i; dp[i][1] = max profit not holding at day i.

java
int maxProfit(int[] prices) {
    int hold = -prices[0], free = 0;
    
    for (int i = 1; i < prices.length; i++) {
        int newHold = Math.max(hold, free - prices[i]);
        int newFree = Math.max(free, hold + prices[i]);
        hold = newHold;
        free = newFree;
    }
    return free;
}

Worked Examples

Worked Example 1: Maximum Product Subarray (Sequence DP with Negatives)

Problem: Find max product of contiguous subarray.

Challenge: Negatives flip sign. Track both max and min ending at each position.

java
int maxProduct(int[] nums) {
    int maxHere = nums[0], minHere = nums[0], result = nums[0];
    
    for (int i = 1; i < nums.length; i++) {
        int newMax = Math.max(nums[i], Math.max(maxHere * nums[i], minHere * nums[i]));
        int newMin = Math.min(nums[i], Math.min(maxHere * nums[i], minHere * nums[i]));
        
        maxHere = newMax;
        minHere = newMin;
        result = Math.max(result, maxHere);
    }
    return result;
}

Dry Run [2, 3, -2, 4]: Start (2,2,2). i=1: (6,3,6). i=2: (4,-6,4). i=3: (24,-24,24). Result: 24. ✓

Worked Example 2: Coin Change (Unbounded Knapsack)

Problem: Minimum coins to make amount.

State: dp[amt] = min coins for amount.

java
int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);
    dp[0] = 0;
    
    for (int amt = 1; amt <= amount; amt++) {
        for (int coin : coins) {
            if (amt >= coin) {
                dp[amt] = Math.min(dp[amt], dp[amt - coin] + 1);
            }
        }
    }
    return dp[amount] <= amount ? dp[amount] : -1;
}

Note: Forward iteration (unbounded) vs backward (0/1).

Worked Example 3: Regular Expression Matching (String DP with Wildcards)

Problem: DP match where '.' matches one char, '*' matches 0+ of previous char.

java
boolean isMatch(String s, String p) {
    int m = s.length(), n = p.length();
    boolean[][] dp = new boolean[m + 1][n + 1];
    dp[0][0] = true;
    
    for (int j = 2; j <= n; j++) {
        if (p.charAt(j - 1) == '*') dp[0][j] = dp[0][j - 2];
    }
    
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (p.charAt(j - 1) == '*') {
                dp[i][j] = dp[i][j - 2] || (dp[i - 1][j] && (s.charAt(i - 1) == p.charAt(j - 2) || p.charAt(j - 2) == '.'));
            } else {
                dp[i][j] = dp[i - 1][j - 1] && (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.');
            }
        }
    }
    return dp[m][n];
}

Solved Problems

Problem 1 (Easy): Palindromic substrings count. State: dp[i][j] = true if s[i..j] is palindrome. Transition: true if s[i]==s[j] and dp[i+1][j-1], base case length 1 or 2 strings.

Problem 2 (Easy): Partition equal subset sum. State: dp[sum] = true if sum is achievable. Each number either included or not.

Problem 3 (Medium): Word break. State: dp[i] = true if s[0..i-1] can be segmented into dictionary. Transition: if dp[j] and s[j..i-1] in dict, then dp[i] = true.

Problem 4 (Medium): Maximal square in matrix. State: dp[i][j] = side length of largest square with (i,j) as bottom-right. Transition: if grid[i][j]='1', then dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]).

Problem 5 (Hard): Burst balloons. State: dp[left][right] = max coins bursting balloons in range. Transition: try each balloon last, compute coins = balloons[left]*balloons[mid]*balloons[right] + recursive solutions.


Recognition Guide

  • Sequence DP: One linear progress; each answer depends on prior positions.
  • Grid DP: Two axes; fill top-left to bottom-right.
  • Knapsack: Items and capacity; backward iteration for 0/1, forward for unbounded.
  • String DP: Two string prefixes; match, align, or count.
  • State Machine: Small set of modes; transitions over time.
  • Interval DP: Split a range; recur on subranges.

Comparison Tables

Family State Order Use Case
Sequence dp[i] i ascending Linear progress
Grid dp[i][j] row then col 2D paths
Knapsack dp[w] capacity desc (0/1) Item selection
String dp[i][j] both ascending Prefix comparison
Interval dp[l][r] length ascending Range decisions
State Machine dp[day][state] day ascending Mode transitions

Design and Decision Making

When a new problem arrives, ask:

  1. Is there one linear progress measure? → Sequence DP.
  2. Are there two grid-like dimensions? → Grid DP.
  3. Do we choose items under a capacity or limit? → Knapsack.
  4. Do we compare or transform two strings? → String DP.
  5. Do we split a range and combine results? → Interval DP.
  6. Do we move between modes? → State Machine DP.

Practical Applications

  • Finance: optimal trade sequences, portfolio allocation
  • Bioinformatics: sequence alignment, gene matching
  • Game design: optimal play strategies, turn-based decisions
  • Manufacturing: assembly optimization, scheduling

Failure Modes and Trade-offs

Knapsack backward iteration forgotten: Forward iteration allows reusing one item. Must reverse for 0/1.

String DP off-by-one: Prefix lengths (i+1 dimensions) vs indices can confuse. Be explicit.

State machine mode forget: Forgetting one mode or an allowed transition causes wrong answers.


Condensed Notes

  • Sequence: dp[i] = f(dp[i-1], dp[i-2], ...)
  • Grid: dp[i][j] = combine(dp[i-1][j], dp[i][j-1], ...)
  • Knapsack 0/1: Loop capacity backward; each item once.
  • Knapsack unbounded: Loop capacity forward; each item many times.
  • String DP: Prefix lengths i, j both ascending.
  • State Machine: Rolling variables for day transitions.

Additional Problems

Easy: (1) Delete and earn, (2) Best time buy-sell stock, (3) Min cost stairs, (4) Climbing stairs variants, (5) House robber 2 (circular).

Medium: (1) Coin change 2 (ways), (2) Partition equal subset, (3) Target sum (2D count), (4) Unique paths 2 (obstacles), (5) Triangle minimum path.

Hard: (1) Wildcard matching, (2) Distinct subsequences 2, (3) Palindrome partitions (count), (4) Maximal rectangle, (5) Shortest path visiting all cells.


Key Questions

  1. Why reverse capacity iteration in 0/1 knapsack? Each item used once; forward would reuse same item.

  2. When do you use interval DP? Problems asking to split a range optimally.

  3. How is LCS different from edit distance? LCS finds longest matching subsequence; edit distance counts minimum operations to transform.

  4. When does a problem need two state variables? When answer depends on two independent progress measures or comparison dimensions.

  5. What is the state machine DP pattern? Track a small number of modes; transition between them; optimize over time.

  6. How do you handle string DP with wildcards? Special transitions for * (0+ matches) vs normal chars.

  7. Can you always compress 2D knapsack to 1D? Yes, if each item is used at most once (0/1). Unbounded needs more state handling.

  8. What is the key insight for palindrome DP? If ends match and middle is palindrome, whole range is palindrome.

  9. How do you recognize interval DP problems? Ranges, splitting points, combining subrange answers.

  10. When should you track both max and min? When negatives or reversals can change the optimal choice.


Applied Project

Project: Build a stock trading assistant with multiple constraints.

Features:

  • Buy/sell with transaction fee
  • Cooldown days between transactions
  • Maximum held stocks limit
  • Compute max profit

State: dp[day][holding][cooldown] = max profit at day, holding status, cooldown remaining.

Testing: Verify edge cases (fee=0, cooldown=0, single stock).

23: Advanced DP Families

Introduction and Context

Some problems do not fit neatly into sequence, grid, or knapsack boxes. Trees need DP on parent-child structure. Subsets need bitmask encoding. Number constraints need digit DP. Hard problems combine multiple techniques.

This chapter teaches how to recognize and design DP states when the input structure is non-linear or the constraints are architectural. The skill is not memorizing new formulas. It is identifying what information matters for future decisions and encoding it compactly.

Core Intuition and Mechanics

  • Tree DP: Each node state depends on child subtrees.
  • Bitmask DP: Subsets encoded as bits; state transitions flip bits.
  • Digit DP: Process a number digit by digit; track constraint tightness.
  • Advanced compression: Store only what future decisions need; drop everything else.
  • Constraint-driven pruning: Eliminate branches that violate invariants or cannot improve the objective.

Core Concepts and Subtopics

Concept Cluster: Non-Linear State Spaces

Topics in this cluster:

  • 23.1 DP on subsequences; DP on strings; DP on trees; Tree DP Pattern
  • 23.2 Bitmask DP; Bitmasking basics; Subset and state-encoding patterns; Digit DP overview; Digit DP Pattern
Tree DP Pattern

State: Each node stores answers for its subtree, often split into cases (e.g., node taken vs skipped).

java
// Maximum weighted independent set on tree (no two adjacent nodes)
class TreeNode { int val; List<TreeNode> children; }

int[] dfs(TreeNode node) {
    if (node.children.isEmpty()) return new int[]{node.val, 0};
    
    int taken = node.val;
    int skipped = 0;
    
    for (TreeNode child : node.children) {
        int[] states = dfs(child);
        taken += states[1]; // if node taken, children must be skipped
        skipped += Math.max(states[0], states[1]); // if node skipped, children can be either
    }
    return new int[]{taken, skipped};
}

Key: Each subtree computes independently; results combine at parent.

Bitmask DP

State: dp[mask][last] where mask encodes which items are used, last is previous item index.

java
// Traveling salesman: visit all cities once, minimize cost
int tsp(int[][] dist) {
    int n = dist.length;
    int[][] dp = new int[1 << n][n];
    for (int[] row : dp) Arrays.fill(row, Integer.MAX_VALUE);
    dp[1][0] = 0;
    
    for (int mask = 1; mask < (1 << n); mask++) {
        for (int u = 0; u < n; u++) {
            if ((mask & (1 << u)) == 0) continue;
            if (dp[mask][u] == Integer.MAX_VALUE) continue;
            
            for (int v = 0; v < n; v++) {
                if ((mask & (1 << v)) != 0) continue;
                int newMask = mask | (1 << v);
                dp[newMask][v] = Math.min(dp[newMask][v], dp[mask][u] + dist[u][v]);
            }
        }
    }
    
    int result = Integer.MAX_VALUE;
    for (int u = 1; u < n; u++) {
        result = Math.min(result, dp[(1 << n) - 1][u] + dist[u][0]);
    }
    return result;
}

Complexity: O(2^n * n^2); only viable for n ≤ 20.

Digit DP

State: dp[pos][tight][started] = count of numbers with certain digit properties up to bound.

java
// Count integers in [0, n] where digit sum is k
class DigitDP {
    int n, k;
    int[][][] memo;
    
    int solve(int pos, int tight, int sum) {
        if (sum > k) return 0;
        if (pos == -1) return sum == k ? 1 : 0;
        
        if (memo[pos][tight][sum] != -1) return memo[pos][tight][sum];
        
        int limit = tight ? (n / (int)Math.pow(10, pos)) % 10 : 9;
        int result = 0;
        
        for (int digit = 0; digit <= limit; digit++) {
            int newTight = tight && (digit == limit) ? 1 : 0;
            result += solve(pos - 1, newTight, sum + digit);
        }
        return memo[pos][tight][sum] = result;
    }
}

Key: Tight flag ensures prefix stays ≤ bound.

Concept Cluster: Compression and Optimization

Topics in this cluster:

  • 23.3 Advanced State Compression Pattern; Sparse-state memo tables and caching strategies
  • 23.4 Constraint-driven pruning in hard DP problems; Recognizing DP states in hard problems
  • 23.5 Divide and Conquer Pattern; Divide and Conquer DP Pattern
  • 23.6 Knuth Optimization Pattern; Convex Hull Trick Pattern; Monotonicity assumptions and optimization prerequisites; When a simpler DP is better than a theoretical optimization
State Compression

If the state space is sparse, use a HashMap instead of an array.

java
// Coin change with many denominations, large target
Map<Integer, Integer> memo = new HashMap<>();

int minCoins(int amount) {
    if (amount == 0) return 0;
    if (memo.containsKey(amount)) return memo.get(amount);
    
    int result = Integer.MAX_VALUE;
    for (int coin : coins) {
        if (amount >= coin) {
            int sub = minCoins(amount - coin);
            if (sub != Integer.MAX_VALUE) result = Math.min(result, sub + 1);
        }
    }
    return memo.put(amount, result);
}
Constraint-Driven Pruning

Prune branches that violate problem constraints before exploring further.

java
// Max weight independent set: prune if current weight > limit or remaining nodes cannot improve
int search(int node, int weight, int remaining) {
    if (weight > limit) return Integer.MIN_VALUE; // prune: over limit
    if (node == n) return weight; // base: all nodes processed
    
    int maxLossIfSkip = remaining * maxNodeValue;
    if (weight + maxLossIfSkip <= bestSoFar) return Integer.MIN_VALUE; // prune: cannot improve
    
    // try taking or skipping
    int taken = search(node + 1, weight + nodeValue[node], remaining - 1);
    int skipped = search(node + 1, weight, remaining - 1);
    
    return Math.max(taken, skipped);
}
Divide and Conquer DP Optimization

If optimal indices move monotonically, narrow the candidate range recursively.

java
// Partition problem with monotone opt: dp[i] = min cost, tries k in [l, r]
// If opt[i] < opt[i+1] (monotone), search [opt[i], opt[i+1]] for opt[i+1]
void optimizeDC(int left, int right, int optL, int optR) {
    if (left > right) return;
    
    int mid = (left + right) / 2;
    int bestK = optL;
    long bestCost = Long.MAX_VALUE;
    
    for (int k = optL; k <= Math.min(mid, optR); k++) {
        long cost = dp[k] + cost(k + 1, mid);
        if (cost < bestCost) {
            bestCost = cost;
            bestK = k;
        }
    }
    dp[mid] = bestCost;
    
    optimizeDC(left, mid - 1, optL, bestK);
    optimizeDC(mid + 1, right, bestK, optR);
}

Worked Examples

Worked Example 1: House Robber III (Tree DP)

Problem: Rob houses on a tree; cannot rob adjacent nodes; maximize total.

java
class TreeNode { int val; TreeNode left, right; }

int[] rob(TreeNode node) {
    if (node == null) return new int[]{0, 0};
    
    int[] left = rob(node.left);
    int[] right = rob(node.right);
    
    int robbed = node.val + left[1] + right[1];
    int notRobbed = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
    
    return new int[]{robbed, notRobbed};
}

Result: Return max(root[0], root[1]).

Worked Example 2: Traveling Salesman (Bitmask DP)

Already shown in concept cluster. Key insight: visit cities in any order; use bitmask to track visited set.

Worked Example 3: Count Numbers with Digit Sum k (Digit DP)

java
int countNumbers(int n, int k) {
    String s = String.valueOf(n);
    int[][][] dp = new int[s.length() + 1][2][k + 1];
    for (int[][] plane : dp) for (int[] row : plane) Arrays.fill(row, -1);
    
    return helper(s, 0, 1, 0, k, dp);
}

int helper(String s, int pos, int tight, int sum, int k, int[][][] dp) {
    if (sum > k) return 0;
    if (pos == s.length()) return sum == k ? 1 : 0;
    
    if (dp[pos][tight][sum] != -1) return dp[pos][tight][sum];
    
    int limit = tight == 1 ? Character.getNumericValue(s.charAt(pos)) : 9;
    int result = 0;
    
    for (int digit = 0; digit <= limit; digit++) {
        result += helper(s, pos + 1, tight == 1 && digit == limit ? 1 : 0, sum + digit, k, dp);
    }
    
    return dp[pos][tight][sum] = result;
}

Solved Problems

Problem 1 (Easy): Maximum depth of N-ary tree. DFS each subtree; result is 1 + max child depth.

Problem 2 (Easy): Number of distinct islands. Mark visited; count connected components.

Problem 3 (Medium): Paint house with k colors such that no two adjacent houses have the same color. DP: dp[i][c] = min cost painting houses 0..i with house i color c.

Problem 4 (Medium): Count number of unique paths in a grid with obstacles. DP: dp[i][j] = paths to (i,j) from (0,0).

Problem 5 (Hard): Largest divisible subset. DP: for each number, find longest chain where each divides the next. Use LIS-like approach.


Recognition Guide

  • Tree DP: Input is tree; answer depends on subtree values.
  • Bitmask DP: n ≤ 20; subset, tour, or assignment relationship.
  • Digit DP: Count numbers with digit constraint up to bound.
  • Sparse memo: State space large but only subset reachable; use HashMap.
  • Divide-conquer DP: Monotone optimal indices allow bounded transition search.

Comparison Tables

Technique Use When State Size Typical Complexity
Tree DP Input is tree O(n) O(n)
Bitmask n ≤ 20, subsets matter O(2^n * n) O(2^n * n^2)
Digit DP Digit constraint, bound given O(len * 2 * sum) O(len * 10 * sum)
Sparse memo Reachable states << total O(reached) Varies
DC DP opt Monotone opt indices O(states) O(states log states)

Design and Decision Making

Tree DP: Return value per node for each case (taken, skipped, etc.). Combine child results bottom-up.

Bitmask DP: Only for small n. Ensure encoding is consistent (bit i = item i or bit i = visited i).

Digit DP: Always track tight flag. Process digits left to right.

Sparse memo: Use when state is multi-dimensional or dependent on input values (not just indices).


Practical Applications

  • Routing: TSP, vehicle routing
  • Assignments: job allocation under constraints
  • Combinatorics: digit constraints in number theory
  • Tree optimization: forest management, organization hierarchies

Failure Modes and Trade-offs

Bitmask overflow: Confirm n ≤ 20. For n=25, 2^n > 33 million states.

Digit DP tight flag wrong: Forgetting tight means allowing numbers > bound. Must track carefully.

Tree DP mixing cases: Ensure cases (e.g., taken vs skipped) are mutually exclusive and exhaustive.


Condensed Notes

  • Tree DP: dfs returns array of cases; combine child results.
  • Bitmask: dp[mask][last]; flip bits as you visit.
  • Digit DP: Process left-to-right; track tight(compare to bound).
  • Sparse: HashMap<State, Value> instead of array.
  • DC opt: Recurse on left/right with narrowed opt range.

Additional Problems

Easy: (1) Tree node count, (2) Max depth, (3) Balanced tree check, (4) Same tree, (5) Symmetric tree.

Medium: (1) LCA, (2) Paint house, (3) Russian doll envelopes (DP on 2D), (4) Distinct subsequences, (5) Count pairs divisible.

Hard: (1) Alien dictionary (topological DP), (2) Largest divisible subset, (3) Maximal network rank, (4) Number of ways to arrive destination (shortest path count), (5) Restore array from adjacent pairs.


Key Questions

  1. How do you handle tree DP on a binary tree? Return an array [case1, case2, ...]; combine child cases in parent.

  2. When is bitmask DP feasible? n ≤ 20 only; beyond that, state space is too large.

  3. What is the tight flag in digit DP? Tracks if prefix is still equal to upper bound; if not, later digits can be 0-9.

  4. How do you reconstruct a path in TSP? Store parent/previous state in a separate array during DP.

  5. When should you use sparse memoization? State space is multi-dimensional or dependent on values, not just indices.

  6. How do you know if monotone optimal indices hold? Prove it mathematically, or test on a few examples. Do not assume.

  7. What is the time complexity of TSP bitmask DP? O(n^2 * 2^n); reasonable up to n~20.

  8. How do you avoid leading zeros in digit DP? Add a started flag; if not started and digit=0, do not increment sum.

  9. Can you always optimize divide-conquer DP? Only if monotone opt holds. Verify before implementing.

  10. Why is tree DP efficient? Each node computed once; subtrees solved independently; O(n) total time.


Applied Project

Project: Plan an expedition visiting cities with supply constraints.

Features:

  • Start at city 0; visit all; return to 0
  • Carry limited supplies; refuel at cities
  • Minimize total cost (fuel + resupply)

Approach: Bitmask DP with extra dimension for fuel. State: dp[mask][last][fuel] = min cost to visit mask cities, end at last, have fuel remaining.

24: Enterprise / Architectural Patterns

Introduction and Context

Once you can solve problems correctly, the next challenge is structuring code so it is testable, maintainable, and scalable. Enterprise patterns are design solutions to recurring structural challenges: decoupling data access from business logic, managing dependencies, orchestrating complex workflows, and organizing systems at boundaries.

This chapter teaches six major patterns used in production systems: Dependency Injection (loose coupling), Repository (data abstraction), Unit of Work (transaction management), Specification (reusable queries), CQRS and Event Sourcing (read-write separation), and Domain-Driven Design (modeling by domain concepts). Then it covers three architectural styles that govern how systems are layered and organized.

The core skill is recognizing when a pattern solves a real structural problem versus when it adds unnecessary complexity.

Core Intuition and Mechanics

  • Dependency Injection: Objects receive their dependencies rather than creating them; enables testing and flexibility.
  • Repository: Hide data access details; expose domain-friendly query methods.
  • Unit of Work: Collect changes; commit or rollback atomically.
  • Specification: Express business rules as composable objects.
  • CQRS: Separate command (write) and query (read) models; independent scaling.
  • Domain-Driven Design: Structure code by domain concepts; hide implementation.
  • Layered Architecture: Input → Business Logic → Data → Persistence.
  • Hexagonal Architecture: Core domain at center; adapters on boundaries.
  • Clean Architecture: Innermost rule-driven; outermost implementation-driven.

Core Concepts and Subtopics

Concept Cluster: Decoupling and Dependency Management

Topics in this cluster:

  • 24.1 Dependency Injection: Constructor injection; Setter injection and interface injection; IoC container basics
  • 24.2 Repository Pattern: Data access abstraction; CRUD repository, aggregate repository, and ORM integration; Testability and boundary ownership
  • 24.3 Unit of Work: Transaction boundary; Change tracking; Commit and rollback
Dependency Injection

Hard dependency: class creates its own collaborator.

java
class OrderService {
    private UserRepository userRepository = new UserRepository(); // tight coupling
    
    void processOrder(Order order) {
        User user = userRepository.findById(order.userId);
        // ...
    }
}

Constructor Injection: collaborator passed in.

java
class OrderService {
    private final UserRepository userRepository;
    
    OrderService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

Setter Injection: set after construction.

java
class OrderService {
    private UserRepository userRepository;
    
    void setUserRepository(UserRepository repo) {
        this.userRepository = repo;
    }
}

Interface Injection: interface defines setter.

java
interface RepositoryInjector {
    void setUserRepository(UserRepository repo);
}

class OrderService implements RepositoryInjector {
    private UserRepository userRepository;
    public void setUserRepository(UserRepository repo) {
        this.userRepository = repo;
    }
}

IoC Container: Framework instantiates and wires dependencies.

java
// Spring example (pseudocode)
@Component
class OrderService {
    @Autowired UserRepository userRepository; // auto-injected
}

Benefit: Testing uses mock repositories; production uses real ones. Same code, different dependencies.

Repository Pattern

Abstraction hides data access.

java
interface UserRepository {
    User findById(String id);
    void save(User user);
    List<User> findByEmail(String email);
}

class InMemoryUserRepository implements UserRepository {
    private Map<String, User> users = new HashMap<>();
    public User findById(String id) { return users.get(id); }
    public void save(User user) { users.put(user.id, user); }
    public List<User> findByEmail(String email) {
        return users.values().stream().filter(u -> u.email.equals(email)).collect(toList());
    }
}

class JdbcUserRepository implements UserRepository {
    // same interface; implementation uses JDBC/SQL
}

Aggregate Repository: returns entire aggregate (Order with its Items).

java
interface OrderRepository {
    Order findById(String id); // returns Order + all Items
    void save(Order order); // saves Order and Items atomically
}
Unit of Work

Tracks changes; commits atomically.

java
class UnitOfWork {
    private Set<Entity> newEntities = new HashSet<>();
    private Set<Entity> dirtyEntities = new HashSet<>();
    private Set<Entity> removedEntities = new HashSet<>();
    
    void registerNew(Entity entity) { newEntities.add(entity); }
    void registerDirty(Entity entity) { dirtyEntities.add(entity); }
    void registerRemoved(Entity entity) { removedEntities.add(entity); }
    
    void commit() {
        insertNewEntities();
        updateDirtyEntities();
        deleteRemovedEntities();
    }
    
    void rollback() {
        newEntities.clear();
        dirtyEntities.clear();
        removedEntities.clear();
    }
}

Concept Cluster: Domain Modeling and Query Patterns

Topics in this cluster:

  • 24.4 Specification Pattern: Business rules composition; Reusable queries and predicate chaining; Repository plus specification collaboration
  • 24.5 CQRS and Event Sourcing: Command model; Query model; Read write separation; Event-driven CQRS; Event store, replay, audit trail, and snapshotting; Consistency and operational trade-offs
  • 24.6 Domain-Driven Design: Entity; Value object; Aggregate; Domain service; Repository in a DDD model; Bounded context
Specification Pattern

Encapsulate a business rule.

java
interface Specification<T> {
    boolean isSatisfiedBy(T t);
    Specification<T> and(Specification<T> other);
    Specification<T> or(Specification<T> other);
}

class IsActiveSpecification implements Specification<User> {
    public boolean isSatisfiedBy(User u) { return u.isActive; }
    public Specification<User> and(Specification<User> other) { /* */ }
}

class HasEmailDomainSpecification implements Specification<User> {
    private String domain;
    public boolean isSatisfiedBy(User u) { return u.email.endsWith("@" + domain); }
}

// Compose
Specification<User> spec = new IsActiveSpecification()
    .and(new HasEmailDomainSpecification("example.com"));

List<User> matching = users.stream().filter(spec::isSatisfiedBy).collect(toList());
CQRS

Separate command and query models.

java
// Command: writes; returns void or confirmation
interface OrderCommandService {
    void placeOrder(PlaceOrderCommand cmd);
}

// Query: reads; returns data
interface OrderQueryService {
    OrderDTO findOrder(String orderId);
    List<OrderSummaryDTO> listOrders(String userId);
}

// Command model: optimized for consistency, transactions
class OrderCommandServiceImpl {
    private OrderRepository orderRepo;
    public void placeOrder(PlaceOrderCommand cmd) {
        Order order = new Order(cmd.userId, cmd.items);
        orderRepo.save(order); // transactional write
    }
}

// Query model: optimized for read access (denormalized, cached)
class OrderQueryServiceImpl {
    private OrderViewRepository viewRepo; // pre-computed view
    public OrderDTO findOrder(String orderId) {
        return viewRepo.findById(orderId); // fast read
    }
}

Event Sourcing: Store events, replay to rebuild state.

java
interface EventStore {
    void append(Event event);
    List<Event> getEvents(String aggregateId);
}

class Order {
    private String id;
    private List<Item> items;
    
    void reconstruct(List<Event> events) {
        for (Event e : events) {
            if (e instanceof ItemAddedEvent) {
                items.add(((ItemAddedEvent) e).item);
            }
        }
    }
}
Domain-Driven Design

Entity: Identity over time.

java
class Order {
    private String id; // identity
    private List<Item> items;
    private OrderStatus status;
}

Value Object: No identity; immutable.

java
class Money {
    private final BigDecimal amount;
    private final String currency;
    // immutable; equals/hashCode based on amount and currency
}

Aggregate: Cluster of related entities + value objects.

java
class Order { // aggregate root
    private String id;
    private List<Item> items; // can only access via Order
    private Money total;
    
    void addItem(Item item) { items.add(item); } // enforce invariants
}

Domain Service: Stateless logic.

java
class PricingService {
    Money calculateTotal(Order order, Tax tax) { /* */ }
}

Bounded Context: Clear boundary around a domain model.

// e-commerce context: Order, Item, Product
// inventory context: Stock, SKU, Warehouse
// Each has its own Repository, entities, language
// Conversation at boundaries (context map)

Concept Cluster: Architecture Styles

Topics in this cluster:

  • 24.7 Architectural Styles: Layered Architecture; Hexagonal Architecture; Clean Architecture; Ports and adapters; Entities, use cases, interface adapters, and frameworks; Choosing architecture by team size, boundaries, and rate of change
Layered Architecture
┌─────────────────────────────┐
│  Presentation (REST, Web)   │
├─────────────────────────────┤
│  Application (Use cases)    │
├─────────────────────────────┤
│  Domain (Business rules)    │
├─────────────────────────────┤
│  Infrastructure (DB, Queue) │
└─────────────────────────────┘

Each layer depends only downward. Tight horizontally; promotes reuse.

Hexagonal Architecture (Ports & Adapters)
       ┌─────────────────────┐
       │   Adapter: REST     │
       │   Adapter: CLI      │
       │   Adapter: GraphQL  │
       └────────┬────────────┘
                │ ports
       ┌────────▼────────┐
       │  Core Domain    │
       └────────┬────────┘
                │ ports
       ┌────────▼────────────┐
       │ Adapter: DB         │
       │ Adapter: Queue      │
       │ Adapter: Cache      │
       └─────────────────────┘

Core domain isolated; adapters pluggable. Good for evolving requirements.

Clean Architecture

Concentric circles: entities (innermost, rules), use cases, interfaces, frameworks (outermost).

Benefit: Core rules independent of framework; test business logic without web server.


Worked Examples

Worked Example 1: Dependency Injection for Testability

java
interface UserRepository {
    User findById(String id);
}

class UserService {
    private final UserRepository repository;
    
    UserService(UserRepository repository) {
        this.repository = repository;
    }
    
    boolean isValidUser(String userId) {
        return repository.findById(userId) != null;
    }
}

// Test with mock
class TestUserService {
    @Test void testValidUser() {
        UserRepository mockRepo = userId -> userId.equals("123") ? new User("123") : null;
        UserService service = new UserService(mockRepo);
        assertTrue(service.isValidUser("123"));
    }
}

Worked Example 2: Repository Hides Implementation

java
interface PaymentRepository {
    void saveTransaction(Transaction txn);
    List<Transaction> findByUserId(String userId);
}

// In-memory: testing
class InMemoryPaymentRepository implements PaymentRepository {
    private Map<String, Transaction> txns = new HashMap<>();
    public void saveTransaction(Transaction txn) { txns.put(txn.id, txn); }
    public List<Transaction> findByUserId(String userId) { /* filter */ }
}

// Database: production
class JdbcPaymentRepository implements PaymentRepository {
    private DataSource ds;
    public void saveTransaction(Transaction txn) {
        String sql = "INSERT INTO transactions (id, userId, amount) VALUES (?, ?, ?)";
        try (Connection conn = ds.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, txn.id);
            stmt.setString(2, txn.userId);
            stmt.setBigDecimal(3, txn.amount);
            stmt.executeUpdate();
        }
    }
}

Worked Example 3: CQRS with Event Sourcing

java
// Event
class OrderPlacedEvent {
    String orderId;
    String userId;
    List<Item> items;
    Instant timestamp;
}

// Command handler
class PlaceOrderHandler {
    private EventStore eventStore;
    
    void handle(PlaceOrderCommand cmd) {
        Order order = new Order(cmd.userId, cmd.items);
        OrderPlacedEvent event = new OrderPlacedEvent(order.id, cmd.userId, cmd.items, Instant.now());
        eventStore.append(event);
    }
}

// Query side (eventually consistent)
class OrderViewUpdater {
    private OrderViewRepository viewRepo;
    
    void on(OrderPlacedEvent event) {
        OrderView view = new OrderView(event.orderId, event.userId, event.items);
        viewRepo.save(view);
    }
}

Solved Problems

Problem 1 (Easy): Implement a simple UserRepository interface with CRUD methods for both in-memory and JDBC implementations.

Problem 2 (Easy): Create a Specification for "active users with email domain @company.com" and compose two Specifications with and/or.

Problem 3 (Medium): Design a Unit of Work class tracking new, dirty, and removed entities; implement commit/rollback.

Problem 4 (Medium): Build a CQRS OrderService with separate command and query paths; simulate eventually-consistent view updates.

Problem 5 (Hard): Model an e-commerce domain with Order aggregate, Item value objects, OrderRepository, and InventoryService collaboration; include invariants.


Recognition Guide

Use these patterns when:

  • DI: Object creation logic is complex or tests need mocks.
  • Repository: Data source may change or multiple sources exist.
  • Unit of Work: Multiple entities must be saved atomically.
  • Specification: Business rules are reused across queries.
  • CQRS: Read and write load profiles differ significantly.
  • DDD: Domain is complex; language clarity matters.
  • Layered: Team is stable; domain is well-known.
  • Hexagonal: Requirements evolve; need pluggable adapters.
  • Clean: Long-term maintainability and testability are critical.

Avoid these patterns when:

  • Simplicity is paramount; monolithic scripts suffice.
  • Team is tiny; overhead outweighs benefits.
  • System is largely data-driven; few business rules exist.

Comparison Tables

Pattern Decoupling Testability Complexity Use When
DI High High Low Multiple implementations needed
Repository High High Medium Data source varies
Unit of Work Medium Medium Medium Complex transactional logic
Specification Medium High Medium Reusable query rules
CQRS High Medium High Read/write asymmetry
DDD Medium Medium High Complex domain

Design and Decision Making

When to apply patterns: Start with simplicity. Add patterns only when actual problems arise (tight coupling, hard to test, complex queries).

Pattern precedence: DI and Repository are foundational; others build on them.

Over-engineering: Do not force CQRS into a CRUD application. Do not apply DDD to data ETL.

Team fit: Choose patterns your team understands and will maintain consistently.


Practical Applications

  • E-commerce: DDD models complex orders; CQRS separates write (placing order) from read (order history).
  • Banking: Unit of Work ensures transactional consistency; Event Sourcing provides audit trail.
  • SaaS: Layered or Hexagonal architecture allows features to evolve independently.
  • Microservices: DDD defines bounded contexts; DI enables testing of service interactions.

Failure Modes and Trade-offs

Over-abstraction: Too many layers kill productivity. Keep the critical paths simple.

Eventual consistency: CQRS introduces lag between command and view; ensure business can tolerate it.

Repository leakage: Repository still exposes implementation details via inefficient queries. Keep contracts domain-focused.

Test brittleness: Over-mocking hides real integration issues. Blend unit and integration tests.


Condensed Notes

  • DI: Constructor > setter; enables testing and flexibility.
  • Repository: One interface, multiple implementations.
  • Unit of Work: Batch changes; commit atomically.
  • Specification: Composable business rules.
  • CQRS: Read and write separate; optimize independently.
  • DDD: Model by domain; enforce invariants in aggregates.
  • Layered: Simple; tight horizontal coupling.
  • Hexagonal: Ports and adapters; core independent.
  • Clean: Core rules innermost; frameworks outermost.

Additional Problems

Easy: (1) Implement CrudRepository, (2) Implement setter injection, (3) Create a Value Object for Money, (4) Write a simple Specification, (5) Design a basic Entity with identity.

Medium: (1) Build a Service using DI and Repository, (2) Implement Specification composition (and/or), (3) Design aggregate boundaries for a Blog (Post, Comment, Author), (4) Write a basic CQRS command handler, (5) Implement Unit of Work with in-memory store.

Hard: (1) Design a DDD model for a library system (Book, Author, Member, Lending), (2) Implement Event Sourcing for order state, (3) Build a CQRS OrderService with eventual consistency, (4) Design a Hexagonal architecture for a payment processor, (5) Model a bank account with invariants and transactions using DDD.


Key Questions

  1. Why is constructor injection preferred over setter injection? Immutability; all required dependencies known at construction time; avoids partially initialized objects.

  2. How does Repository pattern help testing? Tests can inject a mock repository; no real database needed.

  3. What is the difference between Repository and Data Mapper? Repository uses domain language; Mapper is lower-level, closer to schema.

  4. When should you use CQRS? Read and write loads are asymmetric, or eventual consistency is acceptable.

  5. What is eventual consistency in CQRS? Query updates lag behind commands; suitable for non-critical views.

  6. What is an aggregate in DDD? Cluster of entities and value objects with one root (aggregate root) controlling access.

  7. How do you enforce invariants in DDD? Put them in aggregate methods, not getters; validate before saving.

  8. What is a bounded context? Boundary around a domain model; each context has own language, entities, repositories.

  9. Why use event sourcing? Immutable audit trail; replay to debug; temporal queries.

  10. How do you choose between Layered, Hexagonal, and Clean? Layered for simplicity; Hexagonal for evolving adapters; Clean for testability and rule isolation.


Applied Project

Project: Build an Order Management System using multiple enterprise patterns.

Features:

  • Place order (command): validates, applies business rules, saves to event store
  • Query order (query): returns denormalized view
  • Inventory check (domain service): reserves stock atomically
  • Payment processing (external adapter): via pluggable payment gateway

Architecture: Hexagonal with DDD-modeled Order aggregate; DI for dependencies; Repository for persistence; Specification for filtering orders; CQRS-style command/query separation.

Testing: Unit test business rules (no DB); integration test with in-memory repository; contract test payment adapter.

===

These four chapters form a complete progression from DP foundations through enterprise architecture. Each chapter is self-contained while building toward mastery of both algorithmic and design problem-solving in Java.

25: Advanced Query, String, and Geometry Algorithms

Introduction and Context

Advanced query problems share one theme: solving many repeated subproblems efficiently by preprocessing or offline reordering. String algorithms share another: avoiding repeated character comparisons by reusing prefix knowledge or rolling hashes. Geometry adds a third: translating spatial intuition into stable integer comparisons and sweep-line ordering.

This chapter teaches how to choose range-query structures by constraints (Mo's algorithm, sparse tables, square-root decomposition), implement linear-time string matching (KMP, Z algorithm), use rolling hashes safely with collision handling, solve geometry problems with coordinate compression and sweep lines, and recognize when simpler approaches already solve the problem.

Learners often treat these as separate skills. The unifying principle is constraint-driven design: read the limits first, then pick the lightest correct tool.

Core Intuition and Mechanics

Range queries break when each query rescans. String matching breaks when each pattern shift restarts comparison. Geometry breaks when vague visual intuition replaces exact predicates.

The fixes are preprocessing, prefix reuse, and integer-based ordering. Advanced algorithms exploit structure in the problem to avoid quadratic or cubic loops. The key is knowing what structure exists and how to extract it.

Core Concepts and Subtopics

Concept Cluster: Range Query Selection by Constraints

Topics in this cluster:

  • 25.1 Advanced range and query techniques: Mo's algorithm; Square root decomposition; Sparse table review
  • 25.5 Choosing the right string-matching approach
Why This Matters

A sparse table answers static RMQ in O(1). Square-root decomposition balances point updates and range queries. Mo's algorithm reorders offline queries to minimize window movement. Choosing wrong means wrong limits or unnecessary complexity.

How It Works

Sparse table: preprocess powers of 2; query by combining two overlapping blocks for idempotent operations (min, max, gcd).

Square-root decomposition: split array into √n blocks; full blocks use block summaries, partial blocks scan.

Mo's algorithm: sort queries by left block and right endpoint; slide current window and maintain add/remove for that window.

Java Implementation
java
// Sparse table for RMQ
class SparseTable {
    int[][] st;
    int[] logs;
    
    SparseTable(int[] arr) {
        int n = arr.length;
        logs = new int[n + 1];
        for (int i = 2; i <= n; i++) {
            logs[i] = logs[i / 2] + 1;
        }
        st = new int[n][logs[n] + 1];
        for (int i = 0; i < n; i++) st[i][0] = arr[i];
        for (int j = 1; j <= logs[n]; j++) {
            for (int i = 0; i + (1 << j) <= n; i++) {
                st[i][j] = Math.min(st[i][j-1], st[i + (1 << (j-1))][j-1]);
            }
        }
    }
    
    int query(int l, int r) {
        int len = r - l + 1;
        int k = logs[len];
        return Math.min(st[l][k], st[r - (1 << k) + 1][k]);
    }
}

Concept Cluster: String Matching and Pattern Preprocessing

Topics in this cluster:

  • 25.2 KMP algorithm; Z algorithm; Prefix-function and Z-style matching intuition
  • 25.3 Rabin-Karp; Rolling Hash Pattern; Collision handling, verification, and memory trade-offs
  • 25.4 Suffix Array Pattern; Suffix Tree Pattern; Suffix array / suffix tree overview
  • 25.5 Trie-based string matching; String Matching Pattern
KMP vs Z vs Rolling Hash

KMP: preprocesses pattern LPS (longest proper prefix that is also suffix); avoids restarting text scan on mismatch. O(n+m) time, collision-free.

Z algorithm: precomputes Z[i] = length of longest substring starting at i that matches prefix. Elegant for pattern search via concatenation. O(n+m) time.

Rabin-Karp: treats substrings as polynomial hashes; rolls hash in O(1); verifies on match. Supports multiple patterns and multi-dimensional hashing.

Implementation
java
// KMP pattern search
class KMPMatcher {
    int[] lps;
    
    KMPMatcher(String pattern) {
        lps = new int[pattern.length()];
        for (int i = 1; i < pattern.length(); i++) {
            int j = lps[i - 1];
            while (j > 0 && pattern.charAt(i) != pattern.charAt(j)) {
                j = lps[j - 1];
            }
            if (pattern.charAt(i) == pattern.charAt(j)) lps[i] = j + 1;
        }
    }
    
    List<Integer> search(String text, String pattern) {
        List<Integer> matches = new ArrayList<>();
        int j = 0;
        for (int i = 0; i < text.length(); i++) {
            while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
                j = lps[j - 1];
            }
            if (text.charAt(i) == pattern.charAt(j)) j++;
            if (j == pattern.length()) {
                matches.add(i - j + 1);
                j = lps[j - 1];
            }
        }
        return matches;
    }
}

Concept Cluster: Geometry and Event Processing

Topics in this cluster:

  • 25.6 Geometry Pattern; Sweep Line Pattern; Sweep line overview; Line Sweep plus Events Pattern
  • 20.4 Coordinate compression and sorted events
  • 20.5 Area, intersection, and boundary-case reasoning; Numeric stability and overflow handling in Java
Core Ideas

Geometry problems become tractable when spatial relationships are replaced by integer predicates (orientation, overlap) and events are sorted. Sweep line processes events in order, maintaining active structures.

Coordinate compression maps sparse large coordinates to dense indices while preserving relative order.

Example: Largest Rectangle
java
// Largest rectangle in histogram
class LargestRectangle {
    int largestRectangle(int[] heights) {
        Stack<Integer> stack = new Stack<>();
        int max = 0;
        for (int i = 0; i < heights.length; i++) {
            while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) {
                int h = heights[stack.pop()];
                int w = stack.isEmpty() ? i : i - stack.peek() - 1;
                max = Math.max(max, h * w);
            }
            stack.push(i);
        }
        while (!stack.isEmpty()) {
            int h = heights[stack.pop()];
            int w = stack.isEmpty() ? heights.length : heights.length - stack.peek() - 1;
            max = Math.max(max, h * w);
        }
        return max;
    }
}

Worked Examples

Worked Example 1: Range Minimum Query with Mo's Algorithm

Problem: Answer many range-min queries on a static array.
Constraints: 10^5 elements, 10^5 queries offline.

Brute Force: O(q*n) — scan each interval.

Better Approach: Sort queries by left block and right endpoint. Slide window in sorted order.

Java Solution:

java
class MosAlgorithm {
    int[] arr;
    int blockSize;
    
    int[] solve(int[] arr, int[][] queries) {
        this.arr = arr;
        this.blockSize = (int) Math.sqrt(arr.length);
        Integer[] order = new Integer[queries.length];
        for (int i = 0; i < order.length; i++) order[i] = i;
        Arrays.sort(order, (a, b) -> {
            int blockA = queries[a][0] / blockSize;
            int blockB = queries[b][0] / blockSize;
            return blockA != blockB ? blockA - blockB : queries[a][1] - queries[b][1];
        });
        
        int[] result = new int[queries.length];
        int l = 0, r = -1, min = Integer.MAX_VALUE;
        for (int idx : order) {
            int ql = queries[idx][0], qr = queries[idx][1];
            while (r < qr) min = Math.min(min, arr[++r]);
            while (r > qr) r--;
            while (l < ql) l++;
            while (l > ql) min = Math.min(min, arr[--l]);
            result[idx] = min;
        }
        return result;
    }
}

Worked Example 2: Pattern Matching with KMP

Problem: Find all occurrences of pattern in text.

Brute Force: O((n-m)*m) — try every position.

Better: KMP with LPS array prevents restarting after mismatch.

Complexity: O(n+m) time, O(m) space. Dry Run: Pattern "aba" in "abacaba" → matches at indices 0 and 4.

Worked Example 3: Coordinate Compression for Interval Union

Problem: Find union area of many rectangles.

Brute Force: For each unit coordinate, track coverage.

Better: Compress y-coordinates; sweep line with segment tree.

Complexity: O((n+q) log n) where n = events, q = queries. Event processing is key.

Solved Problems

Problem 1 (Easy): Implement sparse table query.
Problem 2 (Easy): Find pattern with rolling hash (with verification).
Problem 3 (Medium): Answer multiple range-max queries with sqrt decomposition.
Problem 4 (Medium): Largest rectangle in histogram using monotonic stack.
Problem 5 (Hard): Count distinct elements in all subarrays using Mo's algorithm.

Recognition Guide

Use these techniques when:

  • Many queries on static/semi-static arrays → sparse table or sqrt decomposition.
  • One exact pattern search in large text → KMP or Z algorithm.
  • Multiple patterns of same length → rolling hash with verification.
  • Geometry with many events → coordinate compression and sweep line.
  • Offline queries can be reordered → Mo's algorithm.

Comparison Tables

Technique Time Space Best For
Sparse Table O(n log n) build, O(1) query O(n log n) Static RMQ
Sqrt Decomposition O(n√n) build, O(√n) op O(n) Point updates + range queries
Mo's Algorithm O((n+q)√n) O(n) Offline distinct/median queries
KMP O(n+m) O(m) Exact single pattern
Rabin-Karp O(n+m) avg O(m) Multiple patterns, rolling window
Sweep Line O(n log n) + structure O(n) Geometry, intervals

Design and Decision Making

Choose structures by constraint profile: if updates exist and RMQ is needed, sparse tables are ruled out. If the array is large and static, sparse table outpaces sqrt decomposition. If queries are offline, Mo's algorithm often beats specialized data structures on memory and constant factors.

For strings, prefer KMP or Z algorithm for deterministic correctness. Use rolling hash with verification when multiple patterns or substring equality is the bottleneck. Suffix arrays are the pragmatic choice for global substring queries, while suffix trees are conceptual power for a high implementation cost.

For geometry, always use integer arithmetic and predicates over floating-point formulas. Sweep line is the standard framework; choose the active structure (counter, set, Fenwick tree, segment tree) by query type.

Practical Applications

Range queries: interval statistics in logs, prefix-sum queries on time-series data, kth-smallest in subarrays.

String algorithms: text search engines, pattern matching in DNA sequences, plagiarism detection via rolling hashes.

Geometry: rectangle union area in map display, skyline algorithms in urban planning, event scheduling with overlapping meetings.

Failure Modes and Trade-offs

Sparse tables fail with any update. Mo's algorithm needs offline queries. KMP and Z require careful boundary handling. Rolling hash risks collisions unless verified. Geometry predicates overflow with large coordinates (use long). Sweep line is sensitive to event ordering at equal coordinates.

Condensed Notes

  • Sparse table: O(1) idempotent RMQ after O(n log n) preprocess.
  • KMP/Z: Avoid restarting comparisons via prefix preprocessing.
  • Rabin-Karp: Roll hashes in O(1); verify matches.
  • Mo's algorithm: Sort queries to minimize window moves.
  • Sweep line: Process events in sorted order; maintain active structure.
  • Coordinate compression: Map sparse coordinates to dense indices.

Additional Problems

15 problems across arrays, strings, and geometry at easy, medium, and hard levels covering range queries, pattern matching, string operations, and geometric calculations.

Key Questions

  1. When does sparse table outperform segment trees?
  2. Why does KMP avoid redundant comparisons?
  3. What does rolling hash collision handling do?
  4. How does Mo's algorithm reduce repeated work?
  5. What is coordinate compression and when is it needed?
  6. How does sweep line reduce dimension in geometry?
  7. When should you verify rolling hash matches?
  8. Can suffix arrays replace KMP for multiple patterns?
  9. What is the space-time trade-off in string matching?
  10. How do you handle numeric overflow in geometry?

Applied Project

Build a substring search engine that accepts multiple patterns and finds all non-overlapping occurrences in a document. Use rolling hash for fast window checks and KMP for verification. Add frequency ranking by suffix arrays. Test on real text corpora and measure latency versus accuracy trade-offs.


26: Advanced Trees & Paths

Introduction and Context

Once tree problems involve many queries or updates, rerunning DFS for each question becomes impractical. This chapter teaches how to preprocess trees into array indices and segment-tree queries so subtree aggregates and path problems run in logarithmic time.

The core patterns are Euler-tour flattening for subtrees, binary lifting for ancestors, and heavy-light decomposition for arbitrary node-to-node paths. Each transforms a tree question into a range query on a flattened array.

Learners often memorize these techniques without understanding when simpler approaches already work. This chapter emphasizes that HLD is engineering-heavy and only necessary when path queries dominate and updates must be online.

Core Intuition and Mechanics

Trees stop being simple when the question is not a single traversal. Many queries on one static tree demand preprocessing. Ancestors are found via powers-of-two jumps. Subtrees become contiguous segments. Long paths break into heavy chains. Each transformation enables a range-query structure underneath.

Core Concepts and Subtopics

Concept Cluster: Ancestor and Ancestry Queries

Topics in this cluster:

  • 26.1 Lowest common ancestor; Lowest Common Ancestor Pattern; Lowest Common Ancestor Pattern revisited with preprocessing
  • 26.2 Binary lifting; Euler tour; Euler tour flattening for subtree queries
LCA with Binary Lifting

Every node stores 2^k-th ancestors. To find LCA, align depths with binary jumps, then simultaneously jump until ancestors diverge.

Euler Tour Flattening

Assign each node an entry time in DFS order. Subtree of node u becomes interval [tin[u], tout[u]] in Euler order. Enables Fenwick or segment tree for subtree sums.

Java Implementation
java
class TreePreprocessor {
    List<Integer>[] adj;
    int[] tin, depth;
    int[][] up;
    int timer = 0;
    
    void preprocess(int n) {
        adj = new List[n];
        for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
        tin = new int[n];
        depth = new int[n];
        up = new int[n][20]; // 2^20 > 10^6
    }
    
    void dfs(int u, int p) {
        tin[u] = timer++;
        up[u][0] = p;
        for (int i = 1; i < 20; i++) {
            up[u][i] = up[up[u][i-1]][i-1];
        }
        for (int v : adj[u]) {
            if (v != p) {
                depth[v] = depth[u] + 1;
                dfs(v, u);
            }
        }
    }
    
    int lca(int u, int v) {
        if (depth[u] < depth[v]) { int t = u; u = v; v = t; }
        for (int i = 19; i >= 0; i--) {
            if (depth[up[u][i]] >= depth[v]) u = up[u][i];
        }
        if (u == v) return u;
        for (int i = 19; i >= 0; i--) {
            if (up[u][i] != up[v][i]) {
                u = up[u][i];
                v = up[v][i];
            }
        }
        return up[u][0];
    }
}

Concept Cluster: Tree Flattening and Path Queries

Topics in this cluster:

  • 26.3 Heavy Light Decomposition; Segment tree plus tree path combinations
  • 26.4 Tree diameter; Path queries versus subtree queries
  • 26.5 Tree query problem patterns; Path vs subtree queries; Trade-offs versus simpler DFS-based approaches
  • 26.6 Advanced tree toolkit design and reusable query templates
Heavy-Light Decomposition

For each node, choose one heavy child (largest subtree). Heavy edges form chains. Path from u to v follows at most O(log n) chains.

Each chain is linearized. A segment tree on flattened chains answers path aggregates efficiently.

When to Use HLD

Use HLD only when: path queries and updates are online, the query count is large, and LCA + binary lifting is insufficient for the aggregation.

Simpler Alternatives

For subtree queries, Euler tour + Fenwick tree is sufficient.
For static path sums, LCA + prefix sums from root avoid HLD entirely.

Path vs Subtree Recognition
  • Subtree query: "aggregate all descendants of node u" → Euler tour.
  • Root-to-node path: "aggregate from root to u" → prefix array.
  • Node-to-node path: "aggregate between u and v" → LCA + two root-to-node queries.
  • Many path updates + queries: HLD + segment tree.

Worked Examples

Worked Example 1: Subtree Sum with Euler Tour and Fenwick Tree

Problem: Answer subtree-sum queries and handle point updates.

Brute Force: O(subtree size) per query.

Better: Euler tour maps subtree to interval; Fenwick tree answers range sums in O(log n).

Java Solution:

java
class FenwickTree {
    long[] tree;
    FenwickTree(int n) { tree = new long[n + 1]; }
    void update(int i, long delta) {
        for (i++; i < tree.length; i += i & -i) tree[i] += delta;
    }
    long query(int i) {
        long s = 0;
        for (i++; i > 0; i -= i & -i) s += tree[i];
        return s;
    }
}

Worked Example 2: LCA and Distance

Problem: Find distance between any two nodes.

Solution: LCA with binary lifting; distance = depth[u] + depth[v] - 2*depth[lca].

Complexity: O(log n) per query after O(n log n) preprocess.

Worked Example 3: Tree Diameter

Problem: Find the longest path in the tree.

Algorithm: BFS from any node to find farthest node A; BFS from A to find farthest B. Distance A-B is diameter.

Complexity: O(n) time, O(n) space.

Solved Problems

Problem 1 (Easy): Find depth of all nodes.
Problem 2 (Easy): Find LCA for given pairs.
Problem 3 (Medium): Subtree sum with point updates.
Problem 4 (Medium): Distance between two nodes.
Problem 5 (Hard): Path maximum with online updates (HLD + segment tree).

Recognition Guide

Use these techniques when:

  • Many LCA or ancestor queries → binary lifting.
  • Subtree aggregates with updates → Euler tour + Fenwick/segment tree.
  • Path queries without updates → LCA + prefix sums.
  • Path queries with online updates → HLD + segment tree.
  • Longest path in tree → two-pass BFS for diameter.
  • Local tree reasoning → simple DFS (do not over-engineer).

Comparison Tables

Method LCA Time Space Supports Updates
Binary Lifting O(log n) O(n log n) Query only
Euler Tour N/A O(n) Yes (via structure)
HLD O(log^2 n) O(n log n) Yes (path + updates)

Design and Decision Making

Binary lifting is lightweight and sufficient for ancestor queries. Euler tour flattens subtrees naturally into array queries. HLD is complex and should be avoided if simpler approaches already pass constraints.

Always ask: is the query about ancestry, subtrees, or paths? Each has a canonical solution. Do not force HLD when Euler tour + Fenwick tree suffices. Do not add segment trees when binary lifting already solves the problem.

Practical Applications

Ancestry queries: organizational hierarchies, file system directories, genealogical trees.

Subtree aggregates: team budgets, subordinate counts, inventory in warehouses.

Path queries: network routing, communication latency in mesh topologies, dependency resolution in build systems.

Failure Modes and Trade-offs

Binary lifting uses O(n log n) memory—acceptable only for moderate n (~10^5). HLD is the slowest to code and debug among tree techniques. Euler tour requires careful indexing. Updates break sparse tables but work with Fenwick/segment trees.

Condensed Notes

  • LCA binary lifting: Store 2^k-th ancestors; jump in O(log n).
  • Euler tour: Map subtree [tin, tout] to array; use Fenwick/segment tree.
  • HLD: Heavy chains flatten to array; path = O(log n) segments.
  • Tree diameter: Two BFS finds longest path end-to-end.
  • Rule: Subtree → Euler tour. Paths without updates → LCA. Paths with updates → HLD.

Additional Problems

15 problems covering LCA, subtree queries, path aggregates, tree diameters, and advanced tree combinations.

Key Questions

  1. What does binary lifting store and how does it find LCA?
  2. How does Euler tour make subtrees contiguous?
  3. When is HLD justified instead of simpler approaches?
  4. What is tree diameter and how is it found efficiently?
  5. How do you combine LCA with prefix sums for path queries?
  6. What is the memory cost of binary lifting?
  7. Can Fenwick trees replace segment trees in Euler-tour queries?
  8. Why does HLD require multiple chain heads?
  9. How do you handle edge weights in tree paths?
  10. When should you skip advanced tree structures?

Applied Project

Build a census system for a large organization. Query ancestral manager chains, count subordinates in departments (subtree aggregates), and compute paths between any two employees. Implement binary lifting for ancestor queries and Euler tour for subtree aggregates. Measure query latency and compare with brute-force DFS on small inputs.


27: Concurrency, Resilience Patterns, and Distributed Systems Design

Introduction and Context

Production systems run across multiple threads and machines under partial failures. This chapter teaches proven patterns for managing concurrency (thread pools, producer-consumer), surviving failures (circuit breakers, retries, bulkheads), and coordinating work across services (sagas, microservices boundaries).

The core skill is matching the pattern to the failure mode: what is breaking and why? Then apply the minimal fix. Overengineering concurrency early is a common mistake. Start with understanding the bottleneck.

Core Intuition and Mechanics

Concurrency problems arise when multiple threads compete for resources or when services depend on each other over the network. Resilience problems arise when failures (latency, timeouts, crashes) are inevitable and must be contained.

The mental model: threads need coordination primitives, failures need circuit breakers and retries, and distributed work needs sagas. Each pattern solves one specific failure mode without trying to fix all problems at once.

Core Concepts and Subtopics

Concept Cluster: Concurrent Resource Management

Topics in this cluster:

  • 27.1 Thread Pool Pattern; Worker threads and task queue; Resource reuse
  • 27.2 Producer Consumer Pattern; Bounded buffer and blocking queue; Backpressure and throughput tuning
Thread Pool Pattern

Reuse threads instead of creating one per request. A fixed thread pool with a bounded queue prevents unbounded thread creation and memory exhaustion.

java
ExecutorService pool = Executors.newFixedThreadPool(8);
for (Task task : tasks) {
    pool.submit(() -> {
        try { task.execute(); } 
        catch (Exception e) { logError(e); }
    });
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
Producer-Consumer Pattern

A blocking queue coordinates between producers (filling) and consumers (draining). Backpressure—when the queue is full, producers block—prevents the consumer from being overwhelmed.

java
BlockingQueue<Item> queue = new LinkedBlockingQueue<>(100);
// Producer thread
queue.put(item); // blocks if queue is full

// Consumer thread
Item item = queue.take(); // blocks if queue is empty

Concept Cluster: Failure Containment and Recovery

Topics in this cluster:

  • 27.3 Circuit Breaker Pattern; Failure threshold and open, half-open, closed states
  • 27.4 Retry Pattern with fixed retry and exponential backoff; Idempotency and duplicate-safe retries
  • 27.5 Bulkhead Pattern and resource isolation; Fallback logic and failure containment
Circuit Breaker

Tracks error rates. If failures exceed a threshold, the circuit opens and subsequent calls fail immediately without waiting. After a cooldown, it tries a probe. If that succeeds, it closes; otherwise, it opens again.

java
// Pseudocode structure
class CircuitBreaker {
    enum State { CLOSED, OPEN, HALF_OPEN }
    State state = CLOSED;
    int failureCount = 0;
    long lastFailureTime = 0;
    int threshold = 5;
    long timeout = 60_000;
    
    <T> T call(Supplier<T> fn) throws Exception {
        if (state == OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > timeout) {
                state = HALF_OPEN;
            } else {
                throw new CircuitBreakerOpenException();
            }
        }
        try {
            T result = fn.get();
            if (state == HALF_OPEN) {
                state = CLOSED;
                failureCount = 0;
            }
            return result;
        } catch (Exception e) {
            failureCount++;
            lastFailureTime = System.currentTimeMillis();
            if (failureCount >= threshold) state = OPEN;
            throw e;
        }
    }
}
Retry with Exponential Backoff

For transient failures, retry after a short delay. Double the delay each time; add jitter to prevent retry storms.

java
int attempt = 0, maxAttempts = 5;
long baseDelay = 100; // ms
while (attempt < maxAttempts) {
    try {
        return remoteCall();
    } catch (TransientException e) {
        attempt++;
        long delay = baseDelay * (1L << attempt) + random.nextLong(baseDelay);
        Thread.sleep(delay);
    }
}
throw new PermanentFailureException();
Bulkhead Pattern

Isolate resources so one failing service does not exhaust resources shared with others. Use separate thread pools per dependency.

java
ExecutorService paymentPool = Executors.newFixedThreadPool(4);
ExecutorService inventoryPool = Executors.newFixedThreadPool(4);
// Payment calls use paymentPool; inventory calls use inventoryPool

Concept Cluster: Distributed Coordination

Topics in this cluster:

  • 27.6 Saga Pattern; Choreography saga; Orchestration saga; Compensation actions; Long-running workflows; Choosing saga versus stronger consistency models
  • 27.7 Microservices patterns: API Gateway; Service Discovery; Distributed Config; Sidecar Pattern; Strangler Fig Pattern; Service boundaries and migration strategy
Saga Pattern

A saga is a sequence of local transactions across services. If a step fails, compensation transactions undo earlier steps.

Choreography saga: Each service listens for events and reacts.
Orchestration saga: A central coordinator calls each step.

java
// Orchestration: saga coordinator
class OrderSaga {
    void executeOrder(Order order) throws Exception {
        try {
            paymentService.charge(order.userId, order.amount);
            inventoryService.reserve(order.items);
            shippingService.schedule(order.shipToAddress);
        } catch (Exception e) {
            inventoryService.release(order.items);
            paymentService.refund(order.userId, order.amount);
            throw e;
        }
    }
}
Microservices Boundaries

Split services by business capability, not by technical layer. Own data exclusively. Communicate via APIs (sync) or events (async).

Worked Examples

Worked Example 1: Thread Pool with Bounded Queue

Problem: Process many tasks concurrently without unbounded thread creation.

Solution: Fixed thread pool with queue. Producer blocks when queue fills.

Dry Run: 1000 tasks, 8 threads, queue size 100. Threads drain tasks at ~10 tasks/thread/second. Queue fills, producers wait.

Worked Example 2: Circuit Breaker Preventing Cascades

Problem: One slow downstream service causes all upstream clients to hang.

Solution: Circuit breaker opens after 5 consecutive failures, fails fast for 60 seconds.

Complexity: O(1) per call; overhead is tracking state.

Worked Example 3: Saga Coordinating Multi-Service Order

Problem: Place an order across payment, inventory, and shipping services atomically.

Solution: Orchestration saga. If any step fails, compensate earlier steps.

Complexity: O(number of saga steps) for orchestration overhead.

Solved Problems

Problem 1 (Easy): Implement a basic thread pool executor.
Problem 2 (Easy): Consumer blocks when queue is empty; producer blocks when queue is full.
Problem 3 (Medium): Circuit breaker transitions between CLOSED, OPEN, and HALF_OPEN states.
Problem 4 (Medium): Retry with exponential backoff and jitter.
Problem 5 (Hard): Orchestration saga with compensation transactions.

Recognition Guide

Use these patterns when:

  • Many concurrent requests → thread pool with bounded queue.
  • One service is slower → producer-consumer with backpressure.
  • Cascading failures → circuit breaker and timeout.
  • Transient failures → retry with exponential backoff.
  • One slow dependency starves others → bulkhead (separate thread pool).
  • Multi-service atomic action → saga with compensation.
  • Service instances change → service discovery.

Comparison Tables

Pattern Problem Overhead Complexity
Thread Pool Unbounded threads Low Low
Circuit Breaker Cascading failures Medium Medium
Retry + Backoff Transient failures Low Low
Bulkhead Resource starvation Medium Medium
Saga Multi-service atomicity High High

Design and Decision Making

Start simple: thread pools and bounded queues handle most concurrency. Add circuit breakers and retries when you see cascading failures in production. Use bulkheads for critical dependencies. Use sagas only when you truly need multi-service transactional semantics and eventual consistency is acceptable.

Avoid premature resilience patterns. Measure first. Do not add circuit breakers to every call—only to expensive or unreliable ones.

Practical Applications

Thread pools: web servers handling many requests, batch processors, parallel downloads.

Circuit breakers: payment gateways, third-party API calls, database connections.

Sagas: e-commerce order processing, booking systems (flights + hotels), fund transfers.

Bulkheads: microservices isolation, critical path protection.

Failure Modes and Trade-offs

Thread pools require careful tuning; too small and latency rises; too large and context-switching dominates. Circuit breakers delay recovery if the timeout is too long. Retries can amplify load if not rate-limited. Sagas sacrifice strong consistency for availability—eventual consistency means temporary inconsistency is visible.

Condensed Notes

  • Thread pool: Reuse threads; bounded queue prevents OOM.
  • Producer-consumer: Blocking queue with backpressure.
  • Circuit breaker: Fail fast when error rate exceeds threshold.
  • Retry + backoff: Exponential delay with jitter.
  • Bulkhead: Separate thread pools per dependency.
  • Saga: Multi-service transaction with compensation.

Additional Problems

15 problems covering concurrency, failure recovery, and distributed coordination.

Key Questions

  1. Why use a thread pool instead of creating threads on demand?
  2. How does backpressure prevent consumer overwhelm?
  3. What are the three states of a circuit breaker?
  4. Why add jitter to exponential backoff?
  5. How does a bulkhead prevent cascading failures?
  6. What is the difference between choreography and orchestration sagas?
  7. When is eventual consistency acceptable?
  8. What is idempotency and why does it matter for retries?
  9. How do you measure circuit breaker thresholds?
  10. When should you use sagas versus distributed transactions?

Applied Project

Build a resilient order processing system that calls payment, inventory, and shipping services. Implement thread pools, circuit breakers, retries with backoff, and a saga coordinator. Simulate failures (latency spikes, service crashes) and measure system behavior (cascade prevention, recovery time, order success rate).


28: Hybrid Problem Solving, UI Architecture, and Mastery

Introduction and Context

This final chapter synthesizes pattern recognition across domains. Hard problems rarely fit one template. They combine array patterns, graph traversal, DP optimization, and game-state reasoning into composable solutions. UI architecture completes the picture: how do patterns apply beyond backend algorithms?

The central theme is recognizing multi-pattern problems, avoiding anti-patterns (overengineering, pattern misidentification), and building communicable solutions. Mastery means knowing not just what patterns exist, but when simpler approaches suffice and when composition is justified.

Core Intuition and Mechanics

Hybrid problems reveal themselves through brute-force bottlenecks. One pattern fixes the first bottleneck; a second pattern fixes the next. Good solutions are transparent: each layer has one responsibility.

UI patterns teach that backend patterns apply to frontend architecture. Component composition, state management (Redux), and unidirectional data flow bring the same rigor to user interfaces as algorithms bring to backend processing.

Core Concepts and Subtopics

Concept Cluster: Multi-Pattern Problem Composition

Topics in this cluster:

  • 28.1 Expert Hybrid Pattern; Multi-Pattern Problems; Pattern Combinations across arrays, graphs, and DP
  • 28.2 Next greater element; Histogram problems; Monotonic structures and interval patterns; Merge intervals
  • 28.6 Pattern Combinations; Factory plus Strategy; Builder plus Prototype; Observer plus Mediator; Decorator plus Composite
  • 28.9 Pattern identification; Scenario-based questions; Refactoring questions; Low-level design problems; Pattern selection heuristics and trade-off evaluation
Recognizing Hybrid Problems

Brute force first: Write the direct solution and identify exactly what is too slow.

Isolate bottlenecks: Is it repeated scanning? Exponential search space? Incorrect state representation?

Choose patterns deliberately: One pattern should fix each bottleneck. If two patterns solve the same problem, you are overcomplicating.

Common Combinations
  • Prefix sums + monotonic queue: Transform intervals into difference arrays; deque maintains best candidate starts.
  • Graph + DP: State includes both node and a discrete dimension (edges used, mask visited).
  • Segment tree + lazy propagation: Range updates and range queries on compressed coordinates.
  • DFS + hashing: Detect patterns in recursion tree via rolling hashes.
Avoiding Anti-Patterns
  • Pattern misidentification: Forcing a familiar pattern onto a problem it does not fit.
  • Premature optimization: Optimizing before the bottleneck is proven.
  • Overcomposition: Adding a second pattern when the first already solves it.
  • Lack of explanation: The solution works but the reasoning is unclear.

Concept Cluster: UI Architecture Patterns

Topics in this cluster:

  • 28.4 MVC Pattern and request flow; MVP Pattern and presenter responsibility; MVVM Pattern and data binding; Component Pattern and reusable components; Props, inputs, and state management; Choosing a UI pattern by framework constraints
  • 28.5 Flux and Redux Pattern; Store, actions, and reducers; Unidirectional data flow; Side effects and async coordination; UI composition with components; When centralized state is unnecessary
MVC: Model-View-Controller

Model holds data; View displays it; Controller handles input and updates Model.

java
// MVC: Controller routes input to model
class OrderController {
    private OrderModel model;
    
    void handleCheckout(CheckoutRequest req) {
        Order order = model.createOrder(req);
        model.processPayment(order);
        view.showConfirmation(order);
    }
}

Pros: Clear separation of concerns. Cons: Controller can grow large; view and model are often coupled.

Redux/Flux: Centralized State Management

Single store holds all application state. Actions describe what happened. Reducers compute new state from old state and action.

java
// Redux: Actions and reducers
class AppState {
    List<Order> orders;
    User currentUser;
}

AppState appReducer(AppState state, Action action) {
    if (action instanceof CreateOrderAction) {
        Order newOrder = ((CreateOrderAction)action).order;
        state.orders.add(newOrder);
    }
    return state;
}

Pros: Predictable state changes; time-travel debugging. Cons: Verbose; every change requires an action.

Component Pattern

Reusable UI building blocks. Props flow down; events flow up. State belongs to a parent unless only one component needs it.

java
// Component: reusable, composable
class OrderCard extends UIComponent {
    Order order;
    Callback onCancel;
    
    void render() {
        display(order.id, order.amount);
        button("Cancel", () -> onCancel.run());
    }
}

Concept Cluster: Game Theory and Randomization

Topics in this cluster:

  • 28.3 Game Theory Pattern; Randomized Algorithm Pattern revisited; Winning states, losing states, and turn-based analysis; Expected behavior versus worst-case guarantees; Adversarial testing and counterexample design; When randomness simplifies an otherwise hard strategy
Winning and Losing States

State is winning if the current player can move to a losing state. State is losing if all moves lead to winning states for the opponent.

java
// Game DP: is position winning for current player?
boolean isWinning(int[] piles) {
    Map<String, Boolean> memo = new HashMap<>();
    return canWin(piles, memo);
}

boolean canWin(int[] piles, Map<String, Boolean> memo) {
    String key = Arrays.toString(piles);
    if (memo.containsKey(key)) return memo.get(key);
    
    for (int i = 0; i < piles.length; i++) {
        if (piles[i] > 0) {
            piles[i]--;
            if (!canWin(piles, memo)) {
                piles[i]++;
                memo.put(key, true);
                return true;
            }
            piles[i]++;
        }
    }
    memo.put(key, false);
    return false;
}
Randomization Benefits

Randomized pivot selection in quicksort makes O(n log n) expected time even on adversarial inputs. Randomization simplifies where deterministic case analysis is complex.

Worked Examples

Worked Example 1: Next Greater Element (Monotonic Stack)

Problem: For each element, find the next element to the right that is greater.

Brute Force: O(n^2) nested scan.

Better: Monotonic decreasing stack stores candidates. Pop when a larger element arrives.

java
int[] nextGreater(int[] arr) {
    int[] result = new int[arr.length];
    Stack<Integer> stack = new Stack<>();
    for (int i = arr.length - 1; i >= 0; i--) {
        while (!stack.isEmpty() && stack.peek() <= arr[i]) stack.pop();
        result[i] = stack.isEmpty() ? -1 : stack.peek();
        stack.push(arr[i]);
    }
    return result;
}

Complexity: O(n) time, O(n) space.

Worked Example 2: Trapping Rain Water (Prefix + Monotonic Deque)

Problem: Calculate water trapped between elevation bars.

Insight: Water at position i is bounded by max height to left and max height to right.

Hybrid: Precompute left/right maxima (prefix idea); or use monotonic decreasing stack to process bar pairs.

Complexity: O(n) time.

Worked Example 3: Largest Rectangle in Histogram (Monotonic Stack)

Problem: Find the largest rectangle in a histogram.

Idea: For each bar, find how far left and right it extends without a shorter bar.

Solution: Monotonic stack tracks increasing heights; when a shorter bar arrives, pop taller ones and compute areas.

Complexity: O(n) time.

Solved Problems

Problem 1 (Easy): Identify which pattern applies: brute force, prefix sum, monotonic stack, or DP.
Problem 2 (Easy): Next greater element using monotonic stack.
Problem 3 (Medium): Trapping rain water with two-pointer or monotonic deque.
Problem 4 (Medium): UI state management: given an action stream, compute final state.
Problem 5 (Hard): Multi-pattern problem combining prefix compression, graph traversal, and DP optimization.

Recognition Guide

Recognize these hybrid signals:

  • One pattern alone is too slow → add a second.
  • State includes multiple independent dimensions → DP over one, search over another.
  • Geometry + ordering → sweep line + active structure.
  • Graph + optimization → BFS + DP or state compression.
  • Game logic + randomization → memoized game tree + adversarial testing.

Comparison Tables

Scenario Primary Pattern Secondary Pattern Why
Next greater Monotonic stack None Stack alone O(n)
Largest rectangle Monotonic stack Prefix heights Heights precomputed; stack processes
Trapping water Prefix sums Two pointers Or: monotonic stack
Path in grid with stops BFS DP State = (node, stops_used)
Heavy graph + many queries Graph traversal Segment tree Flatten via DFS; query via tree

Design and Decision Making

Start hybrid design from brute force and bottlenecks, not from pattern names. Ask what is slow: scanning, searching, state explosion? Pick the simplest fix. Do not add patterns unless the constraints rule out the simpler approach.

For UI, choose MVC for simple apps, Redux for apps with complex state shared across many components. Avoid over-centralizing state when one component owns it.

Practical Applications

Hybrid arrays/graphs: Shortest path with forbidden edges; flow with capacities.

Hybrid DP: Knapsack with item-rarity scoring; sequence optimization with edit-distance variants.

UI architecture: E-commerce checkout (multiple steps, shared cart state); real-time dashboards (Redux with async effects).

Failure Modes and Trade-offs

Over-hybridization creates unmaintainable solutions. Weak composition (patterns that interfere) is harder to debug than simple solutions. UI state centralization (Redux) adds verbosity but improves predictability. Randomization trades worst-case guarantees for expected performance; some problems require derandomization if worst-case matters.

Condensed Notes

  • Hybrid workflow: Brute force → identify bottleneck → add one pattern → test → add second if needed.
  • Monotonic stack: O(n) for next-greater, largest rectangle, trapping water.
  • MVC: Simple apps. Redux: complex shared state.
  • Game DP: Winning/losing states via memoization.
  • Adversarial testing: Build counterexamples to weak heuristics.
  • Avoid: pattern names as goal; complexity without bottleneck proof.

Additional Problems

15 problems mixing arrays, graphs, DP, games, and UI state management across easy, medium, and hard levels.

Key Questions

  1. What is the brute-force baseline and its bottleneck?
  2. Which pattern removes that bottleneck?
  3. After first optimization, what is the next bottleneck?
  4. Can one pattern solve it, or do you need composition?
  5. When is MVC sufficient and when does Redux help?
  6. How do you test hybrid solutions without confusion?
  7. What is the difference between choreography and orchestration in UI?
  8. When is centralized state management overkill?
  9. How do you identify anti-patterns in your solution?
  10. What is the simplest correct approach that passes constraints?

Applied Project

Build a stock portfolio tracker combining backend hybrid algorithms and frontend UI patterns. Backend: compute most profitable trades (DP), rank by volatility (heap + sorting), detect pump-and-dump patterns (graph cycles + hashing). Frontend: display portfolio in MVC (simple view) or Redux (complex filters and sorting). Implement component reusability and time-travel debugging. Test responsiveness under real-time price updates.