DSA Interview Cheat Sheet
Interview problems change; the patterns behind them don't. Once you can name the pattern, an unfamiliar question turns into a familiar recipe, and you stop needing to have seen that exact problem before.
These 13 patterns cover the large majority of coding rounds at product companies, service companies and startups. For each one you get what it is, when to use it, the classic problems (with our brute-force-to-optimal Java solutions), the key idea and a one-line trigger to spot it.
Quick reference
| # | Pattern | How to spot it |
|---|---|---|
| 1 | Two Pointers | "Sorted array" plus "find a pair / triplet / best pair" means two pointers first. |
| 2 | Sliding Window | "Contiguous", "substring" or "subarray" together with "longest / shortest / at most K" points to a sliding window. |
| 3 | Binary Search | "Sorted", "rotated", or "smallest speed / capacity / days such that" means binary search, often on the answer. |
| 4 | Hashing | "Find two that add up", "duplicate", "anagram" or "group" on unsorted data means reach for a hash map. |
| 5 | Stack and Queue | "Valid / balanced / nested" means stack; "next greater / warmer / span" means monotonic stack. |
| 6 | Linked List Patterns | "Linked list" plus "in place", "middle", "cycle" or "k-th from the end" means pointer rewiring or fast and slow pointers. |
| 7 | Trees (BFS and DFS) | "Level" or "row" means BFS; "path", "height", "subtree" or "ancestor" means DFS; "BST" means use the in-order order. |
| 8 | Graph Traversal | "Grid of 1s and 0s", "connected", "minimum moves" or "prerequisites" means graph traversal. |
| 9 | Recursion and Backtracking | "Return all possible", "every combination" or "place N items with no conflicts" means backtracking. |
| 10 | Dynamic Programming | "Number of ways", "minimum cost", "longest" or "can you reach" with choices that overlap means DP. |
| 11 | Greedy | "Minimum number of jumps / arrows / rooms" or "maximum non-overlapping" means try greedy, usually after sorting. |
| 12 | Heap / Priority Queue | "K-th", "top K", "closest K" or "median of a stream" means a heap. |
| 13 | Bit Manipulation | "Appears twice except one", "no extra space" or "without using + or -" means bit tricks. |
1Two Pointers
Two indices, usually called left and right, walk through an array or string from different positions and move based on a simple rule.
When to use it
- The input is sorted, or sorting it is allowed
- You need a pair or triplet that meets a target
- You compare or swap elements from both ends
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Two Sum II - Input Array Is Sorted | Medium | Read | LeetCode ↗ |
| Remove Duplicates from Sorted Array | Easy | Read | LeetCode ↗ |
| 3Sum | Medium | Read | LeetCode ↗ |
| Container With Most Water | Medium | Read | LeetCode ↗ |
| Trapping Rain Water | Hard | Read | LeetCode ↗ |
Key idea: Each comparison lets you safely discard one end, so the O(n²) check of every pair collapses into a single O(n) pass.
How to spot it: "Sorted array" plus "find a pair / triplet / best pair" means two pointers first.
Go deeper: Two Pointers
2Sliding Window
A window over a contiguous part of an array or string that grows on the right and shrinks on the left while you keep a running summary of what is inside.
When to use it
- The question is about a subarray or substring
- You want the longest, shortest, maximum or a count of windows
- A brute force would recompute overlapping ranges
Common problems
Key idea: Add the element entering the window and remove the one leaving, instead of recomputing; every element is touched at most twice, giving O(n).
Types: Fixed window: the size k is given; slide one step at a time. · Variable window: expand until the rule breaks, then shrink until it holds again.
How to spot it: "Contiguous", "substring" or "subarray" together with "longest / shortest / at most K" points to a sliding window.
Go deeper: Sliding Window
3Binary Search
Repeatedly halve a search space that is ordered, either an array or a range of possible answers.
When to use it
- The data is sorted or rotated-sorted
- You need a position, boundary or first/last occurrence
- You want the minimum or maximum value that satisfies a yes/no check
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Search Insert Position | Easy | Read | LeetCode ↗ |
| Search in Rotated Sorted Array | Medium | Read | LeetCode ↗ |
| Find Minimum in Rotated Sorted Array | Medium | Read | LeetCode ↗ |
| Koko Eating Bananas | Medium | Read | LeetCode ↗ |
| Median of Two Sorted Arrays | Hard | Read | LeetCode ↗ |
Key idea: Look at the middle and throw away the half that cannot contain the answer, turning O(n) into O(log n).
Types: On an array: find an index or boundary in sorted data. · On the answer: guess a value, check if it works, and narrow the range (Koko Eating Bananas).
How to spot it: "Sorted", "rotated", or "smallest speed / capacity / days such that" means binary search, often on the answer.
Go deeper: Binary Search
4Hashing
Use a hash map or set to remember what you have already seen, how often, or where.
When to use it
- You need O(1) "have I seen this?" lookups
- You are counting frequencies or grouping similar items
- You are matching pairs, such as a value and its complement
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Two Sum | Easy | Read | LeetCode ↗ |
| Valid Anagram | Easy | Read | LeetCode ↗ |
| Group Anagrams | Medium | Read | LeetCode ↗ |
| Longest Consecutive Sequence | Medium | Read | LeetCode ↗ |
| Subarray Sum Equals K | Medium | Read | LeetCode ↗ |
Key idea: Trade a little memory for speed: a map turns a nested search into a single pass with constant-time lookups.
How to spot it: "Find two that add up", "duplicate", "anagram" or "group" on unsorted data means reach for a hash map.
Go deeper: Hashing & Counting · Prefix Sum
5Stack and Queue
A stack handles last-in-first-out work such as matching and undoing; a monotonic stack or deque keeps elements in sorted order to answer "next bigger" or "window max" questions.
When to use it
- Matching brackets or cancelling adjacent pairs
- Next greater or smaller element, spans, histogram areas
- Evaluating expressions or maximum of a sliding window
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Valid Parentheses | Easy | Read | LeetCode ↗ |
| Min Stack | Medium | Read | LeetCode ↗ |
| Evaluate Reverse Polish Notation | Medium | Read | LeetCode ↗ |
| Daily Temperatures | Medium | Read | LeetCode ↗ |
| Largest Rectangle in Histogram | Hard | Read | LeetCode ↗ |
| Sliding Window Maximum | Hard | Read | LeetCode ↗ |
Key idea: Each element is pushed and popped at most once. In a monotonic stack, popping smaller items is exactly the moment they find their answer, so the whole scan is O(n).
How to spot it: "Valid / balanced / nested" means stack; "next greater / warmer / span" means monotonic stack.
Go deeper: Stack · Monotonic Stack · Queue & Monotonic Deque
6Linked List Patterns
Rewire next pointers in place, often with a dummy head, and use fast and slow pointers to find the middle or detect cycles.
When to use it
- The input is a linked list
- You must reverse, merge, reorder or remove nodes in place
- You need the middle, the nth node from the end, or cycle detection in O(1) space
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Reverse Linked List | Easy | Read | LeetCode ↗ |
| Merge Two Sorted Lists | Easy | Read | LeetCode ↗ |
| Linked List Cycle | Easy | Read | LeetCode ↗ |
| Remove Nth Node From End of List | Medium | Read | LeetCode ↗ |
| Reorder List | Medium | Read | LeetCode ↗ |
| Merge k Sorted Lists | Hard | Read | LeetCode ↗ |
Key idea: Save next before you change a pointer, and let a dummy node absorb the edge cases. Two pointers at different speeds find middles and cycles without extra memory.
How to spot it: "Linked list" plus "in place", "middle", "cycle" or "k-th from the end" means pointer rewiring or fast and slow pointers.
Go deeper: Linked List Techniques · Fast & Slow Pointers
7Trees (BFS and DFS)
Depth-first recursion builds a node's answer from its children; breadth-first traversal with a queue processes the tree level by level.
When to use it
- Heights, path sums, diameters or ancestors (DFS)
- Anything per level, a side view or minimum depth (BFS)
- A binary search tree, where in-order traversal gives sorted values
Common problems
Key idea: Trust the recursion: solve for the left and right subtrees, then combine. Every node is visited once, so traversals are O(n).
Types: DFS: pre-order, in-order or post-order recursion; post-order when parents need their children's answers. · BFS: a queue, processing exactly queue.size() nodes per level.
How to spot it: "Level" or "row" means BFS; "path", "height", "subtree" or "ancestor" means DFS; "BST" means use the in-order order.
Go deeper: Tree DFS · Tree BFS (Level Order) · Binary Search Tree & In-order
8Graph Traversal
Explore nodes and edges, including grids treated as graphs, with DFS or BFS while marking what you have visited.
When to use it
- Counting islands, regions or connected components
- Fewest steps or moves when every step costs the same (BFS)
- Ordering tasks with prerequisites (topological sort) or merging groups (union-find)
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Number of Islands | Medium | Read | LeetCode ↗ |
| Clone Graph | Medium | Read | LeetCode ↗ |
| Rotting Oranges | Medium | Read | LeetCode ↗ |
| Course Schedule | Medium | Read | LeetCode ↗ |
| Word Ladder | Hard | Read | LeetCode ↗ |
| Number of Provinces | Medium | Read | LeetCode ↗ |
Key idea: Mark a node visited the moment you reach it so nothing is processed twice: O(V + E). BFS reaches nodes in order of distance, which is why it finds shortest paths in unweighted graphs.
How to spot it: "Grid of 1s and 0s", "connected", "minimum moves" or "prerequisites" means graph traversal.
Go deeper: Graph DFS · Graph BFS · Topological Sort · Union-Find
9Recursion and Backtracking
Build a candidate one choice at a time, explore deeper, and undo the choice to try the next option, pruning branches that cannot work.
When to use it
- The problem asks for all subsets, permutations or combinations
- Placing items under constraints (N-Queens, Sudoku)
- Searching a board or tree of choices for a valid path
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Subsets | Medium | Read | LeetCode ↗ |
| Permutations | Medium | Read | LeetCode ↗ |
| Combination Sum | Medium | Read | LeetCode ↗ |
| Generate Parentheses | Medium | Read | LeetCode ↗ |
| Word Search | Medium | Read | LeetCode ↗ |
| N-Queens | Hard | Read | LeetCode ↗ |
Key idea: Choose, explore, un-choose. The work is still exponential because the output is, but pruning cuts dead branches early.
How to spot it: "Return all possible", "every combination" or "place N items with no conflicts" means backtracking.
Go deeper: Backtracking · Recursion & Divide and Conquer
10Dynamic Programming
Break a problem into overlapping subproblems, solve each once, and store the answers in a table or memo.
When to use it
- Counting ways, or finding a minimum or maximum over choices
- The same subproblem repeats in a recursive solution
- A choice at each step (take or skip, which coin, which character)
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Climbing Stairs | Easy | Read | LeetCode ↗ |
| House Robber | Medium | Read | LeetCode ↗ |
| Coin Change | Medium | Read | LeetCode ↗ |
| Longest Increasing Subsequence | Medium | Read | LeetCode ↗ |
| Longest Common Subsequence | Medium | Read | LeetCode ↗ |
| Edit Distance | Medium | Read | LeetCode ↗ |
Key idea: Define the state, write how it depends on smaller states, set the base cases, then fill in order. This turns exponential recursion into polynomial time.
Types: 1-D: climbing stairs, house robber. · Knapsack: coin change, subset sums. · Subsequences: LIS. · Grid: unique paths, minimum path sum. · Two strings: LCS, edit distance.
How to spot it: "Number of ways", "minimum cost", "longest" or "can you reach" with choices that overlap means DP.
Go deeper: 1-D Dynamic Programming · Knapsack DP · Longest Increasing Subsequence · Grid DP · String DP
11Greedy
Make the locally best choice at each step and never revisit it, when you can argue that this choice is always safe.
When to use it
- Scheduling or picking non-overlapping intervals
- Reachability or jump problems
- Sorting first reveals an obvious best next pick
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Jump Game | Medium | Read | LeetCode ↗ |
| Jump Game II | Medium | Read | LeetCode ↗ |
| Gas Station | Medium | Read | LeetCode ↗ |
| Merge Intervals | Medium | Read | LeetCode ↗ |
| Non-overlapping Intervals | Medium | Read | LeetCode ↗ |
Key idea: One pass, often after a sort, with no backtracking. Usually O(n) or O(n log n). Always test the rule against a counterexample before trusting it.
How to spot it: "Minimum number of jumps / arrows / rooms" or "maximum non-overlapping" means try greedy, usually after sorting.
Go deeper: Greedy · Intervals & Line Sweep
12Heap / Priority Queue
A heap always gives you the smallest or largest item quickly. Use it for top-K selection, merging sorted sources and processing things in priority order.
When to use it
- K largest, smallest, closest or most frequent
- Merging several sorted lists
- A running median, or always taking the next best task
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Kth Largest Element in an Array | Medium | Read | LeetCode ↗ |
| Top K Frequent Elements | Medium | Read | LeetCode ↗ |
| K Closest Points to Origin | Medium | Read | LeetCode ↗ |
| Task Scheduler | Medium | Read | LeetCode ↗ |
| Find Median from Data Stream | Hard | Read | LeetCode ↗ |
Key idea: Keep a heap of size k so each insert costs O(log k), giving O(n log k) instead of sorting everything in O(n log n).
How to spot it: "K-th", "top K", "closest K" or "median of a stream" means a heap.
Go deeper: Heap & Top-K · Two Heaps · K-Way Merge
13Bit Manipulation
Work directly on binary representations with XOR, AND, OR and shifts.
When to use it
- Every value appears twice except one
- Counting set bits or checking powers of two
- Arithmetic without + or -, or subsets as bitmasks
Common problems
| Problem | Level | Solution | Practice |
|---|---|---|---|
| Single Number | Easy | Read | LeetCode ↗ |
| Number of 1 Bits | Easy | Read | LeetCode ↗ |
| Counting Bits | Easy | Read | LeetCode ↗ |
| Missing Number | Easy | Read | LeetCode ↗ |
| Sum of Two Integers | Medium | Read | LeetCode ↗ |
Key idea: x ^ x = 0 cancels pairs, and n & (n - 1) clears the lowest set bit. Both give O(n) time with O(1) extra space.
How to spot it: "Appears twice except one", "no extra space" or "without using + or -" means bit tricks.
Go deeper: Bit Manipulation
20-pattern checklist
Tick each pattern once you can explain when to use it and code its template from memory. Each one opens the full guide.
- Two PointersSorted input, pairs or both ends
- Sliding WindowBest contiguous subarray or substring
- Prefix SumMany range-sum or subarray-sum queries
- HashingNeed O(1) lookups, counts or seen-before
- Binary SearchSorted data or a monotonic yes/no answer
- Fast & Slow PointersCycles, middle node, repeating sequences
- Linked List ReversalReverse all or part of a list in place
- Monotonic StackNext greater / smaller element
- Heap / Top-KK largest, K closest, running median
- Merge IntervalsOverlapping ranges, meetings, inserts
- GreedyA locally best choice is provably safe
- Tree DFSPaths, heights, subtree answers
- Tree BFSLevel by level, nearest, right-side view
- BacktrackingAll subsets, permutations, placements
- Graph BFS / DFSGrids, islands, shortest unweighted path
- Topological SortDependencies, course order, DAGs
- Union FindConnected components, cycle in undirected graph
- DijkstraShortest path with non-negative weights
- 1D DPAnswer for i builds on i-1, i-2 ...
- 2D DPGrids, two strings, item x capacity
Checklist based on the free Everything You Need to Get Placed list by Mohammad Fraz.
How to use this cheat sheet
- Read the problem twice and underline trigger words: sorted, contiguous, k-th, prerequisites, minimum steps.
- Name the pattern out loud before you code, and start with the brute force so you can explain the improvement.
- Solve 3-5 problems per pattern instead of hundreds at random, then revisit this page the night before an interview.
Want more depth? Every pattern has a full guide with templates, variations and common mistakes in Pattern Guides.