Ace Coding Interviews: 8 Patterns, 24 Problems
You know that feeling. The email lands, "Congratulations! We'd love to schedule your onsite." Then the cold dread sets in. Another gauntlet of coding interviews, another potential brain-freeze moment staring at a whiteboard. Look, I’ve been there. I’ve bombed interviews I thought I had in the bag, and I’ve aced ones where I felt underprepared, purely by understanding the underlying patterns. This isn't about memorizing solutions to 500 LeetCode problems. It's about recognizing the 8 core patterns that drive 80% of coding interview questions. Master these, and you'll solve 24 specific problems—and countless variations—with confidence.
Ditch the LeetCode Grindset: Think Architect, Not Coder
Most people approach coding interviews like a test: cramming facts, memorizing algorithms. That’s a fundamentally broken mental model. FAANG and other top-tier companies aren't checking your recall; they're assessing your problem-solving process. Can you break down a complex problem? Can you identify the right data structure? Can you articulate your thought process clearly, even when you're stuck? The interviewer isn't just looking at your final code; they're watching how you get there. They want to see you think like an engineer designing a system, not just a monkey typing code.
This means shifting your focus from "solve this problem" to "identify the pattern, then apply the right tools." Think of it like a chef. They don't memorize recipes for every dish; they learn fundamental techniques: sautéing, roasting, braising. Then they apply those techniques to whatever ingredients are on hand. Coding problems are the same.
The 8 Essential Patterns: Your Interview Toolkit
I’ve seen enough interviews to recognize that despite the infinite ways to phrase a question, they often boil down to a handful of core structures. Here are the big ones:
1. Two Pointers
This pattern is a workhorse, especially for array and string manipulation. You usually have two pointers, often starting at opposite ends or both at the beginning, moving towards each other or in the same direction. It's fantastic for reducing space complexity and sometimes time complexity too.
- Why it works: You can often compare, swap, or process elements in a single pass without needing extra storage. Think about validating palindromes or finding pairs that sum to a target in a sorted array.
- Key problems to master:
- Valid Palindrome: Check if a string is a palindrome, ignoring non-alphanumeric characters and case. (Think about the edge cases: empty strings, single characters.)
- Two Sum II (Sorted Array): Find two numbers in a sorted array that add up to a specific target. This is the canonical example.
- Remove Duplicates from Sorted Array: Modify an array in-place to remove duplicates, returning the new length. You're essentially consolidating unique elements at the beginning.
2. Sliding Window
When you need to find a subarray, substring, or a range of elements that satisfies a condition, the sliding window is your go-to. It's basically a subarray or substring that "slides" over the main array/string. The window size can be fixed or dynamic, expanding and shrinking.
- Why it works: It avoids redundant computations by only updating the window's state as it moves, instead of re-calculating for every possible subarray.
- Key problems to master:
- Longest Substring Without Repeating Characters: Find the length of the longest substring in a given string that doesn't contain any repeating characters. Your window expands, then shrinks when a duplicate is found.
- Minimum Size Subarray Sum: Find the minimal length of a contiguous subarray of which the sum is greater than or equal to a target. Here, the window shrinks from the left as soon as the sum condition is met.
- Permutation in String: Check if a string
s2contains a permutation ofs1. This involves maintaining character counts within your sliding window.
3. Fast & Slow Pointers (Floyd's Tortoise and Hare)
Primarily used for linked lists or detecting cycles. One pointer moves faster than the other, creating a gap that can detect loops, find the middle element, or determine specific meeting points.
- Why it works: The faster pointer eventually "catches up" to the slower one if a cycle exists. The distance between them can reveal properties of the cycle or list.
- Key problems to master:
- Linked List Cycle: Determine if a linked list has a cycle. This is the classic application.
- Find the Middle of a Linked List: The slow pointer reaches the middle when the fast pointer hits the end.
- Happy Number: Determine if a number is "happy" (repeatedly replace it with the sum of the squares of its digits until it becomes 1 or loops endlessly). This is a number theory problem disguised as a cycle detection problem.
4. Merge Intervals
This pattern handles overlapping intervals efficiently. You sort the intervals by their start times, then iterate, merging any overlaps.
- Why it works: Sorting by start times guarantees that if two intervals overlap, one will appear immediately after or before the other, simplifying the merge logic.
- Key problems to master:
- Merge Intervals: Given a collection of intervals, merge all overlapping intervals.
- Insert Interval: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). This often involves a preliminary sorting step or finding the correct insertion point.
- Meeting Rooms II: Given an array of meeting time intervals consisting of start and end times, find the minimum number of conference rooms required. This one uses a min-heap along with sorting to manage active meetings.
5. Cyclic Sort
When you have an array of numbers in a specific range (e.g., 1 to N), and you need to sort it or find missing/duplicate numbers in-place, cyclic sort is incredibly powerful. You place each number at its correct index.
- Why it works: Each number
ibelongs at indexi-1. If a number isn't at its correct spot, you swap it with the number that should be at its spot until everything is in order. It's often O(N) time because each number is swapped at most a few times. - Key problems to master:
- Find the Missing Number: Given an array containing
ndistinct numbers taken from0, 1, ..., n, find the one that is missing. - Find all Duplicate Numbers in an Array: Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice. Can be done without extra space.
- Find the First Missing Positive: Given an unsorted integer array, find the smallest missing positive integer. This is trickier because of zeros and negative numbers, but the core idea remains.
- Find the Missing Number: Given an array containing
6. Breadth-First Search (BFS) / Depth-First Search (DFS)
These are fundamental graph traversal algorithms, but they apply to trees, matrices, and even implicit graphs (like state-space search problems).
- BFS (Queue-based): Explores level by level. Good for finding the shortest path in unweighted graphs or problems that require processing elements in layers.
- DFS (Recursion/Stack-based): Explores as deeply as possible along each branch before backtracking. Good for pathfinding, cycle detection, and topological sorting.
- Key problems to master (3 BFS, 3 DFS):
- BFS - Binary Tree Level Order Traversal: Traverse a binary tree level by level. Use a queue to store nodes.
- BFS - Walls and Gates: Given a 2D grid, fill empty rooms with the distance to the nearest gate. This is a multi-source BFS.
- BFS - Number of Islands: Count the number of islands in a 2D grid. BFS from each unvisited land cell.
- DFS - Subsets: Given a set of distinct integers, return all possible subsets (the power set). This is a classic backtracking (DFS) problem.
- DFS - Permutations: Given a collection of distinct integers, return all possible permutations. Another backtracking staple.
- DFS - Valid Sudoku: Determine if a 9x9 Sudoku board is valid. While not a typical "graph traversal," the checking logic for rows, columns, and 3x3 boxes can be framed with recursive checks.
7. Dynamic Programming
Ah, DP. The one that strikes fear into many. It's about breaking down a problem into smaller overlapping subproblems and storing the results to avoid redundant calculations. Often involves a table (array or matrix) for memoization or tabulation.
- Why it works: You're avoiding re-computing solutions for the same subproblems repeatedly. If a problem can be broken down into smaller, identical problems whose solutions can be combined, DP is probably the answer.
- Key problems to master:
- Climbing Stairs: You are climbing a staircase. It takes
nsteps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? (Simple Fibonacci sequence variation). - Longest Common Subsequence: Find the length of the longest common subsequence between two strings. This is a classic 2D DP problem.
- Coin Change: Given coins of different denominations and a total amount of money, compute the fewest number of coins needed to make up that amount. (Often requires careful handling of base cases and infinities).
- Climbing Stairs: You are climbing a staircase. It takes
8. K-way Merge
When you're dealing with K sorted arrays or lists and need to combine them, or find the K smallest/largest elements across them, this pattern shines. A min-heap (or max-heap) is typically involved.
- Why it works: The heap efficiently keeps track of the smallest (or largest) element from each of the
Klists, allowing you to merge them in order without repeatedly scanning all lists. - Key problems to master:
- Merge K Sorted Lists: Merge
ksorted linked lists into one sorted linked list. - Kth Smallest Element in a Sorted Matrix: Find the
k-th smallest element in ann x nmatrix where each row and column is sorted in ascending order. (This is a bit of a twist, treating rows as separate sorted lists). - Find K Pairs with Smallest Sums: Given two sorted integer arrays
nums1andnums2and an integerk, return thekpairs(u,v)with the smallest sums.
- Merge K Sorted Lists: Merge
Beyond the Code: The Unspoken Rules of Interview Success
Knowing the patterns is half the battle. The other half is how you present yourself.
1. Communication is King, Seriously. Don't dive into coding immediately. Repeat the problem in your own words. Clarify edge cases. Discuss constraints. Ask "What if N is huge? What if the input is empty?" This shows you're thinking critically, not just reacting. Articulate your chosen pattern, why it fits, and walk through an example before you write a line of code.
2. Whiteboard vs. IDE: Most interviews are now virtual, but the "whiteboard" mentality persists. You're not expected to write perfect, production-ready code on the first pass. Focus on correctness, clear variable names, and logical flow. If you use an IDE, resist the urge to just hit "run" repeatedly without explaining your changes.
3. Test Cases Aren't Optional. Once you've written your solution, walk through a few test cases, including edge cases. A small example, an empty input, a single element, and a maximum-size input. This catches bugs, demonstrates your thoroughness, and gives you a chance to explain your code again. I've seen candidates get offers even with minor bugs if they find them themselves during testing and explain the fix.
4. Time and Space Complexity. Always, always, always state the time and space complexity of your solution. Then, if there's a better approach, discuss it. Even if you can't code the optimized version under pressure, showing you understand the trade-offs is crucial. "My current solution is O(N^2) time and O(N) space due to the hash map. We could potentially get this to O(N log N) if we sorted first and used two pointers, but that adds X complexity..." This kind of talk is what senior engineers do.
5. The "This Depends" Moment: Some problems have multiple valid solutions, each with different trade-offs. For instance, sometimes a slightly less optimal time complexity might be acceptable if it dramatically simplifies the code or reduces space usage in scenarios where memory is tight. Or, if the input size is always small, a brute-force O(N^2) solution might be perfectly fine, even "better" than a complex O(N log N) one, because it's easier to maintain. Don't be afraid to voice these considerations. It shows pragmatism and an understanding of real-world engineering constraints, not just theoretical computer science.
Practice Smart, Not Just Hard
You don't need to do 500 LeetCode problems. Pick 3-4 problems for each of these 8 patterns. Solve them, understand the pattern deeply, then try variations. Focus on understanding why a solution works, not just how to type it out. After you solve a problem, look at other solutions. Why are they different? Is one better? In what scenarios?
This framework isn't a magic bullet. You still need to put in the work. But it gives you a lens, a structure, to approach any coding problem. You'll stop seeing a random assortment of puzzles and start seeing variations of familiar themes. That's when you truly start acing interviews.
Ready to Ace Your Next Interview?
Practice with AI-powered mock interviews tailored to your target role and company. Start Practicing for Free | Explore Interview Prep
