Coding interview patterns
Top 18 Coding Interview Patterns (LeetCode Patterns), Visualized
Stop solving random LeetCode problems. Master the 18 underlying patterns most coding interview questions are built on.
Coding Patterns
Curated Problems
Access
Starter Problems
Patterns You'll Master
Two Pointers & Sliding Window
Hash Maps & Frequency Counting
Fast & Slow Pointers (Floyd's)
Merge Intervals & Scheduling
Binary Search Variations
BFS & DFS on Trees & Graphs
Dynamic Programming (1D, 2D, Knapsack)
Backtracking & Subsets
Top K Elements & Heaps
Topological Sort
Choose a Pattern to Start
The 18 coding interview patterns, explained
Interview questions are rarely new. They are variations on a small number of underlying techniques, and the skill being tested is recognising which one a problem is asking for. Each pattern below covers what the technique does, how to spot it in a question you have not seen, and what it costs: followed by the problems where you can watch it run.
Two Pointers
37 problemsTwo indices walk the same array, usually from opposite ends toward each other or at different speeds. Each step, one pointer moves based on a comparison, so the pair sweeps the whole search space in a single pass instead of checking every combination.
The array is sorted, or sorting it does not lose information, and the question asks for a pair or triplet meeting some condition. "Find two numbers that sum to X", "the container holding the most water", "remove duplicates in place" are all this pattern. If your first instinct is a nested loop over the same array, check whether two pointers collapses it.
O(n) time and O(1) extra space, against O(n²) for the nested-loop version. When sorting is required first, the sort dominates at O(n log n).
Underlying concept: Two Pointers in the DSA visualizer curriculum
- Introduction to Two PointersFree
- Reverse StringPro
- Reverse Vowels of a StringPro
- Reverse Words in a StringPro
- Two Sum II - Input Array Is SortedFree
- Max Number of K-Sum PairsPro
- Valid PalindromePro
- Merge Strings AlternatelyPro
- Greatest Common Divisor of StringsPro
- Merge Sorted ArrayPro
- Remove Duplicates from Sorted ArrayPro
- String CompressionPro
- Remove ElementPro
- Rotate ArrayPro
- Next PermutationPro
- Repeated String MatchPro
- Find the Index of the First Occurrence in a StringFree
- Shortest PalindromePro
- Squares of a Sorted ArrayPro
- Is SubsequencePro
- Valid Palindrome IIPro
- Longest Palindromic SubstringPro
- Palindromic SubstringsPro
- Encode and Decode StringsPro
- Container With Most WaterPro
- 3-SumPro
- 3Sum ClosestPro
- 4SumPro
- Valid Triangle NumberPro
- Move ZeroesPro
- Sort ColorsPro
- Trapping Rain WaterPro
- Multiply StringsPro
- String to Integer (atoi)Pro
- Add BinaryPro
- Add StringsPro
- Plus OnePro
Hash Map
20 problemsRemember what you have already seen so a later step can look it up in O(1) on average instead of rescanning. The everyday forms: look up a complement (Two Sum), count frequencies (Valid Anagram, Top K Frequent Elements), group items under a key they share (Group Anagrams), and test membership with a set when only presence matters (Longest Consecutive Sequence).
The brute force is a nested loop whose inner loop asks "have I seen X before?", "how many times?" or "which items share this?": a hash map answers each.
O(n) time on average for one pass with O(1) average lookups, paid for with O(n) extra space for the map: against O(n²) time and O(1) space for the nested loop.
Underlying concept: Hash Map in the DSA visualizer curriculum
- Two SumFree
- Contains DuplicatePro
- Find the Difference of Two ArraysPro
- Unique Number of OccurrencesPro
- Valid AnagramPro
- Longest PalindromeFree
- Determine if Two Strings Are ClosePro
- Equal Row and Column PairsPro
- Group AnagramsPro
- Top K Frequent ElementsPro
- Longest Consecutive SequencePro
- Valid SudokuPro
- Detect SquaresPro
- Majority ElementPro
- Majority Element IIPro
- Isomorphic StringsPro
- Word PatternPro
- Ransom NotePro
- First Unique Character in a StringPro
- Roman to IntegerPro
Sliding Window
21 problemsA window defined by a left and right index moves across the data. The right edge extends to include new elements; the left edge advances only when the window breaks a constraint. Running totals update incrementally rather than being recomputed, so each element is visited a constant number of times.
The problem asks for the longest, shortest, or best contiguous subarray or substring satisfying a condition. The word "contiguous" is the tell, as is a fixed window size k. "Longest substring without repeating characters" and "maximum sum subarray of size k" are the canonical forms.
O(n) time (each index enters and leaves the window at most once) against O(n²) or O(n³) for recomputing every subarray.
Underlying concept: Sliding Window in the DSA visualizer curriculum
- Introduction to Sliding WindowFree
- Maximum Number of Vowels in a Substring of Given LengthPro
- Longest Subarray of 1's After Deleting One ElementPro
- Longest Substring Without Repeating CharactersFree
- Longest Repeating Character ReplacementPro
- Minimum Window SubstringPro
- Minimum Size Subarray SumPro
- Max Consecutive Ones IIIPro
- Binary Subarrays With SumPro
- Count Number of Nice SubarraysPro
- Number of Substrings Containing All Three CharactersPro
- Fruit Into BasketsPro
- Longest Substring with At Most K Distinct CharactersPro
- Number of Recent CallsPro
- Contains Duplicate IIPro
- Fixed-Length Sliding WindowPro
- Maximum Points You Can Obtain from CardsPro
- Maximum Sum of Distinct Subarrays With Length KPro
- Permutation in StringPro
- Find All Anagrams in a StringPro
- Sliding Window MaximumPro
Intervals
9 problemsIntervals are sorted by one endpoint, then swept in order while tracking what is currently open. Almost every interval problem reduces to sorting correctly and then handling one comparison between the current interval and the previous one.
The input is a list of start/end pairs (meetings, bookings, ranges) and the question involves merging, overlap, insertion or counting concurrency. If the input looks like [[1,3],[2,6],[8,10]], this is the pattern.
O(n log n), dominated by the sort; the sweep itself is O(n). Choosing the wrong sort key is the most common failure, and it is usually end time rather than start time.
Linked List
23 problemsPointer manipulation with no random access. Almost every linked list technique is one of three moves: run two pointers at different speeds, reverse a section in place, or use a dummy head so the first node needs no special case.
The input is a list rather than an array, and the question asks about cycles, the nth node from the end, reordering, or comparing the list against itself. The giveaway constraint is "do it in one pass" or "use O(1) extra space": both rule out copying into an array.
O(n) time and O(1) extra space for the pointer techniques. Copying into an array also gives O(n) time but costs O(n) space, which is usually the thing being tested.
Underlying concept: Linked List in the DSA visualizer curriculum
- Linked List OverviewFree
- Reverse Linked ListFree
- Middle of the Linked ListFree
- Delete the Middle Node of a Linked ListPro
- Odd Even Linked ListPro
- Maximum Twin Sum of a Linked ListPro
- Intersection of Two Linked ListsFree
- Merge Two Sorted ListsFree
- Add Two NumbersFree
- Linked List CycleFree
- Linked List Cycle IIFree
- Sort ListFree
- Rotate ListFree
- Palindrome Linked ListFree
- Remove Nth Node From End of ListFree
- Reorder ListFree
- Swap Nodes in PairsFree
- LRU CacheFree
- LFU CachePro
- Find the Duplicate NumberFree
- Copy List with Random PointerFree
- Reverse Nodes in k-GroupFree
- Happy NumberFree
Stack
24 problemsA stack holds elements whose fate is still undecided. The monotonic variant keeps its contents in sorted order by popping anything that violates that order as new elements arrive, and each pop is the moment an earlier element gets its answer.
The problem asks for the next greater or smaller element, needs matching pairs validated (brackets, tags), or involves undoing and revisiting recent state. Histogram and temperature problems are monotonic stack in disguise.
O(n) time, because every element is pushed once and popped at most once, against O(n²) for scanning forward from each position.
Underlying concept: Stack in the DSA visualizer curriculum
- Stack OverviewFree
- Valid ParenthesesFree
- Decode StringPro
- Longest Valid ParenthesesPro
- Monotonic Stack PatternPro
- Daily TemperaturesPro
- Largest Rectangle in HistogramPro
- Maximal RectanglePro
- Evaluate Reverse Polish NotationPro
- Min StackPro
- Implement Queue using StacksFree
- Car FleetPro
- Next Greater Element IPro
- Next Greater Element IIPro
- Asteroid CollisionPro
- Online Stock SpanPro
- Sum of Subarray MinimumsPro
- Sum of Subarray RangesPro
- Remove K DigitsPro
- Simplify PathPro
- Basic Calculator IIPro
- Basic CalculatorPro
- Removing Stars From a StringPro
- Remove All Adjacent Duplicates in StringPro
Binary Search
20 problemsHalve the search space on every comparison. The powerful form in interviews is not searching a sorted array but binary searching the answer itself: guess a value, ask a yes/no feasibility question, and discard half the range of possible answers.
The data is sorted or rotated-sorted, or (more often) the answer lies in a numeric range and there is a monotonic feasibility check ("if capacity C works, C+1 also works"). "Minimum capacity to ship packages in D days" is binary search on the answer.
O(log n) per search. Binary searching an answer range costs O(log(range) × cost of the feasibility check).
Underlying concept: Binary Search in the DSA visualizer curriculum
- Binary SearchFree
- Search Insert PositionPro
- First Bad VersionPro
- Guess Number Higher or LowerPro
- Successful Pairs of Spells and PotionsPro
- Search Suggestions SystemPro
- Single Element in a Sorted ArrayPro
- Sqrt(x)Pro
- Valid Perfect SquarePro
- Find Peak ElementPro
- Find a Peak Element IIPro
- Koko Eating Bananas (Apple Harvest)Pro
- Split Array Largest SumPro
- Search in Rotated Sorted ArrayPro
- Search in Rotated Sorted Array IIPro
- Find Minimum in Rotated Sorted ArrayPro
- Search a 2D MatrixPro
- Search a 2D Matrix IIPro
- Time Based Key-Value StorePro
- Median of Two Sorted ArraysPro
Heap / Priority Queue
16 problemsA heap keeps the smallest or largest element instantly reachable while allowing insertions and removals in logarithmic time. Keeping a heap of size k gives you the top k of a stream without ever sorting the whole input.
The question says "top k", "k largest", "k closest", "median of a stream", or requires repeatedly taking the current minimum, which is what makes it the engine inside Dijkstra and k-way merges.
O(n log k) for a top-k pass against O(n log n) for a full sort. Peeking is O(1); push and pop are O(log n).
Underlying concept: Heap / Priority Queue in the DSA visualizer curriculum
- Heap OverviewFree
- Kth Largest Element in an ArrayPro
- Smallest Number in Infinite SetPro
- Maximum Subsequence ScorePro
- Total Cost to Hire K WorkersPro
- Kth Largest Element in a StreamFree
- K Closest Points to OriginPro
- Find K Closest ElementsPro
- Merge K Sorted ListsPro
- Design TwitterPro
- Kth Smallest Element in a Sorted MatrixPro
- Find Median from Data StreamPro
- Last Stone WeightPro
- Network Delay TimePro
- Min Cost to Connect All PointsPro
- Swim in Rising WaterPro
Depth-First Search
46 problemsFollow one path as far as it goes, then back up and try the next. On trees this gives the preorder, inorder and postorder traversals; on graphs it needs a visited set to avoid revisiting nodes.
You need to explore every node, test whether a path exists, work with tree structure, or compute something that depends on a node's children before the node itself: the postorder shape behind most tree DP.
O(V + E) time. Space is O(h) for the recursion stack, where h is depth, which is O(n) in the worst case for a skewed tree.
Underlying concept: Depth-First Search in the DSA visualizer curriculum
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFSPro
- Invert Binary TreePro
- Maximum Depth of Binary TreePro
- Same TreePro
- Leaf-Similar TreesPro
- Balanced Binary TreePro
- Subtree of Another TreePro
- Path SumPro
- Passing Values Down (State)Pro
- Validate Binary Search TreePro
- Kth Smallest Element in a BSTPro
- Delete Node in a BSTPro
- Search in a Binary Search TreePro
- Insert into a Binary Search TreePro
- Inorder Successor in BSTPro
- Largest BST SubtreePro
- Vertical Order Traversal of a Binary TreePro
- Recover Binary Search TreePro
- Construct Binary Search Tree from Preorder TraversalPro
- Construct Binary Tree from Preorder and Inorder TraversalPro
- Serialize and Deserialize Binary TreePro
- Binary Tree TiltPro
- Diameter of Binary TreePro
- Lowest Common Ancestor of a Binary TreePro
- Path Sum IIPro
- Path Sum IIIPro
- Longest ZigZag Path in a Binary TreePro
- Count Good Nodes in Binary TreePro
- Longest Univalue PathPro
- Graphs OverviewPro
- Graph Representation: Adjacency ListPro
- Clone GraphPro
- Graph Valid TreePro
- Matrices as GraphsPro
- Flood FillPro
- Types of DFS (Tree Traversals)Pro
- Binary Tree Inorder TraversalFree
- Two Sum IV - Input is a BSTFree
- Number of IslandsPro
- Making A Large IslandPro
- Number of Distinct IslandsPro
- Surrounded RegionsPro
- Pacific Atlantic Water FlowFree
- Longest Increasing Path in a MatrixPro
Breadth-First Search
18 problemsExplore level by level using a queue: all nodes at distance 1, then all at distance 2, and so on. Because levels are visited in order, the first time a node is reached is guaranteed to be by a shortest path.
The question asks for the shortest path or minimum number of steps in an unweighted graph or grid, or for something computed per level ("level order traversal", "rightmost node of each row"). "Minimum number of moves" almost always means BFS.
O(V + E) time, O(V) space for the queue and visited set. On a grid that is O(rows × cols).
Underlying concept: Breadth-First Search in the DSA visualizer curriculum
- Introduction to BFSFree
- BFS OverviewFree
- Maximum Level Sum of a Binary TreePro
- Binary Tree Level Order TraversalPro
- Symmetric TreePro
- Binary Tree Right Side ViewPro
- Binary Tree Zigzag Level Order TraversalPro
- Maximum Width of Binary TreePro
- All Nodes Distance K in Binary TreePro
- Graphs OverviewFree
- Minimum Knight MovesPro
- Rotting OrangesPro
- Nearest Exit from Entrance in MazePro
- Walls and GatesPro
- 01 MatrixPro
- Bus RoutesPro
- Word LadderPro
- Cheapest Flights Within K StopsPro
Backtracking
17 problemsBuild a candidate solution one choice at a time. Recurse after each choice, and if the branch cannot lead to a valid answer, undo the choice and try the next. The undo step is what separates backtracking from plain recursion.
The problem asks for all permutations, all subsets, all combinations, or all ways of doing something, or it is a constraint puzzle like N-Queens or Sudoku. "Find every…" means backtracking.
Exponential by nature: O(2ⁿ) for subsets, O(n!) for permutations. Pruning invalid branches early is the only meaningful optimisation.
Underlying concept: Backtracking in the DSA visualizer curriculum
- Introduction to BacktrackingFree
- Solution Space TreesPro
- Subsets (Power Set)Pro
- PermutationsPro
- Permutations IIPro
- CombinationsPro
- Letter Case PermutationPro
- N-QueensPro
- Sudoku SolverPro
- Subsets IIPro
- Combination SumPro
- Combination Sum IIPro
- Combination Sum IIIPro
- Generate ParenthesesPro
- Word SearchPro
- Letter Combinations of a Phone NumberPro
- Palindrome PartitioningPro
Graphs (Topological Sort)
16 problemsTopological sort orders the nodes of a directed acyclic graph so every edge points forward. It is produced either by repeatedly removing nodes with no remaining prerequisites (Kahn's algorithm) or by reversing a DFS finish order.
Tasks have prerequisites and you need a valid order, or you need to detect whether the dependencies contain a cycle. Course schedules, build orders and dependency resolution are all this.
O(V + E). If the algorithm finishes having emitted fewer than V nodes, the graph contains a cycle, which is how cycle detection falls out for free.
Underlying concept: Graphs (Topological Sort) in the DSA visualizer curriculum
- Ordering Dependencies (Topological Sort)Free
- Course SchedulePro
- Course Schedule IIPro
- Minimum Height TreesPro
- Alien DictionaryPro
- Redundant ConnectionPro
- Accounts MergePro
- Critical Connections in a NetworkPro
- Keys and RoomsPro
- Number of ProvincesPro
- Reorder Routes to Make All Paths Lead to the City ZeroPro
- Evaluate DivisionPro
- Is Graph Bipartite?Pro
- Number of Operations to Make Network ConnectedPro
- Path With Minimum EffortPro
- Reconstruct ItineraryPro
Dynamic Programming
41 problemsSolve each distinct subproblem once and reuse the answer. Memoization caches results on top of the natural recursion; tabulation fills a table bottom-up. Both depend on finding a recurrence that expresses a problem in terms of smaller versions of itself.
The problem asks for a count of ways, a minimum or maximum over choices, or whether something is achievable, and a brute-force recursion would solve the same subproblem repeatedly. Overlapping subproblems plus optimal substructure is the signature.
Usually O(states × transitions). A 1D DP over n items is O(n); knapsack and most string DP are O(n × m). Space often reduces to one or two rows.
Underlying concept: Dynamic Programming in the DSA visualizer curriculum
- Intro to Dynamic ProgrammingFree
- Solving a Question with DPFree
- Fibonacci NumberPro
- N-th Tribonacci NumberPro
- Domino and Tromino TilingPro
- Counting BitsPro
- Pascal's TrianglePro
- Min Cost Climbing StairsPro
- House RobberPro
- House Robber IIPro
- House Robber IIIPro
- Coin ChangePro
- Coin Change IIPro
- Maximum Product SubarrayPro
- Combination Sum IVPro
- Partition Equal Subset SumPro
- Last Stone Weight IIPro
- Target SumPro
- Decode WaysPro
- Maximal SquarePro
- Unique PathsPro
- Unique Paths IIPro
- Minimum Path SumPro
- TrianglePro
- Longest Common SubsequencePro
- Longest Palindromic SubsequencePro
- Palindrome Partitioning IIPro
- Edit DistancePro
- Interleaving StringPro
- Distinct SubsequencesPro
- Regular Expression MatchingPro
- Wildcard MatchingPro
- Burst BalloonsPro
- Best Time to Buy and Sell Stock with CooldownPro
- Best Time to Buy and Sell Stock with Transaction FeePro
- Best Time to Buy and Sell Stock IIIPro
- Best Time to Buy and Sell Stock IVPro
- Longest Increasing SubsequencePro
- Number of Longest Increasing SubsequencePro
- Word BreakPro
- Maximum Profit in Job SchedulingPro
Greedy Algorithms
17 problemsTake the best-looking option at each step and never reconsider. Greedy produces short, fast solutions, but only for problems where the locally optimal choice is provably globally optimal, which is the part that has to be argued rather than assumed.
The problem asks for a maximum or minimum and there is a natural ordering that makes one choice obviously safest: earliest finishing time, largest value first. If a counterexample comes to mind quickly, the problem is dynamic programming instead.
Typically O(n log n) for the sort plus O(n) for a single pass.
Underlying concept: Greedy Algorithms in the DSA visualizer curriculum
- Introduction to Greedy AlgorithmsFree
- Kids With the Greatest Number of CandiesPro
- Can Place FlowersPro
- Dota2 SenatePro
- Best Time to Buy and Sell StockPro
- Best Time to Buy and Sell Stock IIPro
- Increasing Triplet SubsequencePro
- Gas StationPro
- Jump GamePro
- Jump Game IIPro
- Task SchedulerPro
- Partition LabelsPro
- Valid Parenthesis StringPro
- Hand of StraightsPro
- Merge Triplets to Form Target TripletPro
- Integer to RomanPro
- CandyPro
Trie
6 problemsA tree where each edge is a character, so words sharing a prefix share a path. Lookup cost depends on the length of the word rather than the number of words stored.
The problem involves prefixes (autocomplete, prefix search, word dictionaries) or repeatedly checks membership of many strings. Grid word-search problems use a trie to prune impossible branches early.
O(L) per insert or search, where L is word length, independent of how many words are stored. Space is O(total characters) in the worst case.
Underlying concept: Trie in the DSA visualizer curriculum
Prefix Sum
6 problemsPrecompute cumulative totals once, then answer any range-sum query as the difference of two prefix values. Pairing prefix sums with a hash map turns "count subarrays summing to k" into a single pass.
The problem asks about sums or counts over many subarrays or ranges, especially with repeated queries over unchanging data. "Subarray sum equals k" and "range sum query" are the standard forms.
O(n) preprocessing, then O(1) per range query: against O(n) per query when summing directly.
Underlying concept: Prefix Sum in the DSA visualizer curriculum
Matrices
3 problemsA 2D grid is a graph whose neighbours are implicit: each cell connects to the cells beside it. Most matrix problems are BFS, DFS or DP with row and column bookkeeping, plus in-place tricks for rotation and traversal.
The input is a 2D grid and the question involves islands, regions, flood fill, spiral or diagonal traversal, path counting, or rotating and transposing in place.
O(rows × cols) for a full traversal. In-place transformations keep space at O(1) beyond the input.
Bit Manipulation
10 problemsWork on the binary form of a number directly instead of on its decimal value. A few identities carry most interview questions: n & (n - 1) clears the lowest set bit, x ^ x = 0 cancels pairs, n >> 1 and n & 1 walk the bits one at a time, and & with ^ add two numbers without the + operator.
The problem talks about bits, binary representations, powers of two, or asks for O(1) extra space on a counting or "find the missing or single one" task, where XOR cancelling pairs or a bit mask replaces a hash set.
O(number of bits) per number, which is O(1) for fixed-width integers, with O(1) extra space: against O(n) extra space for the hash set or array a counting approach would use.
Underlying concept: Bit Manipulation in the DSA visualizer curriculum
Frequently asked questions
What are coding interview patterns?
A pattern is a reusable problem-solving technique (sliding window, two pointers, binary search on the answer) that applies across many different-looking questions. Interview problems are usually variations on a small set of these, so recognising which pattern a question wants is most of the work of solving it.
How many patterns do I actually need to know?
The 18 covered here are the ones that recur most often in technical interviews. They are not an exhaustive list of algorithmic techniques, and no fixed number guarantees coverage of any particular interview, but they are the set that gives the most return for the time invested.
Should I learn patterns or just solve more problems?
Solving problems without a framework tends to produce recall rather than transfer: you recognise questions you have seen and stall on ones you have not. Learning the pattern first gives you something to apply to an unfamiliar problem. Most people need both: the pattern to know what to try, and the practice to make it automatic.
Do I need to know data structures before starting patterns?
Yes, at least the fundamentals. Patterns are built on arrays, hash maps, stacks, trees and graphs. If those are shaky, work through the DSA visualizer curriculum first: it covers the same structures with a visualizer for each.
Are the pattern lessons free?
Each pattern includes free starter problems, marked "Free" in the lists above, which open without payment. The full library is part of a one-time purchase with lifetime access and no subscription.
