8 patterns cover 90% of coding interview problems. Learn to recognize them, apply the right one, and communicate your thinking clearly.
🔢 DSA🎯 Strategy🟡 Intermediate📖 ~20 min
Lesson 23 of DSA Track
The 5-Step Approach
Every coding interview problem, no matter how hard, can be tackled with this structured approach. Interviewers care as much about how you think as whether you get the optimal solution. Follow these five steps and you will always have something to say, something to write, and a clear direction forward.
1
Understand
Restate the problem. Ask clarifying questions.
2
Examples
Walk through 2-3 examples by hand.
3
Brute Force
State the naive solution and its complexity.
4
Optimize
Identify the pattern. Reduce time or space.
5
Code
Write clean code. Test with examples.
Why brute force first?
Starting with the brute force solution shows you understand the problem. It gives you a baseline to improve. Many candidates skip straight to the "optimal" solution and get stuck — a brute force answer that works is always better than an optimal answer that doesn't.
Example: "Find the first duplicate in an array"
Understand: "So I need to find the first value that appears twice as I scan left to right? Are values always integers? Can the array be empty?"
Examples:[2, 1, 3, 5, 3, 2] — answer is 3 (index 4 repeats before index 5).
Brute force: For each element, check all previous elements. O(n^2) time, O(1) space.
Optimize: Use a hash set — scan once, check membership in O(1). O(n) time, O(n) space.
Code: Write it, test with the example, test edge cases (empty array, no duplicates).
Pattern 1: Hash Map Lookup
1
When to use
You need O(1) lookups — finding pairs, counting frequencies, or checking membership
Signal words: "find a pair that...", "count occurrences", "first duplicate", "two sum", "group by", "anagram"
The hash map pattern replaces an inner loop with a dictionary lookup, turning O(n^2) brute force into O(n). Whenever you find yourself writing a nested loop to search for a complement or match, ask: "Can I store what I've seen so far in a hash map?"
hashmap_two_sum.pyClassic Two Sum — O(n)
Output
[0, 1]
[1, 2]
Pattern 2: Two Pointers
2
When to use
Sorted array or linked list — find pairs, remove duplicates, or merge
Signal words: "sorted array", "pair with sum", "remove duplicates in-place", "palindrome", "merge two sorted", "container with most water"
Two pointers start at opposite ends (or both at the start) and move toward each other based on a condition. This avoids the nested loop — O(n) instead of O(n^2).
two_pointers_pair_sum.pyFind pair with target sum in sorted array
Output
[0, 4]
[0, 3]
Pattern 3: Sliding Window
3
When to use
Contiguous subarray or substring with a constraint
Signal words: "longest substring", "maximum sum subarray of size k", "minimum window", "contiguous", "subarray with sum"
The sliding window maintains a range [left, right] that expands and contracts. You expand by moving right forward, and shrink by moving left forward when a constraint is violated. This keeps the solution at O(n).
sliding_window_max_sum.pyMaximum sum of subarray of size k
Output
9
16
Pattern 4: BFS / DFS
4
When to use
Trees, graphs, grids — traverse, search, or find connected components
Signal words: "shortest path", "number of islands", "level order", "connected components", "cycle detection", "tree traversal", "maze"
BFS explores level by level (use a queue) — best for shortest path in unweighted graphs. DFS explores as deep as possible first (use recursion or a stack) — best for exhaustive search, connected components, and tree problems.
bfs_dfs_templates.pyBFS and DFS on a graph
Output
BFS: [0, 1, 2, 3]
DFS: [0, 1, 3, 2]
Pattern 5: Binary Search
5
When to use
Sorted data or a monotonic condition — find a boundary or target
Signal words: "sorted", "find minimum", "search rotated array", "kth smallest", "capacity to ship", "minimize the maximum"
Binary search halves the search space each step — O(log n). It works on any monotonic function, not just sorted arrays. If you can define a condition that flips from False to True (or vice versa) across a range, you can binary search for the boundary.
binary_search_template.pyGeneric binary search on a condition
Output
3
3
Pattern 6: Stack
6
When to use
Matching brackets, nested structures, or "next greater element"
Signal words: "valid parentheses", "next greater element", "decode string", "evaluate expression", "largest rectangle in histogram", "monotonic stack"
Stacks handle anything with nesting or "last in, first out" ordering. Monotonic stacks solve "next greater/smaller element" problems in O(n) by maintaining a stack where elements are always increasing or decreasing.
stack_valid_parens.pyValid parentheses — classic stack problem
Output
True
False
True
Pattern 7: Dynamic Programming
7
When to use
Optimization over overlapping subproblems — counting ways, min/max cost
Signal words: "minimum cost", "number of ways", "longest subsequence", "can you reach...", "knapsack", "edit distance", "coin change"
DP stores solutions to subproblems to avoid recomputation. Two keys: (1) define the state clearly, (2) write the recurrence relation. If a brute force solution re-solves the same subproblem many times, DP will help.
dp_climbing_stairs.pyClimbing stairs — classic DP
Output
8
89
Pattern 8: Greedy
8
When to use
Local optimal choices lead to global optimum — scheduling, intervals, coins
Signal words: "minimum number of intervals", "activity selection", "jump game", "task scheduler", "gas station", "assign cookies"
Greedy algorithms make the locally optimal choice at each step, hoping it leads to the global optimum. They work when the problem has the greedy choice property — you can prove that no local decision needs to be reversed. If you are not sure greedy works, try DP instead.
greedy_jump_game.pyJump Game — can you reach the last index?
Output
True
False
Decision Tree: Which Pattern Should I Use?
When you see a new problem, run through this decision tree. Start at the top and follow the questions down to find the most likely pattern.
Given a problem...
↓
Does it involve a sorted array or searching in a range?
YES
↓
Need a pair/triplet with a target sum?
YES
↓
Two Pointers
NO
↓
Binary Search
NO
↓
Does it ask for a contiguous subarray/substring?
YES
↓
Sliding Window
NO
↓
Is it a tree/graph/grid traversal?
YES
↓
BFS / DFS
NO
↓
Does it involve matching/nesting or "next greater"?
YES
↓
Stack
NO
↓
Does it ask for min/max/count with overlapping subproblems?
YES
↓
Dynamic Programming
NO
↓
Need O(1) lookup for pairs/frequency?
YES
↓
Hash Map
NO
↓
Greedy
This is a starting point, not a rule book.
Many problems combine patterns (e.g., BFS + hash map, or binary search + greedy). The decision tree helps you pick the first pattern to try. If it doesn't work, move to the next branch.
Cheat Sheet: Pattern at a Glance
Pattern
Use When
Time
Key Data Structure
Hash Map
O(1) lookups, pairs, frequency
O(n)
dict / set
Two Pointers
Sorted array, pair sums
O(n)
Two indices
Sliding Window
Contiguous subarray/substring
O(n)
Two indices + counter
BFS / DFS
Trees, graphs, grids
O(V+E)
Queue / Stack / Recursion
Binary Search
Sorted data, monotonic condition
O(log n)
Two bounds
Stack
Nesting, matching, next greater
O(n)
Stack (list)
DP
Overlapping subproblems, optimization
Varies
Array / table
Greedy
Local optimal = global optimal
O(n log n)
Sorting + scan
Time Management: The 45-Minute Plan
Most coding interviews give you 45 minutes for one problem (or two easier ones). Here is how to spend that time wisely. The biggest mistake is jumping straight to coding — invest the first 15 minutes in understanding and planning.
1
Understand the Problem
Read carefully. Restate in your own words. Ask clarifying questions: "Can the input be empty?" "Are values unique?" "What should I return if there's no answer?"
0:00 — 5:00
2
Work Through Examples
Walk through 2-3 examples by hand on paper or whiteboard. Include a normal case, an edge case (empty, single element), and a tricky case. This often reveals the pattern.
5:00 — 10:00
3
Describe Brute Force
State the naive approach and its Big-O. Don't code it — just explain it verbally. This shows you understand the problem and gives a baseline.
10:00 — 15:00
4
Optimize & Plan
Identify the pattern (hash map? two pointers? DP?). Explain your approach before writing code. State the expected time and space complexity. Get a verbal "go ahead" from the interviewer.
15:00 — 25:00
5
Code the Solution
Write clean, readable code. Use descriptive variable names. Talk through each line as you write it. Don't worry about perfection — correctness first.
25:00 — 40:00
6
Test & Debug
Trace through your code with the earlier examples. Check edge cases. Fix bugs calmly. If time remains, discuss possible follow-ups or improvements.
40:00 — 45:00
If you get stuck at the "optimize" step:
Don't panic. Tell the interviewer what you've tried and what's not working. Ask: "Would it help if I sorted the input first?" or "I'm thinking about using a hash map here — does that seem reasonable?" Interviewers often give hints when you communicate clearly.
Communication Tips
Technical skill gets you to the interview. Communication gets you the offer. Here are the habits that separate candidates who pass from those who don't.
🗣️
Golden Rule
Think aloud — silence is your enemy
The interviewer can only evaluate what they can see and hear. If you're thinking silently for 3 minutes, they have no signal. Narrate your thought process: "I'm considering a hash map because I need O(1) lookups... but wait, the array is sorted, so two pointers might be better."
The Five Communication Habits
Ask clarifying questions early. "Can the array contain negative numbers?" "Is the input always valid?" This shows thoroughness and prevents wasted time on wrong assumptions.
State your assumptions explicitly. "I'm assuming the input fits in memory" or "I'll assume no duplicate values unless you tell me otherwise." This prevents misunderstandings and shows maturity.
Explain before you code. Describe your approach in plain English first. "I'll use a sliding window — expand right until the constraint breaks, then shrink from the left." Get the interviewer's nod before writing.
Discuss tradeoffs. "The hash map solution is O(n) time but O(n) space. The two-pointer approach is O(n log n) time (due to sorting) but O(1) space. Which would you prefer?" This demonstrates depth.
Acknowledge when you're stuck. "I'm not seeing how to optimize beyond O(n^2). My instinct says there's a two-pointer approach because the array is sorted, but I need a moment to think about the invariant." This is much better than silence.
Body language matters too.
Stay calm. Breathe. Smile occasionally. If you make a mistake, say "Good catch" and fix it — don't get flustered. Interviewers are humans evaluating whether they'd enjoy working with you.
Try It Yourself: Mystery Problem
Identify the Pattern & Solve
Here's a problem. Your job is to (1) identify which pattern fits, and (2) solve it.
Problem: Given an array of integers nums and a target integer target, return True if any two distinct elements in the array sum to target, otherwise return False.
Think about it: Do you need O(1) lookups? Is the array sorted? Is it a subarray problem? Which pattern from the decision tree applies?
Hint: This is a hash map (set) pattern — store seen values and check if the complement exists.
Challenge
Pattern Identification Challenges
Challenge 1: Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters. Example: "abcabcbb" returns 3 (the substring "abc").
Which pattern? Identify it, then code the solution.
This is a sliding window problem. Maintain a window [left, right] and a set of characters in the current window. Expand right — if the character is already in the set, shrink from left until it's removed. Track the maximum window size. O(n) time, O(min(n, alphabet)) space.
Challenge 2: Course Schedule (Cycle Detection)
There are n courses labeled 0 to n-1. Some courses have prerequisites: prerequisites[i] = [a, b] means you must take course b before course a. Return True if you can finish all courses (no circular dependency).
Which pattern? Identify it, then code the solution.
This is a BFS/DFS graph problem — specifically, cycle detection in a directed graph. Build an adjacency list and use DFS with three states (unvisited, in-progress, visited). If you visit a node that's "in-progress," there's a cycle. Alternatively, use BFS topological sort (Kahn's algorithm) with in-degree counting.
Quiz
Question 1 of 5
You are given a sorted array and asked to find two numbers that add up to a target. Which pattern is most efficient?
Question 2 of 5
A problem asks: "Find the longest contiguous subarray whose sum is at most K." Which pattern should you try first?
Question 3 of 5
In the 5-step approach, what should you do immediately after understanding the problem?
Question 4 of 5
You need to check if a string of brackets ({[]}) is valid. Which pattern is the right fit?
Question 5 of 5
During a coding interview, you've been thinking silently for 2 minutes. What should you do?
0
/5
Great work! You're ready for interviews.
Common Interview Mistakes
🚫
Jumping straight to code
Coding before understanding the problem leads to bugs and wasted time. Spend 10-15 minutes planning. Interviewers prefer a well-thought-out approach over fast but wrong code.
🚫
Not testing edge cases
Empty arrays, single elements, all duplicates, negative numbers, very large inputs. Always test at least one edge case after writing your solution. It shows attention to detail.
🚫
Coding in silence
The interviewer cannot evaluate what they cannot hear. Narrate your thinking: "I'm using a hash set here because I need O(1) lookups." Even if you're stuck, say so.
🚫
Refusing to start with brute force
Some candidates refuse to discuss a "bad" solution. But brute force shows understanding and gives you a working baseline. You can always optimize from there.
🚫
Panicking when stuck
Getting stuck is normal — it happens to everyone. Take a breath, re-read the problem, and try a different pattern from the decision tree. Ask the interviewer for a hint if needed — it's not a sign of weakness.
Key Takeaways
✓
8 patterns cover most problems. Hash map, two pointers, sliding window, BFS/DFS, binary search, stack, DP, and greedy. Learn to recognize the signals for each one.
✓
Always start with the 5-step approach. Understand, examples, brute force, optimize, code. This structure prevents you from getting lost and gives the interviewer confidence in your process.
✓
Use the decision tree when stuck. Run through the questions: sorted? contiguous? graph? nesting? overlapping subproblems? Each "yes" points you to a pattern.
✓
Communication is half the battle. Think aloud, ask clarifying questions, state assumptions, discuss tradeoffs. A good communicator who writes decent code beats a silent genius every time.
✓
Manage your 45 minutes deliberately. 15 minutes understanding and planning, 15 minutes coding, 5 minutes testing. Don't code until you have a clear plan.
Congratulations! You've worked through all 23 lessons — from arrays and Big-O all the way to dynamic programming and interview patterns. You have the tools to tackle any coding interview.
Keep practicing, stay consistent, and remember: every expert was once a beginner.