Skip to lesson

Hard problems rarely require a brand-new algorithm you have never seen. Almost always, a hard problem is two familiar medium patterns snapped together — an outer search or reduction paired with an inner linear scan.

Six problems that combine two patterns

Study how each of these six classic hard problems splits into Pattern A plus Pattern B.

  1. Trapping Rain Water (1 ≤ n ≤ 2 × 10⁴): Water above bar i is max(0, min(leftMax[i], rightMax[i]) - h[i]). Combines Prefix/Suffix Maxima + Opposite-End Two Pointers (O(n) time, O(1) space).
  2. Minimum Window Substring (1 ≤ |s|, |t| ≤ 10⁵): Shortest substring of s containing all characters of t (with multiplicity). Combines Variable Sliding Window + Frequency Hashing (have == need counter) (O(|s| + |t|) time, O(1) ASCII space).
  3. Split Array Largest Sum (1 ≤ k ≤ n ≤ 1000): Split nums into k non-empty contiguous subarrays to minimize the largest subarray sum. Combines Binary Search on the Answer ([max(nums), sum(nums)]) + Greedy Prefix Partitioning (O(n log(Σ Aᵢ)) time, O(1) space).
  4. Subarrays with K Different Integers (1 ≤ k ≤ n ≤ 2 × 10⁴): Exact K breaks simple sliding window monotonicity, so combine Exact-to-AtMost Reduction (atMost(K) - atMost(K - 1)) + Variable Sliding Window + Frequency Map (O(n) time).
  5. K-th Smallest Pair Distance (2 ≤ n ≤ 10⁴): Combines Sorting + Binary Search on the Answer ([0, max - min]) + Same-Direction Two Pointers counting pairs with a[right] - a[left] <= mid (O(n log n + n log W) time).
  6. Palindrome Partitioning (1 ≤ |s| ≤ 16): Combines Inward Two-Pointer Palindrome Check + Choose-Explore-Unchoose Backtracking (O(n · 2ⁿ) time).

Model solutions for three of the problems

These solutions cover problems 1, 4 and 5. Problem 1 is solved three ways, from brute force to optimal.

Example 1 · Brute force, Problem 1: scan left and right for every bar (O(n²) time, O(1) space)

TrapWaterBrute.javaJava
public class TrapWaterBrute {    public static int trap(int[] height) {        int water = 0;        for (int i = 0; i < height.length; i++) {            int leftMax = 0;            int rightMax = 0;            for (int j = 0; j <= i; j++) {                leftMax = Math.max(leftMax, height[j]);            }            for (int j = i; j < height.length; j++) {                rightMax = Math.max(rightMax, height[j]);            }            water += Math.min(leftMax, rightMax) - height[i];        }        return water;    }
    public static void main(String[] args) {        System.out.println(trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));        System.out.println(trap(new int[]{4, 2, 0, 3, 2, 5}));    }}
Output
6
9

What this code does

  • For each bar the two inner loops find the tallest bar on its left and on its right. The water above the bar is the smaller of the two, minus its own height.
  • It needs no extra memory, but every bar rescans the whole array, which is too slow for n = 20 000.

Example 2 · Better, then optimal, Problem 1: prefix/suffix arrays (O(n) time, O(n) space), then two pointers (O(n) time, O(1) space)

TrappingRainWaterDemo.javaJava
public class TrappingRainWaterDemo {    // Step 1 (Partial / O(n) Space): Explicit Prefix & Suffix Max Arrays    public static int trapWithArrays(int[] height) {        int n = height.length;        int[] leftMax = new int[n];        int[] rightMax = new int[n];        leftMax[0] = height[0];        for (int i = 1; i < n; i++) leftMax[i] = Math.max(leftMax[i - 1], height[i]);        rightMax[n - 1] = height[n - 1];        for (int i = n - 2; i >= 0; i--) rightMax[i] = Math.max(rightMax[i + 1], height[i]);
        int water = 0;        for (int i = 0; i < n; i++) {            water += Math.min(leftMax[i], rightMax[i]) - height[i];        }        return water;    }
    // Step 2 (Optimal / O(1) Space): Opposite-End Two Pointers    public static int trapOptimal(int[] height) {        int left = 0;        int right = height.length - 1;        int leftMax = 0;        int rightMax = 0;        int water = 0;        while (left < right) {            if (height[left] < height[right]) {                leftMax = Math.max(leftMax, height[left]);                water += leftMax - height[left];                left++;            } else {                rightMax = Math.max(rightMax, height[right]);                water += rightMax - height[right];                right--;            }        }        return water;    }
    public static void main(String[] args) {        int[] h = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};        System.out.println("trapWithArrays: " + trapWithArrays(h));        System.out.println("trapOptimal:    " + trapOptimal(h));    }}
Output
trapWithArrays: 6
trapOptimal:    6

What this code does

  • When height[left] < height[right], we know leftMax < rightMax (or leftMax <= height[right] <= trueRightMax), so the bottleneck at left is guaranteed to be leftMax!
  • Writing trapWithArrays first makes the invariant of trapOptimal crystal clear.

Example 3 · Problem 4: Subarrays with Exactly K Different Integers (atMost(K) - atMost(K - 1))

SubarraysWithKDistinctDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class SubarraysWithKDistinctDemo {    public static int subarraysWithKDistinct(int[] nums, int k) {        return atMostK(nums, k) - atMostK(nums, k - 1);    }
    private static int atMostK(int[] nums, int k) {        if (k <= 0) return 0;        Map<Integer, Integer> freq = new HashMap<>();        int left = 0;        int count = 0;        for (int right = 0; right < nums.length; right++) {            freq.put(nums[right], freq.getOrDefault(nums[right], 0) + 1);            while (freq.size() > k) {                int leftVal = nums[left++];                int c = freq.get(leftVal) - 1;                if (c == 0) freq.remove(leftVal);                else freq.put(leftVal, c);            }            // Every subarray ending at 'right' with start in [left..right] has <= k distinct            count += (right - left + 1);        }        return count;    }
    public static void main(String[] args) {        System.out.println("k=2 on [1,2,1,2,3]: " + subarraysWithKDistinct(new int[]{1, 2, 1, 2, 3}, 2));        System.out.println("k=3 on [1,2,1,3,4]: " + subarraysWithKDistinct(new int[]{1, 2, 1, 3, 4}, 3));    }}
Output
k=2 on [1,2,1,2,3]: 7
k=3 on [1,2,1,3,4]: 3

What this code does

  • A single sliding window cannot directly count subarrays with exactly K distinct elements because shrinking left can stay at K for several positions.
  • By contrast, "at most K distinct" is monotonic: once [left..right] has ≤ K distinct elements, all right - left + 1 subarrays ending at right also have ≤ K distinct elements! Subtracting atMostK(k - 1) leaves exactly K.

Example 4 · Problem 5: K-th Smallest Pair Distance (Binary Search on Answer + Two Pointers)

KthSmallestPairDistanceDemo.javaJava
import java.util.Arrays;
public class KthSmallestPairDistanceDemo {    public static int smallestDistancePair(int[] nums, int k) {        Arrays.sort(nums);        int low = 0;        int high = nums[nums.length - 1] - nums[0];        while (low < high) {            int mid = low + ((high - low) >>> 1);            if (countPairsWithin(nums, mid) >= k) {                high = mid;            } else {                low = mid + 1;            }        }        return low;    }
    // Inner Pattern: Same-Direction Two Pointers in O(n) time    private static int countPairsWithin(int[] sorted, int maxDist) {        int left = 0;        int count = 0;        for (int right = 0; right < sorted.length; right++) {            while (sorted[right] - sorted[left] > maxDist) {                left++;            }            count += (right - left);        }        return count;    }
    public static void main(String[] args) {        System.out.println("k=1 on [1, 3, 1]:    " + smallestDistancePair(new int[]{1, 3, 1}, 1));        System.out.println("k=3 on [1, 6, 1]:    " + smallestDistancePair(new int[]{1, 6, 1}, 3));    }}
Output
k=1 on [1, 3, 1]:    0
k=3 on [1, 6, 1]:    5

What this code does

  • Generating all C(n, 2) pair distances takes O(n²) time and memory, which fails for n = 10⁴ (5 × 10⁷ pairs).
  • Combining Binary Search over distance mid (O(log W) steps) with a Two-Pointer pair counter (O(n) per step) solves it in O(n log n + n log W) time and O(1) extra space.

Getting a Partial Solution First and Writing the Plan Before the Code

When you face a hard problem under a clock, do not try to invent the O(1)-space or two-layer optimal code in your head all at once. First lock in the intermediate partial solution that proves the math:

  • In Trapping Rain Water, first write down the O(n)-space formula using leftMax[i] and rightMax[i] arrays. Once you see that water at i only depends on the smaller of leftMax and rightMax, the O(1)-space two-pointer optimization (leftMax < rightMax ? advance left : advance right) becomes obvious!
  • Before typing a two-pattern solution, write a 4-line comment plan at the top of your method separating the outer pattern from the inner helper so you never mix their variables.
  1. Line 1 (Outer Pattern): e.g., Binary search candidate maxSubarraySum mid in [maxElem, totalSum].
  2. Line 2 (Inner Pattern): Greedy helper canSplit(nums, k, mid) counts how many subarrays are needed when no subarray exceeds mid.
  3. Line 3 (Monotonicity): If canSplit(mid) is true, try smaller (high = mid); else try larger (low = mid + 1).
  4. Line 4 (Edge Cases): k == 1 returns totalSum; k == n returns maxElem; use long if sums exceed 2 × 10⁹.

Reviewing the Model Solution Step by Step

When studying a hard model solution, never read it top-to-bottom like prose. Always split it into two independent functions (even if the author wrote it inline) and verify each function's contract separately:

  1. Verify the inner helper on a fixed parameter first (e.g., verify countAtMostK(nums, 2) on [1, 2, 1, 2, 3], or countPairsWithin(sorted, mid) on [1, 3, 6]).
  2. Verify how the outer driver combines or binary-searches the helper (atMost(k) - atMost(k - 1), or while (low < high)).
In interviews, writing the inner pattern as a named private helper method (canSplit, atMostK, countPairs) makes your code dramatically easier to debug and explain.

Next step

Check your understanding

10 quick questions