LeetCode gets easier when you stop treating every prompt as a new puzzle. Most problems point toward a small set of repeatable patterns, such as two pointers, sliding window, binary search, graphs, or dynamic programming. This checklist shows what each pattern does, what clues to look for, and how to practice it under interview pressure.
Table of Contents
- Step 1: Build Your Pattern Map
- Step 2: Recognize Linear Patterns
- Step 3: Search and Prioritize
- Step 4: Traverse Trees, Graphs, and Matrices
- Step 5: Handle Choice and Dependency
- Step 6: Store State with Hashing and Design Patterns
- Step 7: Reuse State with Dynamic Programming
- Step 8: Practice Pattern Recognition Under Pressure
- Frequently Asked Questions
- Conclusion
Step 1: Build Your Pattern Map
Start with the patterns that appear across arrays, strings, linked lists, trees, and graphs. A good map connects the input shape to the likely technique.
- Array or string: try two pointers, sliding window, hashing, prefix sum, or binary search.
- Tree or graph: try BFS, DFS, backtracking, union-find, or topological sort.
- Repeated choices: consider dynamic programming, greedy selection, or a heap.
- Nearest greater or smaller value: consider a monotonic stack.
Arrays give fast index access, but middle inserts cost more because later values shift. That trade-off often explains why an interview solution adds a hash map, set, or pointer pair.

Keep the map small at first. Recognition matters more than collecting every named technique. The basic definition of an algorithm is useful here: it is a step-by-step procedure for solving a task, not a memorized answer to one prompt.
Step 2: Recognize Linear Patterns
Linear patterns scan an array, string, or linked list while avoiding repeated work. The main clues are order, pairs, ranges, or a condition that changes as you move through the input.
Two pointers
Use two pointers when you need to compare positions or shrink a search from both ends. In a sorted array, one pointer can start at the left and one at the right. If the sum is too small, move the left pointer. If it is too large, move the right pointer.
Same-direction pointers handle a different job. A slow pointer can track the place for the next valid value while a fast pointer scans ahead. This is useful for linked-list cycles, list middles, and in-place filtering.
Sliding window
Sliding window is a focused form of two pointers. It keeps a continuous range that meets a rule. Move the right edge to grow the range. Move the left edge when the rule breaks.
For a string with repeated characters, keep a frequency map or set inside the window. The classic string cases include minimum covering substrings, longest substrings with limited distinct characters, and character replacement. A well-formed window can turn repeated substring checks into a single scan.

Prefix sums belong in this group too. Store the running total at each position. Then a range sum becomes the difference between two stored totals. If the task asks for a subarray with a target sum, combine prefix sums with a hash map to record earlier totals.
Step 3: Search and Prioritize
Some LeetCode patterns reduce the search space instead of scanning every option. Binary search and heap-based selection are the main examples.
Binary search
Use binary search when the search space has a monotonic rule. A sorted array is the common case, but the values do not need to be plainly sorted. You might instead search for the first position where a feasibility test becomes true.
For modified binary search, ask one question first: what stays ordered after the problem changes? In a rotated sorted array, one half remains sorted. In a minimum-capacity problem, a candidate capacity may be feasible above a threshold and infeasible below it.
Write the loop invariant before coding. State what the left and right boundaries mean. This prevents the common errors around duplicates, missing targets, and final pointer placement. The standard binary search definition centers on repeatedly reducing an ordered search interval.
Heap and top K
Use a heap when you repeatedly need the smallest or largest active item. For top K problems, keep only K candidates instead of sorting the full input. A min-heap is often useful for the K largest values because its root is the weakest item currently kept.
Ask what must remain available after each input value arrives. That answer usually tells you whether you need a min-heap, max-heap, or two heaps.
Step 4: Traverse Trees, Graphs, and Matrices
Tree and graph problems usually reduce to a choice between BFS and DFS. A matrix can use the same logic by treating each cell as a node with nearby neighbors.
Breadth-first search
BFS visits nodes by distance from the start. Put the first node in a queue. Remove one node, inspect its neighbors, then add unseen neighbors to the back. This order makes BFS a strong fit for unweighted shortest paths and level-order tree tasks.
Track visited nodes when a graph can contain cycles. Without that set, the traversal may revisit the same nodes forever. In a grid, mark a cell when you add it to the queue, not when you remove it. That stops duplicate queue entries.
Depth-first search
DFS follows one branch until it ends, then returns to the last decision point. Use recursion or an explicit stack. DFS fits path checks, connected components, tree depth, and many island problems.
For a matrix, define the four or eight legal directions once. Check bounds before reading a neighbor. Then decide whether to mark cells in place or store visited coordinates separately.
Step 5: Handle Choice and Dependency
Backtracking, greedy strategy, and topological sorting solve different forms of choice. The key is to identify what the prompt asks you to preserve.
Backtracking
Backtracking explores choices, then reverses the last choice before trying another. It is a constrained DFS. Stop as soon as the current partial answer cannot become valid.
Use it for subsets, permutations, combination sums, word search, and placement problems such as N-Queens. A typical function has four parts:
- Choose a candidate.
- Update the partial result.
- Recurse.
- Undo the update.
If duplicate output is forbidden, sort the input first and skip equal choices at the same depth. Backtracking may still take exponential time because the task asks for many possible answers. Pruning only cuts branches that cannot work.
Greedy
Greedy selection takes the best-looking next move. That rule needs proof. A local choice is safe only when it cannot damage the best final answer.
For interval scheduling, choosing the interval that ends first can leave the most room for later work. But a greedy rule that feels natural can fail when one early choice affects several later choices. Test it against a small counterexample before coding.
Topological sorting
Topological sorting orders items with one-way dependencies. It applies to directed acyclic graphs, such as course prerequisites or build tasks. Use indegrees with a queue, or run DFS while tracking active nodes.
A cycle means no valid full order exists. That check is part of the solution, not an afterthought.
Step 6: Store State with Hashing and Design Patterns
Hash maps and sets are often the hidden support behind other LeetCode patterns. They answer questions such as, “Have I seen this value?” or, “What was the last position of this key?”
Use a set for fast membership and uniqueness checks. Use a map when each key needs a value, such as a count, index, or running total. Two Sum is the simple model: store each earlier value, then check whether the needed complement already exists.
Hashing also pairs with prefix sums. For a target subarray sum, store how often each earlier prefix total appeared. The current total minus the target tells you which earlier total would form a valid range.
The LRU Cache pattern shows how design problems combine structures. A hash map finds a key quickly. A doubly linked list tracks recent use. Together, they support constant-time get and put operations when the list updates are handled carefully.
Phantom Code AI can help during mock interview practice by listening to the discussion, transcribing it, recognizing problem types, and giving real-time guidance. That makes it useful when you know the concepts but struggle to name the pattern while speaking.
Step 7: Reuse State with Dynamic Programming
Dynamic programming, or DP, fits problems with repeated subproblems and a best answer built from smaller answers. The first job is to define the state in plain language.
For climbing stairs, the state might be the number of ways to reach position i. For a knapsack problem, it might be the best value possible with a given capacity. For a string problem, it could describe the best result using prefixes of two strings.
Memoization and tabulation
Memoization starts with recursion and stores answers as they are found. Tabulation fills a table from smaller states toward larger ones. Pick the form that makes dependencies easiest to explain.
Before writing code, state:
- What does each state mean?
- What is the base case?
- Which earlier states produce the current state?
- What is the time and space cost?
DP is often confused with backtracking. If you need every valid arrangement, backtracking may be right. If many branches reach the same state and you need one best result, DP may remove that repeated work. Phantom Code AI is also relevant here because it can help surface the difference between DP, greedy reasoning, and search during a timed mock round.
Step 8: Practice Pattern Recognition Under Pressure
Knowing LeetCode patterns is only half the task. In an interview, you must identify the signal, explain the choice, and test the result while the clock runs.
Use this short routine for each problem:
- Read the prompt twice. Mark the input limits and required output.
- Work through a small example by hand.
- Name two possible patterns before choosing one.
- Describe the brute-force idea first.
- Point to the repeated work you want to remove.
- State the invariant or state definition.
- Code only after the plan is clear.
- Test empty input, one item, duplicates, negative values, and boundary cases.
Keep a decision log after each session. Write the pattern, the clue you missed, and one variation that could break your first approach. A variation might add duplicates, change the input to a stream, or restrict extra memory.
Timed practice should include spoken reasoning, not silent typing. If pressure affects your performance, read Why Timed Coding Challenges Stress Developers Out (And How to Fix It) for a focused preparation angle. For a full practice loop, Phantom Code AI can support mock coding sessions where pattern recognition and explanation matter alongside the final code.
Frequently Asked Questions
What are LeetCode patterns?
LeetCode patterns are repeatable methods for solving groups of coding problems. Common examples include two pointers, sliding window, binary search, BFS, DFS, backtracking, heaps, intervals, hashing, and dynamic programming. The point is to recognize the shape of a new prompt instead of memorizing one answer.
Which LeetCode pattern should I learn first?
Start with arrays, hash maps, two pointers, and sliding window. These patterns teach you how to remove nested scans while keeping the code easy to trace. Then add binary search, stacks, trees, graphs, and dynamic programming. Practice one pattern across several variations before moving to an unrelated topic.
How do I know if a problem uses sliding window?
A problem often uses sliding window when it asks for a longest or shortest contiguous substring or subarray under a changing condition. Keep a left and right boundary. Expand the right side, then move the left side when the condition fails. A set or frequency map often tracks what is inside the current range.
What is the difference between BFS and DFS?
BFS explores by distance or level, while DFS follows one path as far as it can before returning. BFS uses a queue and often fits shortest paths in unweighted graphs. DFS uses recursion or a stack and often fits path checks, components, tree depth, and backtracking-style exploration.
How many problems should I solve for each pattern?
There is no fixed number that proves you understand a pattern. Solve enough examples to explain the decision rule, write the core template, and handle a changed constraint. After each problem, record what clue led to the pattern. That learning record is more useful than a raw solved count.
Conclusion
Build your study plan around pattern signals, not random problem counts. Start with two pointers, sliding window, hashing, binary search, BFS, DFS, and DP, then practice explaining each choice aloud. Use the coding interview preparation hub to choose your next drill, and review your decision log after every session.