Interview Problem Solving: The 5-Step Framework
A complete framework for solving coding interview problems — the 5-step method, pattern recognition, handling stuck moments, communication strategies, common mistakes, and a 100-problem practice roadmap.
What you'll learn
- ✓The 5-step framework: understand, examples, approach, code, test
- ✓How to identify which algorithm pattern fits your problem
- ✓How to analyse time/space complexity during the interview
- ✓Strategies for when you get stuck
- ✓Communication techniques that impress interviewers
- ✓The most common mistakes that cost job offers
- ✓A structured 100-problem practice roadmap
Prerequisites
- •Some familiarity with basic data structures and algorithms
- •Know the basics of Big-O notation
Knowing algorithms is necessary but not sufficient for passing coding interviews. The difference between candidates who pass and those who do not often comes down to process — how you approach a problem, how you communicate, and how you handle the inevitable moments of uncertainty.
This post gives you a repeatable framework that works regardless of the problem. It is the same process used by engineers at top companies and by competitive programmers adapting to the interview format.
The 5-Step Framework
Every problem, from “reverse a string” to “find the shortest path in a weighted graph,” benefits from the same five steps. Rushing to code is the number one reason candidates fail.
Step 1: Understand the Problem (2-3 minutes)
Before writing a single line, make sure you truly understand what is being asked.
Do this:
- Restate the problem in your own words
- Clarify the input format and constraints (size of n, range of values, sorted or unsorted?)
- Ask about edge cases: empty input, single element, duplicates, negative numbers
- Ask about the expected output format
Say this: “So if I understand correctly, I’m given an array of integers and I need to find two numbers that sum to a target. Can the array contain duplicates? Can I use the same element twice? Is the array sorted?”
Why it matters: interviewers deliberately leave problems slightly ambiguous. Asking good clarifying questions shows maturity and saves you from solving the wrong problem.
Step 2: Work Through Examples (2-3 minutes)
Walk through 2-3 examples by hand. Start with a simple case, then try an edge case.
Example 1 (simple):
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)
Example 2 (edge case):
Input: nums = [3, 3], target = 6
Output: [0, 1] (duplicates that sum to target)
Example 3 (no solution?):
Input: nums = [1, 2, 3], target = 10
Output: [] (clarify: is this possible?)
Why it matters: examples reveal patterns your analytical mind might miss. They also catch misunderstandings early.
Step 3: Plan Your Approach (5-8 minutes)
This is the most important step. Think out loud about possible approaches, starting from brute force and optimising.
The optimisation ladder:
- Brute force: what is the simplest correct solution? State its time complexity.
- Can I sort? Sorting often enables binary search or two pointers.
- Can I use extra space? A hash map often trades O(n) space for O(n) time.
- Is there a known pattern? (See the pattern recognition section below.)
- Can I reduce the problem? Can I transform it into a problem I already know?
Say this: “The brute force would be O(n^2) — check every pair. But if I use a hash map to store numbers I’ve seen, I can check in O(1) whether the complement exists. That gives me O(n) time and O(n) space.”
Get confirmation before coding: “Does this approach sound good? Should I go ahead and implement it?”
Step 4: Write the Code (10-15 minutes)
Now — and only now — write code. Write clean, readable code as if a colleague will review it.
Guidelines:
- Use meaningful variable names (
left,right, noti,jfor two pointers) - Write helper functions for complex logic
- Handle edge cases at the top
- Comment non-obvious logic with a short note
- Do not micro-optimise — clarity beats cleverness
def two_sum(nums, target):
# Map: value -> index
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Step 5: Test Your Code (3-5 minutes)
Do not say “I think this works.” Trace through your code with your earlier examples.
Trace with nums = [2, 7, 11, 15], target = 9:
i=0, num=2, complement=7, seen={} → not found, seen={2:0}
i=1, num=7, complement=2, seen={2:0} → found! return [0, 1] ✓
Then check edge cases:
- Empty array → returns
[](the loop does not execute) - Single element → returns
[](no complement found) - Duplicates →
[3, 3], target=6: i=0 adds 3:0, i=1 finds 3 in seen → [0, 1] correct
Fix bugs calmly. Finding and fixing a bug during testing shows strong engineering instincts.
Pattern Recognition — The Decision Tree
When you see a problem, run through this mental checklist:
Is the input sorted?
├─ Yes → Two pointers or binary search
└─ No
├─ Looking for pairs/triplets? → Hash map or sort + two pointers
├─ Contiguous subarray? → Sliding window or prefix sum
├─ Tree/graph traversal? → BFS or DFS
├─ Shortest path? → BFS (unweighted) or Dijkstra (weighted)
├─ Optimal choice at each step? → Greedy (prove it works!)
├─ Try all possibilities? → Backtracking
├─ Overlapping subproblems? → Dynamic programming
├─ String matching? → KMP, Z-algorithm, or hashing
├─ Range queries? → Segment tree or prefix sum
└─ Connected components? → Union-Find or DFS
Quick pattern signals
| Signal in the problem | Likely pattern |
|---|---|
| ”Find the k-th largest” | Heap or quickselect |
| ”All permutations / combinations” | Backtracking |
| ”Minimum/maximum cost with choices” | DP or greedy |
| ”Can you reach from A to B?” | BFS/DFS |
| ”How many ways to…” | DP (count states) |
| “Longest/shortest subsequence” | DP |
| ”Sliding window” or “contiguous subarray” | Sliding window |
| ”Find if cycle exists” | DFS with visited states or Union-Find |
| ”Merge intervals” | Sort by start time |
| ”Matrix / grid path” | BFS or DP |
Complexity Analysis During Interviews
Always state the time and space complexity of your solution. Here is a quick reference:
Common time complexities:
- O(1): hash map lookup, array access
- O(log n): binary search, heap operations
- O(n): single pass through array
- O(n log n): sorting, divide and conquer
- O(n^2): nested loops (brute force for pairs)
- O(2^n): subset enumeration, some backtracking
- O(n!): permutation enumeration
How to analyze quickly:
- Count nested loops (each adds a factor of n)
- Recursive calls: identify the recurrence (T(n) = 2T(n/2) + O(n) = O(n log n))
- Space: what data structures are you maintaining? Hash maps = O(n), recursion stack = O(depth)
Say this: “The time complexity is O(n) because we make a single pass through the array. The space complexity is O(n) for the hash map in the worst case where all elements are unique.”
Handling “I’m Stuck” Moments
Everyone gets stuck. The difference is how you handle it.
Strategy 1: Simplify the problem
If the original problem is too hard, solve a simpler version first:
- “What if the array were sorted?”
- “What if there were only 2 elements?”
- “What if the graph were a tree?”
Often the solution to the simplified version generalises.
Strategy 2: Think about data structures
Go through your mental toolbox: “Would a stack help here? A heap? A trie? A hash map?” Sometimes the right data structure makes the solution obvious.
Strategy 3: Work backwards
Start from the output and ask “what would I need to produce this?” Sometimes working from the answer back to the input reveals the approach.
Strategy 4: Ask for a hint
There is no shame in saying: “I’m thinking about using a sliding window approach, but I’m not sure how to handle the shrinking condition. Could you point me in the right direction?”
What NOT to do: sit in silence for more than 30 seconds. The interviewer cannot help you if they do not know what you are thinking.
Communication Strategies
Interviews are collaborative, not adversarial. The interviewer wants you to succeed.
Think out loud
Narrate your thought process: “I’m considering a hash map because I need O(1) lookups… but wait, I also need ordering, so maybe a TreeMap would be better…”
Explain trade-offs
“I could sort the array for O(n log n) and use binary search, or use a hash set for O(n) but with O(n) extra space. I’ll go with the hash set since the problem doesn’t mention memory constraints.”
Name the pattern
“This looks like a sliding window problem because we’re looking for a contiguous subarray with a specific property.”
Admit uncertainty honestly
“I’m not 100% sure this greedy approach is optimal, but here’s my reasoning…” is much better than confidently presenting a wrong solution.
Common Mistakes That Cost Offers
1. Jumping to code too fast
Without planning, you write yourself into a corner, then have to restart. This wastes 5-10 minutes and rattles your confidence.
2. Not asking clarifying questions
You assume the array is sorted when it is not. You assume indices are 0-based when the interviewer meant 1-based. Five minutes of wrong work follows.
3. Over-engineering the solution
The interviewer asks for a simple solution and you build an enterprise-grade generic framework. Keep it simple.
4. Not testing your code
“I think this works” is not testing. Trace through at least two examples. Finding a bug yourself is much better than the interviewer finding it.
5. Poor variable naming
a, b, c, x, y — the interviewer cannot follow your code. Use left, right, count, target.
6. Ignoring edge cases
Empty input, single element, all elements the same, maximum constraints. Address these explicitly.
7. Panicking when stuck
A 30-second pause followed by a structured approach (simplify, try different DS, work backwards) is fine. Spiralling silently is not.
The 100-Problem Practice Roadmap
Structure your practice by pattern, not by random selection. Here is a roadmap organised by difficulty:
Phase 1: Foundations (Problems 1-30)
| # | Pattern | Problems |
|---|---|---|
| 1-5 | Arrays + Hash Map | Two Sum, Contains Duplicate, Best Time to Buy/Sell Stock, Product of Array Except Self, Maximum Subarray |
| 6-10 | Strings | Valid Anagram, Valid Palindrome, Longest Substring Without Repeating Chars, Group Anagrams, Longest Palindromic Substring |
| 11-15 | Two Pointers | Container With Most Water, 3Sum, Trapping Rain Water, Move Zeroes, Sort Colors |
| 16-20 | Sliding Window | Minimum Window Substring, Longest Repeating Character Replacement, Permutation in String, Max Consecutive Ones III, Fruit Into Baskets |
| 21-25 | Stack/Queue | Valid Parentheses, Min Stack, Daily Temperatures, Evaluate Reverse Polish Notation, Largest Rectangle in Histogram |
| 26-30 | Binary Search | Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array, Search a 2D Matrix, Koko Eating Bananas, Median of Two Sorted Arrays |
Phase 2: Trees and Graphs (Problems 31-55)
| # | Pattern | Problems |
|---|---|---|
| 31-35 | Binary Tree | Invert Binary Tree, Max Depth, Same Tree, Level Order Traversal, Validate BST |
| 36-40 | Binary Tree (Hard) | Serialize/Deserialize, Lowest Common Ancestor, Binary Tree Maximum Path Sum, Construct from Preorder/Inorder, Right Side View |
| 41-45 | Graph BFS/DFS | Number of Islands, Clone Graph, Pacific Atlantic Water Flow, Course Schedule, Word Ladder |
| 46-50 | Graph Advanced | Network Delay Time, Cheapest Flights Within K Stops, Alien Dictionary, Graph Valid Tree, Min Cost to Connect All Points |
| 51-55 | Heap/Priority Queue | Kth Largest Element, Top K Frequent Elements, Find Median from Data Stream, Merge K Sorted Lists, Task Scheduler |
Phase 3: Dynamic Programming (Problems 56-80)
| # | Pattern | Problems |
|---|---|---|
| 56-60 | 1D DP | Climbing Stairs, House Robber, Coin Change, Longest Increasing Subsequence, Word Break |
| 61-65 | 2D DP | Unique Paths, Longest Common Subsequence, Edit Distance, Target Sum, Interleaving String |
| 66-70 | DP (Medium-Hard) | 0/1 Knapsack, Partition Equal Subset Sum, Palindrome Partitioning, Decode Ways, Maximum Product Subarray |
| 71-75 | Interval/Tree DP | Burst Balloons, Matrix Chain, Unique BSTs, House Robber III, Stone Game |
| 76-80 | Backtracking | Subsets, Permutations, Combination Sum, N-Queens, Sudoku Solver |
Phase 4: Advanced (Problems 81-100)
| # | Pattern | Problems |
|---|---|---|
| 81-85 | Greedy | Jump Game, Meeting Rooms II, Non-Overlapping Intervals, Gas Station, Candy |
| 86-90 | Trie + Advanced | Implement Trie, Word Search II, Design Add/Search Words, Longest Word in Dictionary, Palindrome Pairs |
| 91-95 | Union Find | Number of Connected Components, Redundant Connection, Accounts Merge, Most Stones Removed, Swim in Rising Water |
| 96-100 | Bit Manipulation + Math | Single Number, Counting Bits, Reverse Bits, Missing Number, Pow(x,n) |
Study schedule
- 4 weeks (aggressive): 3-4 problems per day, review solutions you got wrong
- 8 weeks (moderate): 2 problems per day, with weekend review sessions
- 12 weeks (relaxed): 1 problem per day, focus on understanding not speed
The most important rule: after solving (or failing) a problem, read the editorial and at least two other solutions. Understanding why an approach works is more valuable than the fact that you solved it.
Recap
The interview is not just about algorithms — it is about demonstrating how you think:
- Understand before you solve. Ask questions. Restate the problem.
- Examples catch misunderstandings and reveal patterns.
- Plan from brute force to optimal. Name the pattern.
- Code cleanly with meaningful names and edge case handling.
- Test by tracing through examples. Fix bugs calmly.
Practice the framework until it becomes automatic. When the pressure is on, you want to fall back on process, not panic.
Next steps
Use the Data Structures Comparison Guide as a reference for choosing the right data structure during your interview. For advanced patterns, see CP Patterns and Advanced DP Patterns.
Questions or feedback? Email codeloomdevv@gmail.com.
Related articles
- DSA DSA Interview Checklist: 75 Must-Know Problems
The complete DSA interview checklist — 75 essential problems organized by pattern, study schedules for 4, 8, and 12 weeks, a pattern recognition framework, and what interviewers actually look for.
- DSA Graph Interview Patterns: Complete Guide
Master the top 20 graph interview patterns with a BFS vs DFS decision flowchart, Union-Find strategies, grid vs adjacency list trade-offs, and template code.
- DSA Linked List Interview Patterns: Complete Guide
Master the top 15 linked list interview patterns — dummy node, fast-slow pointers, reversal, merge, partition, and more. Includes common mistakes, a time complexity cheatsheet, and a decision flowchart.
- DSA String Interview Patterns: Complete Guide
A complete guide to string interview patterns — top 20 patterns, two-pointer on strings, frequency map technique, sliding window template, when to use Trie vs HashMap, common mistakes, and a complexity cheatsheet.