Many coding interview problems look completely different on the surface, but underneath, they can be solved using the same handful of techniques.
We call these recurring techniques patterns.
Once you understand a pattern well, you can recognize it in an unfamiliar problem and start with an approach you already know how to apply.
This chapter covers twenty essential DSA pattern categories.
For each one, we'll understand how it works, look at its template, analyze its time and space complexity, and walk through an example to see it in action. The code examples use Java.
The idea is simple. We go through the input once, count how many times each element appears using a hash map, and then use those counts to solve the problem.
If the elements belong to a small, fixed set, like lowercase English letters, an array of size 26 works just as well.
Building the frequency map takes O(n) time and O(k) space, where k is the number of distinct elements.
In the Valid Anagram problem, we need to check whether two strings contain exactly the same characters with the same frequencies.
Consider the strings "listen" and "silent".
We increment the count for every character in the first string, so l, i, s, t, e, and n each have a count of 1.
Then we go through the second string and decrement each character's count, bringing every count back to 0.
If all the counts are 0 at the end, the strings are anagrams. Otherwise, they aren't.
This takes O(n) time, compared to O(n log n) if we sorted both strings.
Loading simulation...
Think of frequency counting whenever a problem involves duplicates, anagrams, or finding the most frequent or unique elements.
Instead of using nested loops, we maintain two pointers that move through the input, often allowing us to solve the problem in a single pass.
There are two common variants: opposite direction and same direction.
In the opposite direction variant, one pointer starts at the beginning, the other at the end, and they gradually move toward each other.
Suppose we're given the sorted array [1, 3, 4, 6, 8, 11], and we need to find two numbers that add up to 10.
The left pointer starts at 1, and the right pointer starts at 11. Their sum is 12, which is too large.
Since 1 is already the smallest available value, 11 can't form a valid pair with anything else. So we move the right pointer inward.
1 + 8 gives 9, which is too small. Since 8 is now the largest available value, 1 can't form a valid pair either. So we move the left pointer forward.
3 + 8 gives 11, so we move right inward. 3 + 6 gives 9, so we move left forward.
Finally, 4 + 6 gives 10, and we've found our pair.
Each step eliminates one element, giving us O(n) time and O(1) space, instead of O(n²) for checking every possible pair.
The same pattern helps us check whether a string is a palindrome and solve the Container With Most Water problem.
In the same direction variant, both pointers start near the beginning and move forward, often with one pointer reading and the other writing.
Let's remove duplicates in place from the sorted array [1, 1, 2, 2, 2, 3].
The slow pointer tracks the last unique value we've kept, while the fast pointer scans the remaining elements.
Slow starts at index 0. At index 1, fast encounters another 1, so we skip it.
At index 2, fast finds a 2, which is different from the value at slow. We move slow forward and copy the 2 into that position.
Fast skips the next two occurrences of 2, eventually finding a 3 at index 5. We move slow forward again and copy the 3 there.
The first three positions now contain 1, 2, and 3, giving us a new length of 3.
This also takes O(n) time and O(1) space.
Similar two-pointer techniques help us move zeroes to the end and merge two sorted arrays.
Loading simulation...
Think of two pointers when the input is sorted, when you're searching for pairs, or when you need to modify an array in place.
Sliding window is a variation of two pointers designed for problems involving contiguous subarrays or substrings.
The two pointers represent the boundaries of a window. As elements enter from the right and leave from the left, we update the window's state instead of calculating everything from scratch.
In the fixed-size variant, the window always contains k elements.
Let's find the maximum sum of three consecutive elements in the array [2, 1, 5, 1, 3, 2].
The first window has a sum of 8.
To slide the window forward, we add the incoming element and subtract the outgoing element. This gives us 7, then 9, then 6.
The maximum is 9, found in O(n) time instead of O(n · k), using constant extra space.
In the variable-size variant, the window expands and shrinks depending on a condition.
We move the right pointer forward, adding one element at a time.
Whenever the window becomes invalid, we remove elements from the left until it becomes valid again.
Then we update our answer using the current window.
Let's find the longest substring without repeating characters in "abcabcbb", using a set to track the characters inside the window.
The window first grows to "abc", with a length of 3.
The next a is already present, so we remove the first a from the left and add the new one, leaving "bca".
We continue the same process, and the longest valid window has a length of 3.
Each character enters and leaves the window at most once, giving us O(n) time and O(k) space for k distinct characters.
Loading simulation...
Use sliding window when looking for the longest, shortest, or number of contiguous subarrays or substrings that satisfy a condition.
The key is having a predictable way to adjust the window. For many sum-based problems, this works with non-negative numbers. With negative numbers, the next pattern is often a better fit.
Prefix sum lets us precompute running totals so we can calculate the sum of any range in constant time.
prefix[i] stores the sum of the first i elements, with prefix[0] initialized to 0.
For the array [3, 1, 4, 1, 5, 9], the prefix array becomes [0, 3, 4, 8, 9, 14, 23].
To find the sum from index i to index j, we subtract prefix[i] from prefix[j + 1].
So the sum from index 2 to 4 is 14 - 4, which gives 10.
Building the prefix array takes O(n) time and space, but every range sum query takes just O(1) time.
A useful variation combines prefix sums with a hash map to count subarrays that add up to a target k, even when the array contains negative numbers.
A subarray ending at the current index sums to k if an earlier prefix sum equals the current running sum minus k.
So we maintain the frequency of every prefix sum we've encountered, starting with 0 seen once.
Consider the array [1, 2, 3], with k equal to 3. The running sums are 1, 3, and 6.
At 1, we look for -2, which hasn't appeared.
At 3, we look for 0 and find the subarray containing 1 and 2.
At 6, we look for 3 and find the subarray containing just 3.
The answer is 2, found in O(n) time and space.
Loading simulation...
Think of prefix sums whenever you need to answer multiple range sum queries or count subarrays with a target sum.
Binary search finds a target in a sorted array by cutting the search space in half at every step. This gives us O(log n) time and O(1) space.
One template covers most binary search variations: finding the first position where a condition becomes true.
It works whenever the condition is false for an initial portion of the search space and true for the remaining portion.
We initialize lo to 0 and hi to n.
While lo is less than hi, we calculate mid and check the condition. If it's true, the answer could be at mid or somewhere to its left, so hi becomes mid. Otherwise, lo becomes mid + 1.
When the loop ends, lo points to the first position where the condition is true, or n if no such position exists.
Let's find the first occurrence of 5 in the array [1, 3, 5, 5, 5, 8, 9]. Our condition is that the value must be at least 5.
With lo at 0 and hi at 7, mid is 3. The value is 5, so hi becomes 3.
mid is now 1. The value is 3, so lo becomes 2.
Next, mid is 2. The value is 5, so hi becomes 2, and the search ends at index 2.
To find the last occurrence of 5, we search for the first value greater than 5 and move back one position.
Loading simulation...
Another useful variation is binary search on the answer.
Instead of searching through array indices, we search through possible answers and use a helper function to check whether each candidate works.
Consider the Koko Eating Bananas problem, with piles containing 3, 6, 7, and 11 bananas.
Koko can eat up to k bananas from a single pile each hour, and we need to find the minimum speed that lets her finish within 8 hours.
If a particular speed works, every faster speed also works. So we can binary search between 1 and 11, the size of the largest pile.
A speed of 6 requires 1, 1, 2, and 2 hours, for a total of 6 hours. That works, so we explore smaller speeds.
A speed of 3 takes 10 hours, which is too slow, so we search higher.
Speeds 5 and 4 both take 8 hours, and eventually the search converges at 4.
Each feasibility check takes O(n) time, and we perform O(log m) checks, where m is the largest pile. The total complexity is O(n log m) time and O(1) extra space.
Loading simulation...
Think of binary search when the input is sorted or when you need to find the smallest or largest value satisfying a monotonic condition, like a minimum capacity or speed.
Two patterns frequently appear in linked list problems.
The first is fast and slow pointers. Both pointers start at the head, but slow moves one node at a time, while fast moves two.
In the list 1 -> 2 -> 3 -> 4 -> 5, slow visits 1, 2, and 3, while fast visits 1, 3, and 5.
When fast can no longer move two steps, slow is at the middle node.
The same technique helps us detect cycles. If a cycle exists, fast eventually catches up to slow because it gains one node on every iteration. If fast reaches the end, there's no cycle.
Both operations take O(n) time and O(1) space.
Loading simulation...
The second pattern is in-place linked list reversal.
We maintain three references: prev, initially null, curr, initially pointing to the head, and next.
At each step, we save the next node, reverse curr's pointer so it points to prev, and then advance prev and curr.
For the list 1 -> 2 -> 3, we first make 1 point to null, then 2 point to 1, and finally 3 point to 2.
curr eventually becomes null, and prev points to 3, our new head.
This also takes O(n) time and O(1) space. Variations include reversing a portion of a list or reversing nodes in groups of k.
These two patterns also work well together. To check whether a linked list is a palindrome, we find its middle using fast and slow pointers, reverse the second half, and compare both halves.
A monotonic stack is a stack that maintains its elements in increasing or decreasing order.
It allows us to solve problems involving the next greater or next smaller element in a single pass.
For the next greater element, we iterate through the array's indices.
While the current value is greater than the value represented by the top index, we pop that index. We've just found its next greater element. Then we push the current index onto the stack.
In the Daily Temperatures problem, we need to find how many days we must wait for a warmer temperature.
The temperatures are [73, 74, 75, 71, 69, 72, 76, 73].
74 pops 73, and 75 pops 74. Both of those days wait just one day.
71 and 69 are pushed onto the stack above 75.
When 72 arrives, it pops 69, which waited one day, and 71, which waited two.
76 pops 72, which waited one day, and 75, which waited four days.
The final 73 gets pushed onto the stack. Every index still remaining has no warmer day ahead, so its answer is 0.
The result is [1, 1, 4, 2, 1, 1, 0, 0].
Every index is pushed and popped at most once, giving us O(n) time and O(n) space.
A decreasing stack helps find next greater elements, while an increasing stack helps find next smaller elements.
Loading simulation...
Think of monotonic stacks for next or previous greater and smaller elements, stock span, and the largest rectangle in a histogram.
Backtracking explores possible solutions by making one choice at a time and undoing that choice once a path is complete or can no longer lead to a valid solution.
The general template is a recursive function that receives the current partial solution.
Whenever we reach a valid solution, we record a copy. For each available choice, we make that choice, recurse, and then undo it before trying another.
Let's generate all subsets of [1, 2, 3].
Each recursive call records the current subset and tries adding elements that appear after the last chosen element. This avoids generating duplicates like [2, 1].
We start by recording the empty subset, followed by [1], then [1, 2], and finally [1, 2, 3].
We backtrack by removing 3 and then 2, before adding 3 to generate [1, 3].
Next, we return to the empty subset and explore [2], then [2, 3], and finally [3].
That gives us all eight possible subsets.
For permutations, we instead track which elements have already been used, allowing any unused element to be chosen next.
For constraint-based problems like N-Queens or Sudoku, we skip choices that violate a rule. This optimization is called pruning.
Backtracking often takes exponential or factorial time. Generating subsets takes O(n · 2ⁿ), while generating permutations takes O(n · n!).
Both use O(n) extra space for the recursion and current path, excluding the output.
Loading simulation...
Think of backtracking when a problem asks for all subsets, combinations, permutations, or valid arrangements. Small input constraints, like n up to 20, are often another clue.
Many binary tree problems come down to choosing the right traversal and performing some work at each node.
The depth-first template is a recursive function that returns when it reaches a null node. Otherwise, it processes the current node and recursively explores both children.
When we process the node determines the traversal order.
All four traversals take O(n) time. Depth-first traversals use O(h) space, where h is the tree's height, while level order uses space proportional to its maximum width.
Loading simulation...
Let's use postorder to find the diameter of a binary tree, which is the number of edges along the longest path between any two nodes.
Our tree has root 1, with children 2 and 3. Node 2 has children 4 and 5.
Each recursive call returns the height of its subtree, measured in nodes. Adding the left and right heights gives us the longest path through the current node, measured in edges.
Leaves 4 and 5 each return 1. The path through node 2 has two edges, and node 2 returns a height of 2.
Node 3 returns 1. So the path through the root has 2 + 1, or three edges, following 4, 2, 1, 3.
The diameter is 3, and we found it in a single traversal.
When a problem involves repeated prefix lookups across a collection of words, a trie lets us store those words once and efficiently search through their prefixes.
To insert a word, we walk through its characters, create any missing nodes, and mark the final node as the end of a word.
To search for a prefix, we follow its characters from the root. If the path doesn't exist, no word starts with that prefix. Otherwise, every stored word beneath that node shares it.
Both insertion and prefix lookup take O(L) time, where L is the length of the word or prefix. Storage is proportional to the total characters inserted in the worst case.
Consider the Search Suggestions problem, with the products mobile, mouse, moneypot, monitor, and mousepad.
As the user types "mouse", we need to display up to three matching products in alphabetical order.
After inserting all the products, typing m takes us to the node representing m. By exploring its children alphabetically, we find mobile, moneypot, and monitor.
Typing o produces the same three suggestions.
Typing u takes us to the node representing "mou", where we find mouse and mousepad. The remaining two letters keep those same suggestions.
Each keystroke advances one level in the trie, and we only explore the matching subtree to collect suggestions.
Another example is Word Search II, where we're looking for multiple words in a grid. A trie lets us abandon a search path as soon as it no longer matches any stored prefix.
Loading simulation...
Think of tries when solving autocomplete, prefix matching, or problems involving searches across multiple words.
A heap gives us access to the smallest or largest element in O(1) time, with insertion and removal taking O(log n).
There are two particularly useful patterns built around heaps.
The first is finding the top k elements. To find the k largest elements, we insert each element into a min-heap. Whenever its size exceeds k, we remove the smallest element.
By the end, the heap contains the k largest elements, giving us O(n log k) time and O(k) space.
Let's find the two most frequent elements in the array [1, 1, 1, 2, 2, 3].
First, we count their frequencies. 1 appears three times, 2 appears twice, and 3 appears once.
Then we insert each distinct element into a min-heap ordered by frequency. After inserting the third element, the heap exceeds its capacity, so we remove 3, the least frequent element.
We're left with 1 and 2. Notice how this problem combines frequency counting with a heap.
Loading simulation...
The second pattern is k-way merge, which combines k sorted lists into one sorted sequence.
We insert the first element from each list into a min-heap. Then we repeatedly remove the smallest element, add it to the result, and insert the next element from the same list.
For the lists [1, 4, 7], [2, 5, 8], and [3, 6, 9], the heap initially contains 1, 2, and 3.
We remove 1 and insert 4, remove 2 and insert 5, and continue until all nine elements have been merged.
Since the heap never contains more than k elements, this takes O(N log k) time, where N is the total number of elements, and O(k) extra space.
Loading simulation...
Think of heaps when finding the k largest, smallest, or most frequent elements, or when merging multiple sorted sequences.
Interval problems involve ranges with a start and an end, such as meetings or reservations.
Many of these problems follow a similar approach: sort the intervals, then sweep through them while tracking how they interact.
To merge overlapping intervals, we first sort them by their starting positions.
If the next interval starts before or at the end of the last merged interval, they overlap. We extend the merged interval to the larger of their ending positions. Otherwise, we start a new interval.
Let's merge [1, 3], [2, 6], [8, 10], [9, 12], and [15, 18].
[2, 6] overlaps with [1, 3], giving us [1, 6].
[8, 10] starts a new interval, and [9, 12] extends it to [8, 12].
[15, 18] starts another interval. Our final result is [1, 6], [8, 12], and [15, 18].
Sorting takes O(n log n) time, sweeping takes O(n) time, and the output uses O(n) space.
A related technique is the sweep line, which can help us find the minimum number of meeting rooms.
We represent each meeting as a start event that adds one and an end event that subtracts one. Then we sort the events by time and track the number of active meetings.
For meetings [0, 30], [5, 10], and [15, 20], the count goes 1, 2, 1, 2, 1, 0. The maximum is 2, so we need two rooms.
When a meeting starts at the exact time another ends, we process the end first because that room is available again.
Think of this pattern whenever the input contains ranges and the problem involves overlaps, merging, scheduling, or conflicts.
A greedy algorithm makes the best available choice at each step without reconsidering earlier decisions.
This only works when locally optimal choices lead to a globally optimal solution. So before using greedy, make sure you can explain why each choice is safe.
Many greedy algorithms sort the input using a particular criterion and then make a single pass, giving them O(n log n) or O(n) time.
In the array [2, 3, 1, 1, 4], each value represents the maximum distance we can jump from that position. We need to determine whether we can reach the last index.
Instead of exploring every possible jump, we simply track the farthest index we can reach.
From index 0, we can reach index 2. From index 1, we can extend our reach to index 4, which is the last index. So the answer is true.
If we ever encounter an index beyond our farthest reachable position, we know we can't move any further.
For the array [3, 2, 1, 0, 4], our farthest reachable index never extends beyond 3. So the answer is false.
This takes O(n) time and O(1) space.
But greedy doesn't work for every optimization problem.
Suppose we have coins worth 1, 3, and 4. To make 6, always choosing the largest available coin gives 4, 1, 1, using three coins. But 3 + 3 requires only two.
Dynamic programming is a better fit for this problem.
Think of greedy when you can justify making an irreversible choice, like selecting the earliest-ending meeting to maximize the number of non-overlapping meetings.
Some coding interview problems ask you to design a class or simulate a process instead of computing a single answer.
For design problems, start by identifying the required operations and their expected complexity. Then combine data structures that allow each operation to meet that target.
A classic example is the LRU cache, which supports get and put in O(1) time and evicts the least recently used entry when it reaches capacity.
A hash map provides fast lookups but doesn't maintain recency order. A doubly linked list maintains that order and allows us to move nodes in constant time, but it can't efficiently locate a key.
So we combine the two. The hash map maps each key to its corresponding node, while the linked list maintains nodes from most recently used to least recently used.
On get, we locate the node through the map and move it to the front of the list.
On put, we insert or update the node at the front. If we exceed capacity, we remove the tail node and delete its key from the map.
With a capacity of 2, we insert 1, then 2, so the list contains 2, 1.
Getting 1 moves it to the front.
Inserting 3 exceeds capacity, so we evict 2. A subsequent get for 2 returns -1.
Every operation takes O(1) time on average, and storage is proportional to the cache capacity.
Loading simulation...
Simulation problems, on the other hand, involve following a set of rules step by step, like traversing a matrix in spiral order or computing the next generation in Conway's Game of Life.
The key is maintaining the correct state. In the Game of Life, each cell's next state depends on the original grid, so we either write to a separate grid or encode both states within the same cell.
Depth-first search explores each path as far as possible before backtracking and exploring another path.
The recursive template marks the current node as visited, then recursively explores each unvisited neighbor. We can also implement it iteratively using an explicit stack.
In a grid, each cell represents a node, and its neighbors are typically the cells above, below, to the left, and to the right.
The grid version returns immediately if the current cell is out of bounds, blocked, or already visited. Otherwise, we mark it as visited and recursively explore all four neighbors.
This takes O(V + E) time for a graph, or O(m · n) for a grid, and O(V) extra space for the visited set and recursion.
Let's count the number of islands in a grid, where 1 represents land and 0 represents water.
We scan every cell. Whenever we encounter unvisited land, we increment the island count and run depth-first search to mark every connected land cell.
The two-by-two block in the top-left corner forms our first island. The isolated cell in the middle forms the second, and the two cells in the bottom-right corner form the third.
So the grid contains three islands.
Loading simulation...
Think of depth-first search for finding connected components, checking whether paths exist, filling regions, and detecting cycles.
Breadth-first search explores nodes in increasing order of their distance from the starting node, using a queue.
This means that in an unweighted graph, the first time we reach a node, we've found a shortest path to it.
The template begins by adding the starting node to the queue and marking it as visited.
While the queue isn't empty, we can capture its current size to determine how many nodes belong to the current level, then process exactly that many nodes.
For each node, we add its unvisited neighbors to the queue and immediately mark them as visited. This prevents the same node from being added multiple times.
The time complexity is O(V + E), and the space complexity is O(V).
A useful variation is multi-source breadth-first search, where we initialize the queue with multiple starting nodes.
Consider the Rotting Oranges problem. 2 represents a rotten orange, 1 represents a fresh orange, and 0 represents an empty cell.
Every minute, rotten oranges spread to adjacent fresh oranges. We need to find how long it takes for all oranges to become rotten.
We start by adding every rotten orange to the queue. Each level of spreading represents one minute.
During the first minute, the oranges to the right and below the initial rotten orange become rotten.
During the second minute, the top-right and center oranges become rotten.
The bottom-middle orange becomes rotten in minute 3, followed by the bottom-right orange in minute 4.
So the answer is 4. If any fresh orange remained after the search, the answer would be -1.
Loading simulation...
Think of breadth-first search when finding the minimum number of steps in an unweighted graph or grid, or when something spreads outward one level at a time.
Topological sort arranges the vertices of a directed acyclic graph so that for every edge from u to v, u appears before v.
It's especially useful for ordering tasks so that every task is completed after its dependencies.
One common implementation is Kahn's algorithm.
We first calculate the in-degree of every vertex, which represents the number of incoming edges. Then we add every vertex with an in-degree of 0 to a queue.
Next, we repeatedly remove a vertex, add it to our ordering, and decrease the in-degree of each of its neighbors. Whenever a neighbor's in-degree becomes 0, we add it to the queue.
If our ordering contains every vertex, we've found a valid topological order. Otherwise, the graph contains a cycle.
This takes O(V + E) time and O(V) extra space.
Suppose courses 1 and 2 require course 0, while course 3 requires both courses 1 and 2. As edges, that's 0 -> 1, 0 -> 2, 1 -> 3, and 2 -> 3.
The queue initially contains course 0, since it's the only course without prerequisites.
Removing 0 reduces the in-degree of courses 1 and 2 to 0, so both join the queue.
Removing course 1 reduces course 3's in-degree to 1. Removing course 2 reduces it to 0, so course 3 joins the queue last.
Our resulting order is 0, 1, 2, 3.
Now imagine course 0 also requires course 3. No course would start with an in-degree of 0, and the empty ordering would reveal that a cycle exists.
Loading simulation...
Think of topological sort whenever a problem involves prerequisites, build orders, task scheduling, or items that depend on one another.
Union find is useful when groups of elements merge over time, and we need to determine whether two elements belong to the same group.
The template uses a parent array, where every element initially acts as its own parent.
The find operation follows parent pointers until it reaches the root. Along the way, it can update those pointers to point directly to the root, an optimization called path compression.
The union operation finds the roots of both elements. If they're identical, the elements are already connected, so it returns false. Otherwise, it attaches the smaller tree beneath the larger one and returns true.
With these optimizations, each operation takes nearly constant amortized time, and the data structure uses O(n) space.
In the Redundant Connection problem, we're given a tree with one additional edge and need to identify that edge.
The edges connect 1 to 2, 1 to 3, and 2 to 3.
The first union connects 1 and 2. The second union adds 3 to the same group.
When we try to connect 2 and 3, we discover that they already share the same root. Adding this edge creates a cycle, so it's the redundant connection.
Union find can also count connected components. We start with n separate components and decrease the count after every successful union. It's also the core data structure behind Kruskal's minimum spanning tree algorithm.
Loading simulation...
Think of union find when connections are added over time and you need to answer connectivity questions without repeatedly traversing the entire graph.
For shortest paths in an unweighted graph, breadth-first search is enough. But when edges have non-negative weights, we typically use Dijkstra's algorithm.
We initialize every distance to infinity, except the source, which gets a distance of 0. Then we insert the source into a min-heap ordered by distance.
We repeatedly remove the node with the smallest distance. If that distance is greater than the currently recorded distance, we skip it because the entry is outdated.
For each neighbor, we check whether traveling through the current node produces a shorter path. If it does, we update the neighbor's distance and insert the new entry into the heap.
For a simple graph, this takes O((V + E) log V) time and O(V + E) space.
Consider these edges: A to B with weight 4, A to C with weight 1, C to B with weight 2, B to D with weight 1, and C to D with weight 5.
We first remove A, setting B's distance to 4 and C's distance to 1.
Next, we remove C. Traveling through C gives us a shorter path to B with a cost of 3. We update B to 3 and D to 6.
Then we remove B. Traveling through B reduces the distance to D from 6 to 4.
So the shortest path from A to D costs 4 and passes through C and B.
Dijkstra relies on non-negative weights because once a node's shortest distance is finalized, no later path can improve it.
For graphs with negative weights, Bellman-Ford repeatedly relaxes every edge in O(V · E) time. A variation also handles paths limited to k edges.
Loading simulation...
Think of shortest path algorithms whenever a problem asks for the minimum cost, time, or distance between nodes, such as network delay time or finding the cheapest flight route.
The idea is to break a problem into smaller subproblems, solve each relevant subproblem once, and store its result so we don't repeat the same work.
It works when the solution can be built from smaller versions of the same problem, and those smaller subproblems overlap.
The general template has four steps:
Loading simulation...
Let's start with a one-dimensional problem, House Robber.
The houses contain 2, 7, 9, 3, and 1. We can't rob adjacent houses, and our goal is to maximize the total money collected.
Let dp[i] represent the maximum amount we can rob from the first i + 1 houses.
At each house, we have two choices. We can skip it and keep dp[i - 1], or rob it and add its money to dp[i - 2].
dp[0] is 2, and dp[1] is 7.
dp[2] is the maximum of 7 and 2 + 9, which gives 11.
dp[3] remains 11, because 7 + 3 gives only 10.
dp[4] becomes 11 + 1, which is 12, achieved by robbing the houses containing 2, 9, and 1.
This takes O(n) time. Since each state depends only on the previous two states, we can reduce the space complexity to O(1).
Climbing Stairs, Coin Change, and Longest Increasing Subsequence are other examples of problems that can use one-dimensional dynamic programming.
When our state depends on two independent indices, such as positions within two strings, we often use a two-dimensional table.
Let's find the longest common subsequence between "abcde" and "ace".
Let dp[i][j] represent the length of the longest common subsequence between the first i characters of the first string and the first j characters of the second.
If the last characters of these two prefixes match, dp[i][j] equals dp[i - 1][j - 1] + 1.
If they don't match, we skip a character from either string and take the maximum of dp[i - 1][j] and dp[i][j - 1].
The first row and column represent comparisons involving an empty string, so we initialize them to 0.
We fill the table row by row, and the bottom-right cell contains our answer: 3, corresponding to the subsequence "ace".
This takes O(m · n) time and space. We can optimize the space to O(n) by maintaining just the previous and current rows.
Edit Distance, Unique Paths, and the 0/1 Knapsack problem follow a similar two-dimensional structure.
Loading simulation...
Think of dynamic programming when a problem asks for the number of possible ways, a minimum or maximum value, or whether something is achievable, and the same subproblems appear across different choices.
Recall the coin change example from the greedy section, with coins worth 1, 3, and 4 and a target of 6. Dynamic programming considers every available coin at each amount and correctly discovers the optimal two-coin solution.
When you encounter an unfamiliar problem, pay close attention to its wording and constraints. They often contain clues about which pattern to use.
Contiguous subarrays suggest sliding window or prefix sums, while sorted input often points toward two pointers or binary search.
Next greater or smaller elements suggest a monotonic stack, while generating every possible combination suggests backtracking.
Finding the top k elements suggests a heap, overlapping ranges suggest sorting and sweeping, and connections between entities suggest a graph-based approach.
When an optimal solution can be built from overlapping subproblems, think of dynamic programming.
Many problems also combine multiple patterns, like Top K Frequent Elements, which brings frequency counting and heaps together.
The goal isn't to memorize every solution. It's to understand these patterns well enough to recognize and adapt them to problems you've never seen before.