Skip to lesson

Spotting the pattern

When you practice inside a chapter titled "Sliding Window", you already know which tool to use before reading the first word. In a real coding test or interview, problems arrive unlabelled — your first job is to read the wording and constraints like a detective and narrow 100 possible ideas down to 1 or 2 candidate patterns.

The pattern map: clues and a tiny example

A pattern is a known way of solving a family of problems, such as two pointers or sliding window. Recognising it from the problem's clues is the key interview skill.

Each pattern leaves clue words in the problem statement. Find the clue, name the pattern, then compare with the tiny example.

  • Two pointers: clues are a sorted array, a pair or triplet with a target sum, a palindrome, or moving items in place. Tiny example: in sorted [1, 3, 4, 8] with target 7, the ends give 1 + 8 (too big), then 1 + 4 (too small), then 3 + 4 = 7.
  • Sliding window: clues are the longest, shortest or best contiguous subarray or substring, or at most K distinct values, with non-negative numbers. Tiny example: longest substring with no repeats in abcab: grow on the right, shrink on the left when a letter repeats.
  • Prefix sums with a HashMap: clues are a subarray sum equal to K, range sum queries, equal numbers of 0s and 1s, or negative numbers. Tiny example: the prefix sums of [2, -2, 5] are 0, 2, 0, 5. The value 0 appears twice, so the part between them sums to 0.
  • Binary search on a sorted array: clues are a sorted or rotated sorted array, finding a position, and a hint of O(log n). Tiny example: find 7 in [1, 3, 5, 7, 9]: the middle is 5, so go right, and the next middle is 7.
  • Binary search on the answer: clues are the smallest or largest value X so that a condition holds, such as capacity, speed or waiting time. Tiny example: the smallest capacity that ships all parcels in D days. Test 10: if it works try less, otherwise try more.
  • Backtracking or bitmask: clues are all subsets, permutations, arrangements or a board to solve, with n up to about 20. Tiny example: the subsets of {a, b} are none, a, b and a b. Choose or skip each item.
  • XOR and bit tricks: clues are every value appearing twice except one, flags, or powers of two. Tiny example: in [4, 1, 2, 1, 2] the pairs cancel under XOR, so the result is 4.
  • Math: GCD, primes, modulo, nCr: clues are an answer modulo 10⁹ + 7, how many ways, primes up to N, or a common divisor. Tiny example: gcd(48, 18): 48 % 18 = 12, 18 % 12 = 6, 12 % 6 = 0, so the answer is 6.

Clue words in action

Two problems can sound alike, yet their clues point to different patterns. The code below solves both and shows how the clues decide.

Example 1 · Spotting Binary Search on Answer vs Two Pointers from Clue Words

ClueWordComparisonDemo.javaJava
import java.util.Arrays;
public class ClueWordComparisonDemo {    // Clue: "pair in array with sum <= limit" -> Sort + Opposite Two Pointers    public static int countPairsAtMost(int[] nums, int limit) {        int[] sorted = nums.clone();        Arrays.sort(sorted);        int left = 0;        int right = sorted.length - 1;        int count = 0;        while (left < right) {            if (sorted[left] + sorted[right] <= limit) {                count += (right - left);                left++;            } else {                right--;            }        }        return count;    }
    // Clue: "minimum capacity C to ship packages in D days" -> Binary Search on Answer    public static int minShipCapacity(int[] weights, int days) {        int low = 0;        int high = 0;        for (int w : weights) {            low = Math.max(low, w);            high += w;        }        while (low < high) {            int mid = low + ((high - low) >>> 1);            if (canShip(weights, days, mid)) {                high = mid;            } else {                low = mid + 1;            }        }        return low;    }
    private static boolean canShip(int[] weights, int days, int cap) {        int usedDays = 1;        int load = 0;        for (int w : weights) {            if (load + w > cap) {                usedDays++;                load = 0;            }            load += w;        }        return usedDays <= days;    }
    public static void main(String[] args) {        System.out.println("Pairs with sum <= 7 in [1, 5, 3, 4, 2]: "            + countPairsAtMost(new int[]{1, 5, 3, 4, 2}, 7));        System.out.println("Min ship capacity for [1,2,3,4,5,6,7,8,9,10] in 5 days: "            + minShipCapacity(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5));    }}
Output
Pairs with sum <= 7 in [1, 5, 3, 4, 2]: 8
Min ship capacity for [1,2,3,4,5,6,7,8,9,10] in 5 days: 15

What this code does

  • In countPairsAtMost, order in the original array does not matter (we count pairs {i, j}), so sorting in O(n log n) and sweeping with two pointers in O(n) works.
  • In minShipCapacity, packages must be shipped in order, and canShip(cap) is monotonic (false, ..., false, true, ..., true), which is the signature of Binary Search on the Answer.

Constraints as clues

Online judges typically allow around 10⁷ to 10⁸ simple operations per second. Before writing a single line of code, look at the maximum value of n in the Constraints section — it tells you the slowest time complexity that can pass and rules out patterns that are too slow or unnecessarily complex.

  • n ≤ 10 to 12: O(n!) or O(n · 2ⁿ) — Backtracking (permutations, N-Queens).
  • n ≤ 20: O(2ⁿ) or O(n · 2ⁿ) — Backtracking (subsets/combinations) or Bitmask Power Set.
  • n ≤ 2 000: O(n²) passes — nested loops, expand-around-center, or 2D Pascal's triangle.
  • n ≤ 10⁵ to 10⁶: must be O(n log n) or O(n) — Two Pointers, Sliding Window, Prefix Sum + HashMap, Binary Search, or Sieve. And if n ≥ 10⁹, the algorithm must be O(√n) or O(log n) (Binary Search, Binary Exponentiation, or Euclid's GCD).

Just as important as n are the element bounds (nums[i]). If 0 <= nums[i] <= 10^4, adding an element to a window never decreases the window sum, so two pointers / sliding window is valid. The moment the constraint says -10^4 <= nums[i] <= 10^4, expanding the right pointer can shrink the sum, breaking sliding window monotonicity and forcing Prefix Sum + HashMap!

The same clue with different numbers

The same sentence can need a different pattern when the numbers change. These two examples show it with element bounds and with the size of n.

Example 2 · Why Element Constraints Flip the Pattern: Non-Negative vs Negative Subarray Sum

ConstraintFlipsPatternDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class ConstraintFlipsPatternDemo {    // Pattern A: Sliding Window — ONLY valid when all nums[i] >= 0    public static int longestSubarrayNonNegative(int[] nums, int k) {        int left = 0;        int sum = 0;        int best = 0;        for (int right = 0; right < nums.length; right++) {            sum += nums[right];            while (sum > k && left <= right) {                sum -= nums[left++];            }            if (sum == k) {                best = Math.max(best, right - left + 1);            }        }        return best;    }
    // Pattern B: Prefix Sum + HashMap — works even when nums[i] can be negative!    public static int longestSubarrayWithNegatives(int[] nums, int k) {        Map<Long, Integer> firstIndex = new HashMap<>();        firstIndex.put(0L, -1);        long prefix = 0;        int best = 0;        for (int i = 0; i < nums.length; i++) {            prefix += nums[i];            Integer prev = firstIndex.get(prefix - k);            if (prev != null) {                best = Math.max(best, i - prev);            }            firstIndex.putIfAbsent(prefix, i);        }        return best;    }
    public static void main(String[] args) {        int[] nonNeg = {1, 2, 1, 1, 1, 3, 2};        System.out.println("Non-negative k=4 (Sliding Window): "            + longestSubarrayNonNegative(nonNeg, 4));
        int[] withNeg = {3, 4, -7, 1, 3, 3, 1, -4};        System.out.println("With negatives k=7 (Prefix + Map): "            + longestSubarrayWithNegatives(withNeg, 7));    }}
Output
Non-negative k=4 (Sliding Window): 3
With negatives k=7 (Prefix + Map): 6

What this code does

  • Both problems ask for the "longest contiguous subarray with sum k", yet the constraint nums[i] >= 0 vs nums[i] can be negative completely changes the algorithm.
  • In nonNeg, [1, 2, 1] and [2, 1, 1] have length 3 (sum 4); in withNeg, indices 0..5 ([3, 4, -7, 1, 3, 3]) have length 6 and sum 7.

Example 3 · Choosing Pattern by Constraint Size n

ConstraintClassifierDemo.javaJava
public class ConstraintClassifierDemo {    public static String suggestComplexityAndPatterns(long n, boolean hasNegatives, boolean asksAllConfigs) {        if (asksAllConfigs && n <= 20) {            return "O(2^n) or O(n!): Backtracking / Bitmask Enumeration";        }        if (n >= 100_000_000L) {            return "O(log n) or O(sqrt(n)): Binary Search / Binary Exponentiation / Euclid GCD";        }        if (n >= 50_000L) {            if (hasNegatives) {                return "O(n) or O(n log n): Prefix Sum + HashMap / Sorting + Two Pointers";            }            return "O(n) or O(n log n): Sliding Window / Two Pointers / Binary Search";        }        return "O(n^2) allowed: Nested Scan / Expand Around Center / Pascal Table";    }
    public static void main(String[] args) {        System.out.println("n=15, all subsets -> " + suggestComplexityAndPatterns(15, false, true));        System.out.println("n=1e5, non-neg    -> " + suggestComplexityAndPatterns(100_000, false, false));        System.out.println("n=1e5, negatives  -> " + suggestComplexityAndPatterns(100_000, true, false));        System.out.println("n=1e12, math      -> " + suggestComplexityAndPatterns(1_000_000_000_000L, false, false));    }}
Output
n=15, all subsets -> O(2^n) or O(n!): Backtracking / Bitmask Enumeration
n=1e5, non-neg    -> O(n) or O(n log n): Sliding Window / Two Pointers / Binary Search
n=1e5, negatives  -> O(n) or O(n log n): Prefix Sum + HashMap / Sorting + Two Pointers
n=1e12, math      -> O(log n) or O(sqrt(n)): Binary Search / Binary Exponentiation / Euclid GCD

What this code does

  • Reading n first prevents you from wasting 20 minutes writing an O(n²) nested loop when n = 10⁵ (10¹⁰ operations → TLE).
  • Conversely, when n ≤ 15 and the output is a list of all combinations, you know immediately that an exponential backtracking search is expected.

A Decision Flowchart

When facing an unfamiliar array, string, or math problem, walk through these questions in order rather than guessing at random:

  1. Check n: Is n ≤ 20 and the problem asks for all valid configurations? Use Backtracking or Bitmask subsets.
  2. Check for O(log n) scale: Is the input sorted, or are we minimizing/maximizing a threshold X with a monotonic canAchieve(X) check? Use Binary Search.
  3. Check for contiguous subarrays/substrings: Does the window condition grow monotonically when right advances (e.g., positive numbers, character counts)? Use Sliding Window. If negative numbers break monotonicity, use Prefix Sum + HashMap.
  4. Check for pair/triplet relationships or in-place filtering: Can sorting the array let opposite pointers eliminate a whole row/column of pairs at once? Use Two Pointers.
  5. Check for pairing cancellation or number theory: Do duplicates cancel (x ⊕ x = 0), or does the problem ask for divisibility, primes, or counts modulo 10⁹ + 7? Use XOR, GCD/Sieve, or nCr.
Always verify your chosen pattern on one small hand-crafted edge case (such as an array with a negative number or duplicate values) before coding.

Next step

Check your understanding

10 quick questions