When to use:
Working with sorted arrays or lists, searching for pairs, or reversing sequences.
Examples:
Idea:
Use two pointers starting from opposite ends (or one moving faster than the other) and move them towards each other.
When to use:
Subarray or substring problems where you need to find a max/min/average in a moving “window.”
Examples:
k
Idea:
Maintain a window that moves forward — add a new element and remove the oldest one when needed.
When to use:
Detecting cycles in linked lists or arrays.
Examples:
Idea:
One pointer moves twice as fast as the other; if there’s a loop, they’ll meet.
When to use:
Quick lookups, avoiding nested loops.
Examples:
Idea:
Store data in a hashmap/set for constant time access and avoid repeated work.
When to use:
Searching in sorted arrays, or answers in a sorted search space.
Examples:
Idea:
Repeatedly divide the search space in half.
When to use:
Generate all permutations, combinations, subsets, solving puzzles.
Examples:
Idea:
Build a solution step-by-step and backtrack when a condition fails.
When to use:
When a problem can be broken into similar subproblems.
Examples:
Idea:
Divide the problem, solve subproblems, and combine their results.
When to use:
When a local optimal choice leads to a global optimum.
Examples:
Idea:
Choose the best possible option at each step.
When to use:
When a problem has overlapping subproblems and optimal substructure.
Examples:
Idea:
Store results of subproblems to avoid recomputation.
When to use:
For handling connected components, or determining whether elements are in the same subset.
Examples:
Idea:
Use parent pointers and path compression for efficiency.
When you see a problem:
Would you like me to list some LeetCode practice problems for each pattern too? I can set up a solid learning path for you 👌