The DSA roadmap
The roadmap covers 24 topics, in the order they build on each other. Each topic splits into patterns. Every pattern says how to spot it, teaches the idea in a lesson, then lists the problems that practice it.
01Foundationsstart here10 patterns · 20 lessons50
The language skills every later topic assumes: reading input, loops, functions, basic maths and how to measure how fast code runs.
Thinking like a programmerYou are new to code, or you freeze when a problem has no obvious first step.
Data typesYou need to store a value in a type big enough and precise enough to hold it.2
ConditionsThe code must take a different path depending on a value.2
LoopsThe same step repeats a set number of times.2
Standard libraryA ready-made list, set or sort from your language does the job.3
Time and space complexityYou need to say how the running time grows before you write any code.
Loops through pattern printingYou want nested loops to feel automatic before you meet real problems.22
- How to read a pattern: rows, columns and what changesRead
- Square of starsSolveEasy
- Right triangle of starsSolveEasy
- Right triangle of numbersSolveEasy
- Triangle of repeated numbersSolveEasy
- Inverted right triangle of starsSolveEasy
- Inverted right triangle of numbersSolveEasy
- Star pyramidSolveEasy
- Inverted star pyramidSolveEasy
- Star diamondSolveEasy
- Half diamondSolveEasy
- Alternating binary triangleSolveEasy
- Number crownSolveEasy
- Increasing number triangleSolveEasy
- Increasing letter triangleSolveEasy
- Reverse letter triangleSolveEasy
- Letter rampSolveEasy
- Letter pyramidSolveEasy
- Letter triangle from the endSolveEasy
- Symmetric voidSolveMedium
- Symmetric butterflySolveMedium
- Hollow squareSolveMedium
- Concentric number squaresSolveMedium
Working with digits and divisorsThe input is a number and you need to take it apart digit by digit or find what divides it.10
- Extracting digits with % and /Read
- Count the digits of a numberSolveEasy
- Count the odd digits of a numberSolveEasy
- Largest digit of a numberSolveEasy
- Palindrome NumberSolveEasy
- Armstrong NumberSolveEasy
- Divisors and primes in O(√n)Read
- All divisors of a numberSolveMedium
- Check whether a number is primeSolveMedium
- Perfect NumberSolveEasy
- GCD with the Euclidean algorithmRead
- GCD of two numbersSolveMedium
- LCM of two numbersSolveMedium
Recursion basicsA function needs to solve a smaller copy of the same problem.5
- How recursion works: base case and the call stackRead
- Print something N times with recursionSolveEasy
- Passing the answer down or returning it upRead
- Drawing the recursion tree to count callsRead
- Sum of the first N numbersSolveEasy
- Factorial of NSolveEasy
- Sum of the digits of a numberSolveEasy
- Fibonacci Number147 DSA SheetSolveEasy
Counting with arrays and mapsYou need how often each value appears, and an array index or a map key can hold the count.4
02Arrays and Hashingafter Foundations7 patterns · 3 lessons44
Most problems start with an array and a hash map. This topic teaches the moves that every later topic reuses.
Array basicsYou need to scan an array once to find, count or move elements.12
- Arrays in memory: indexing, copying and resizingRead
- Linear searchSolveEasy
- Largest elementSolveEasy
- Second largest elementSolveEasy
- Sum of array elementsSolveEasy
- Count the odd numbers in an arraySolveEasy
- Reverse an arraySolveEasy
- Check whether an array is sortedSolveEasy
- Max Consecutive OnesSolveEasy
- Find All Numbers Disappeared in an ArraySolveEasy
- Left rotate an array by oneSolveEasy
- Rotate ArraySolveMedium
- Leaders in an arraySolveMedium
Hash map lookupsYou need to know in one step whether you have seen a value before.9
- Two Sum147 DSA SheetSolveEasy
- Contains Duplicate147 DSA SheetSolveEasy
- Valid Anagram147 DSA SheetSolveEasy
- Group Anagrams147 DSA SheetSolveMedium
- Longest Consecutive Sequence147 DSA SheetSolveMedium
- Valid SudokuSolveMedium
- Encode and Decode StringsSolveMedium
- First Unique Character in a StringSolveEasy
- First Missing PositiveSolveHard
Counting and votingThe answer depends on how often each value appears.4
- Top K Frequent Elements147 DSA SheetSolveMedium
- Majority Element147 DSA SheetSolveEasy
- Majority Element IISolveMedium
- Detect SquaresSolveMedium
One pass with running stateYou keep one or two values as you scan, and the answer is ready at the end.3
- Best Time to Buy and Sell Stock147 DSA SheetSolveEasy
- Maximum Subarray147 DSA SheetSolveMedium
- Maximum Product Subarray147 DSA SheetSolveMedium
Prefix sumsThe question is about the sum of a subarray, and adding it up again for every range is too slow.10
- Prefix sums and the running-sum mapRead
- Product of Array Except Self147 DSA SheetSolveMedium
- Subarray Sum Equals K147 DSA SheetSolveMedium
- Maximum Size Subarray Sum Equals kSolveMedium
- Range Sum Query - ImmutableSolveEasy
- Range Sum Query 2D - ImmutableSolveMedium
- Contiguous ArraySolveMedium
- Subarray Sums Divisible by KSolveMedium
- Continuous Subarray SumSolveMedium
- Longest subarray with sum 0SolveMedium
- Count subarrays with given xor KSolveMedium
Difference arraysMany updates each add a value to a whole range, and you need the array after all of them.3
Walking a matrixThe input is a grid, and the work is moving through it in a fixed order.3
- Spiral Matrix147 DSA SheetSolveMedium
- Rotate ImageSolveMedium
- Set Matrix ZeroesSolveMedium
03Mathafter Foundations4 patterns · 3 lessons14
A few problems test arithmetic more than data structures. Each one has a single idea to learn.
Number tricksThe input is a number, or digits stored in a string or an array.8
- Plus One147 DSA SheetSolveEasy
- Happy NumberSolveEasy
- Pow(x, n)147 DSA SheetSolveMedium
- Reverse IntegerSolveMedium
- Multiply StringsSolveMedium
- Count PrimesSolveMedium
- Ugly NumberSolveEasy
- Nim GameSolveEasy
Primes and the sieveYou need primes or prime factors for many numbers at once.2
Fast power and modular arithmeticThe answer is huge, so you work modulo a prime and square as you go.1
Pascal's triangle and combinationsYou need nCr, or the rows of Pascal's triangle.3
04Bit Manipulationafter Arrays and Hashing4 patterns · 2 lessons20
Integers are rows of bits. A few operators, mostly XOR and shifts, solve problems that seem to need extra memory.
Bit basicsYou need to read, set or clear one bit of a number.7
XOR tricksEvery value appears twice except one or two, or one value is missing.6
- Single Number147 DSA SheetSolveEasy
- Missing Number147 DSA SheetSolveEasy
- Single Number IISolveMedium
- Single Number IIISolveMedium
- Set MismatchSolveEasy
- XOR of all numbers in a rangeSolveMedium
Counting and shifting bitsThe question is about the bits of a number.6
- Number of 1 Bits147 DSA SheetSolveEasy
- Counting Bits147 DSA SheetSolveEasy
- Reverse Bits147 DSA SheetSolveEasy
- Sum of Two IntegersSolveMedium
- Divide Two IntegersSolveMedium
- Bitwise AND of Numbers RangeSolveMedium
BitmasksThe input is small enough that every subset fits in an integer.1
05Stringsafter Arrays and Hashing4 patterns · 1 lesson20
Strings are arrays of characters with a few traps: they are often immutable, and building one in a loop can be quadratic.
String basicsYou need to reverse, compare or rebuild a string character by character.10
- Strings in memory: immutability and building strings efficientlyRead
- Reverse StringSolveEasy
- Valid Palindrome IISolveEasy
- Largest Odd Number in StringSolveEasy
- Longest Common Prefix147 DSA SheetSolveEasy
- Isomorphic StringsSolveEasy
- Rotate StringSolveEasy
- Longest PalindromeSolveEasy
- Reverse Words in a StringSolveMedium
- String CompressionSolveMedium
- Count and SaySolveMedium
Parentheses and nestingThe string is made of brackets and you track how deep you are.4
Parsing and conversionYou turn text into a number or a number into text, with every edge case handled.3
Counting over substringsYou need a statistic for every substring, and there are O(n²) of them.3
06Sortingafter Arrays and Hashing3 patterns · 4 lessons11
Knowing how the sorts work tells you what a sort costs, when order is kept, and when a problem is really a sorting problem.
Simple sortsYou need to understand O(n²) sorting well enough to write it without thinking.5
Divide-and-conquer sortsYou need O(n log n), and splitting the array in half is the way in.4
Counting during merge sortYou must count pairs where an earlier value is larger than a later one.2
07Two Pointersafter Arrays and Hashing3 patterns · 1 lesson18
Two indexes move through the same array. One pass then does the work of two nested loops.
Pointers from both endsThe array is sorted, or can be, and you are looking for a pair.9
- Two pointers: why one pass is enoughRead
- Valid Palindrome147 DSA SheetSolveEasy
- Two Sum II - Input Array Is Sorted147 DSA SheetSolveMedium
- 3Sum147 DSA SheetSolveMedium
- Container With Most Water147 DSA SheetSolveMedium
- 4SumSolveMedium
- Trapping Rain Water147 DSA SheetSolveHard
- Squares of a Sorted ArraySolveEasy
- 3Sum ClosestSolveMedium
- Boats to Save PeopleSolveMedium
Rearranging in placeYou must reorder the array without making a second one.5
- Sort Colors147 DSA SheetSolveMedium
- Next Permutation147 DSA SheetSolveMedium
- Move ZeroesSolveEasy
- Remove Duplicates from Sorted ArraySolveEasy
- Rearrange Array Elements by SignSolveMedium
Merging sorted arraysYou have two sorted sequences and need their union, intersection or merge.4
08Sliding Windowafter Two Pointers3 patterns · 2 lessons16
A window over a range grows on one side and shrinks on the other. Each element enters once and leaves once.
Longest or shortest windowThe question asks for the longest or shortest substring or subarray that meets a condition.8
- The sliding window template: grow, then shrinkRead
- Longest Substring Without Repeating Characters147 DSA SheetSolveMedium
- Max Consecutive Ones III147 DSA SheetSolveMedium
- Longest Repeating Character Replacement147 DSA SheetSolveMedium
- Longest Substring with At Most K Distinct CharactersSolveMedium
- Minimum Window Substring147 DSA SheetSolveHard
- Minimum Size Subarray SumSolveMedium
- Fruit Into BasketsSolveMedium
- Minimum Window SubsequenceSolveHard
Fixed-size windowThe window size is given, so each step adds one element and removes one.4
- Permutation in String147 DSA SheetSolveMedium
- Maximum Points You Can Obtain from Cards147 DSA SheetSolveMedium
- Maximum Average Subarray ISolveEasy
- Find All Anagrams in a StringSolveMedium
Counting windowsThe question asks how many subarrays meet a condition, not which one is longest.4
09Binary Searchafter Arrays and Hashing5 patterns · 2 lessons36
Each step throws away half of what is left. It works on sorted arrays, and on any answer you can check with a yes or no.
Lower and upper boundsYou need the first position where a condition becomes true.8
- Binary search without off-by-one errors: the invariantRead
- Lower boundSolveMedium
- Upper boundSolveMedium
- Search Insert PositionSolveEasy
- Floor and ceil in a sorted arraySolveMedium
- Find First and Last Position of Element in Sorted ArraySolveMedium
- Count occurrences in a sorted arraySolveMedium
- How many times is a sorted array rotatedSolveMedium
- Peak Index in a Mountain ArraySolveMedium
Searching a sorted arrayThe input is sorted, or sorted and then rotated.7
- Binary Search147 DSA SheetSolveEasy
- Search in Rotated Sorted Array147 DSA SheetSolveMedium
- Find Minimum in Rotated Sorted Array147 DSA SheetSolveMedium
- Search in Rotated Sorted Array IISolveMedium
- Single Element in a Sorted ArraySolveMedium
- Find Peak Element147 DSA SheetSolveMedium
- Time Based Key-Value StoreSolveMedium
Searching the answerYou cannot compute the answer directly, but you can quickly check whether a given value works.13
- Binary search on the answer: the monotonic checkRead
- Sqrt(x)147 DSA SheetSolveEasy
- Koko Eating Bananas147 DSA SheetSolveMedium
- Magnetic Force Between Two Balls147 DSA SheetSolveMedium
- Split Array Largest Sum147 DSA SheetSolveHard
- Nth root of a numberSolveMedium
- Find the Smallest Divisor Given a ThresholdSolveMedium
- Minimum Number of Days to Make m BouquetsSolveMedium
- Capacity To Ship Packages Within D DaysSolveMedium
- Kth Missing Positive NumberSolveEasy
- Aggressive cowsSolveHard
- Book allocationSolveHard
- Painter's partitionSolveHard
- Minimize Max Distance to Gas StationSolveHard
Searching a matrixThe input is a sorted matrix, and you search rows, columns or values.6
Partition searchYou need the median or the k-th element of two sorted arrays.2
- Median of Two Sorted Arrays147 DSA SheetSolveHard
- K-th element of two sorted arraysSolveHard
10Linked Listsafter Two Pointers5 patterns · 4 lessons52
Linked list problems are about moving pointers without losing the rest of the list.
Singly linked list basicsYou need to walk, insert into or delete from a linked list by hand.14
- Linked lists: nodes, pointers and the headRead
- Traverse a linked listSolveEasy
- Length of a linked listSolveEasy
- Search in a linked listSolveEasy
- Insert at the headSolveMedium
- Insert at the tailSolveMedium
- Insert at position KSolveMedium
- Insert before the value XSolveMedium
- Delete the headSolveMedium
- Delete the tailSolveMedium
- Delete the K-th nodeSolveMedium
- Delete the node with value XSolveMedium
- Delete Node in a Linked ListSolveMedium
- Remove Linked List ElementsSolveEasy
- Design Linked ListSolveMedium
Doubly linked listsEach node also points back, so you must keep two links right on every change.13
- Doubly linked lists: keeping prev and next in stepRead
- Build a doubly linked list from an arraySolveMedium
- Insert before the headSolveMedium
- Insert before the tailSolveMedium
- Insert before the K-th nodeSolveMedium
- Insert before a given nodeSolveMedium
- Delete the headSolveMedium
- Delete the tailSolveMedium
- Delete the K-th nodeSolveMedium
- Delete a given nodeSolveMedium
- Reverse a doubly linked listSolveMedium
- Delete every occurrence of a keySolveMedium
- Remove duplicates from a sorted doubly linked listSolveMedium
- Pairs with a given sum in a doubly linked listSolveMedium
Fast and slow pointersYou need the middle, a cycle, or a node counted from the end.9
- Fast and slow pointers: why they meetRead
- Middle of the Linked List147 DSA SheetSolveEasy
- Linked List Cycle147 DSA SheetSolveEasy
- Remove Nth Node From End of List147 DSA SheetSolveMedium
- Palindrome Linked ListSolveEasy
- Intersection of Two Linked ListsSolveEasy
- Linked List Cycle II147 DSA SheetSolveMedium
- Find the Duplicate NumberSolveMedium
- Delete the Middle Node of a Linked ListSolveMedium
- Length of the loop in a linked listSolveEasy
Reversing and rewiringThe answer is the same nodes, connected in a different order.14
- The dummy node trickRead
- Reverse Linked List147 DSA SheetSolveEasy
- Merge Two Sorted Lists147 DSA SheetSolveEasy
- Reorder List147 DSA SheetSolveMedium
- Add Two Numbers147 DSA SheetSolveMedium
- Rotate ListSolveMedium
- Sort ListSolveMedium
- Copy List with Random Pointer147 DSA SheetSolveMedium
- Reverse Nodes in k-Group147 DSA SheetSolveHard
- Odd Even Linked ListSolveMedium
- Reverse Linked List IISolveMedium
- Plus One Linked ListSolveMedium
- Next Greater Node In Linked ListSolveMedium
- Sort a linked list of 0s, 1s and 2sSolveMedium
- Flatten a linked listSolveHard
11Stacks and Queuesafter Arrays and Hashing, Linked Lists5 patterns · 3 lessons39
A stack remembers what is still open. The last thing you pushed is the first thing you need.
Building stacks and queuesYou need to implement a stack or queue yourself, or build one from the other.8
- Stacks and queues: operations, uses and costsRead
- Implement a stack with an arraySolveMedium
- Implement a queue with an arraySolveMedium
- Implement a stack with a linked listSolveMedium
- Implement a queue with a linked listSolveMedium
- Implement Stack using QueuesSolveEasy
- Implement Queue using StacksSolveEasy
- Design Circular QueueSolveMedium
- Design Circular DequeSolveMedium
Matching and cancellingEach new item either cancels the most recent open item or waits on top of it.10
- Valid Parentheses147 DSA SheetSolveEasy
- Min Stack147 DSA SheetSolveMedium
- Evaluate Reverse Polish Notation147 DSA SheetSolveMedium
- Asteroid CollisionSolveMedium
- Find the CelebritySolveMedium
- Baseball GameSolveEasy
- Backspace String CompareSolveEasy
- Simplify PathSolveMedium
- Decode StringSolveMedium
- Basic Calculator IISolveMedium
Infix, prefix and postfixYou need to convert or evaluate an expression written in another notation.6
Monotonic stackFor each element you need the next or previous element that is larger or smaller.13
- The monotonic stack templateRead
- Next Greater Element I147 DSA SheetSolveEasy
- Daily Temperatures147 DSA SheetSolveMedium
- Next Greater Element IISolveMedium
- Online Stock SpanSolveMedium
- Car Fleet147 DSA SheetSolveMedium
- Remove K DigitsSolveMedium
- Sum of Subarray MinimumsSolveMedium
- Sum of Subarray RangesSolveMedium
- Largest Rectangle in Histogram147 DSA SheetSolveHard
- Maximal RectangleSolveHard
- Next smaller elementSolveMedium
- Number of greater elements to the rightSolveMedium
- 132 PatternSolveMedium
Monotonic queueYou need the largest or smallest value of every window as it slides.2
- Sliding Window Maximum147 DSA SheetSolveHard
- Sliding Window MedianSolveHard
12Recursion and Backtrackingafter Arrays and Hashing4 patterns · 3 lessons25
Recursion tries one choice and explores everything after it. Then it undoes the choice and tries the next one.
Pick or skipEach element is either in or out, and you need every choice or a count of them.3
Recursion on a stackYou may use only the stack's own push and pop, so the call stack holds the rest.2
Generating every choiceThe question asks for all subsets, combinations or permutations.12
- Backtracking: choose, explore, undoRead
- Subsets147 DSA SheetSolveMedium
- Permutations147 DSA SheetSolveMedium
- Subsets II147 DSA SheetSolveMedium
- Combination Sum147 DSA SheetSolveMedium
- Combination Sum II147 DSA SheetSolveMedium
- Letter Combinations of a Phone Number147 DSA SheetSolveMedium
- Generate Parentheses147 DSA SheetSolveMedium
- Palindrome Partitioning147 DSA SheetSolveMedium
- CombinationsSolveMedium
- Permutations IISolveMedium
- Combination Sum IIISolveMedium
- Gray CodeSolveMedium
Searching with constraintsMost choices break a rule, so you check each one early and stop exploring it.8
- Pruning: stopping a branch earlyRead
- Word Search147 DSA SheetSolveMedium
- N-Queens147 DSA SheetSolveHard
- Sudoku SolverSolveHard
- Rat in a mazeSolveHard
- M-coloringSolveHard
- Beautiful ArrangementSolveMedium
- Word Break IISolveHard
- Expression Add OperatorsSolveHard
13Binary Treesafter Recursion and Backtracking4 patterns · 7 lessons44
Almost every tree problem is one recursive function. The skill is deciding what each call returns to its parent.
TraversalsYou need to visit every node in a set order: pre, in, post or level.6
- Trees: nodes, depth, height and how they are storedRead
- Preorder, inorder and postorderRead
- Binary Tree Preorder TraversalSolveEasy
- Binary Tree Inorder TraversalSolveEasy
- Binary Tree Postorder TraversalSolveEasy
- Iterative traversals with an explicit stackRead
- Preorder, inorder and postorder in one passSolveMedium
- Morris traversal: O(1) space by threading the treeRead
- Morris inorder traversalSolveHard
- Morris preorder traversalSolveHard
Depth first: return a value upThe answer for a node depends on the answers for its children.23
- What should a recursive call return?Read
- Maximum Depth of Binary Tree147 DSA SheetSolveEasy
- Invert Binary Tree147 DSA SheetSolveEasy
- Same Tree147 DSA SheetSolveEasy
- Subtree of Another Tree147 DSA SheetSolveEasy
- Balanced Binary TreeSolveEasy
- Diameter of Binary Tree147 DSA SheetSolveEasy
- Count Good Nodes in Binary TreeSolveMedium
- Binary Tree PathsSolveEasy
- Lowest Common Ancestor of a Binary Tree147 DSA SheetSolveMedium
- Binary Tree Maximum Path Sum147 DSA SheetSolveHard
- Boundary of Binary TreeSolveMedium
- Minimum Depth of Binary TreeSolveEasy
- Symmetric TreeSolveEasy
- Merge Two Binary TreesSolveEasy
- Path SumSolveEasy
- Path Sum IISolveMedium
- Sum Root to Leaf NumbersSolveMedium
- Path Sum IIISolveMedium
- Children sum propertySolveMedium
- Path from the root to a nodeSolveMedium
- Count Complete Tree NodesSolveMedium
- Flatten Binary Tree to Linked ListSolveMedium
- House Robber IIISolveMedium
Breadth first: level by levelThe question mentions levels, a view from one side, or a distance from a node.12
- Level order with a queueRead
- Binary Tree Level Order Traversal147 DSA SheetSolveMedium
- Binary Tree Right Side View147 DSA SheetSolveMedium
- Maximum Width of Binary TreeSolveMedium
- All Nodes Distance K in Binary Tree147 DSA SheetSolveMedium
- Amount of Time for Binary Tree to Be InfectedSolveMedium
- Vertical Order Traversal of a Binary TreeSolveHard
- Binary Tree Zigzag Level Order TraversalSolveMedium
- Binary Tree Level Order Traversal IISolveMedium
- Average of Levels in Binary TreeSolveEasy
- Populating Next Right Pointers in Each NodeSolveMedium
- Top view of a binary treeSolveMedium
- Bottom view of a binary treeSolveMedium
Building and serializingYou must turn traversal orders, or a string, back into a tree.3
14Binary Search Treesafter Binary Trees, Binary Search2 patterns · 1 lesson18
In a BST, everything on the left is smaller and everything on the right is larger. Most problems use this to skip half the tree.
BST basicsYou need to search, find the smallest or largest, or find the nearest value in a BST.5
Using the orderingThe tree is a BST, so an in-order walk visits the values in sorted order.13
- Validate Binary Search Tree147 DSA SheetSolveMedium
- Kth Smallest Element in a BST147 DSA SheetSolveMedium
- Lowest Common Ancestor of a Binary Search Tree147 DSA SheetSolveMedium
- Insert into a Binary Search TreeSolveMedium
- Delete Node in a BST147 DSA SheetSolveMedium
- Construct Binary Search Tree from Preorder TraversalSolveMedium
- Two Sum IV - Input is a BSTSolveEasy
- Recover Binary Search Tree147 DSA SheetSolveMedium
- Largest BST SubtreeSolveMedium
- Trim a Binary Search TreeSolveMedium
- Inorder Successor in BSTSolveMedium
- Binary Search Tree IteratorSolveMedium
- Maximum Sum BST in Binary TreeSolveHard
15Heapsafter Binary Trees5 patterns · 2 lessons22
A heap gives you the smallest or largest item in log time. Use it when you keep needing the current best.
Building a heapYou need to implement a heap yourself, or use one to sort.6
Top KYou need the k largest, smallest or closest items, and a full sort does more work than that.8
- Kth Largest Element in a Stream147 DSA SheetSolveEasy
- Kth Largest Element in an Array147 DSA SheetSolveMedium
- K Closest Points to Origin147 DSA SheetSolveMedium
- K-th smallest element with a heapSolveMedium
- Find K Closest ElementsSolveMedium
- Sort a nearly sorted arraySolveMedium
- Rank Transform of an ArraySolveEasy
- Maximum sum combinationsSolveMedium
Simulating with a heapEach step takes the best item, changes it, and puts it back.6
- Last Stone Weight147 DSA SheetSolveEasy
- Task Scheduler147 DSA SheetSolveMedium
- Design TwitterSolveMedium
- Connect ropes at minimum costSolveEasy
- Reorganize StringSolveMedium
- IPOSolveHard
Two heapsYou need the median of numbers that keep arriving.1
- Find Median from Data Stream147 DSA SheetSolveHard
Merging k sorted listsYou have k sorted sequences and need one sorted output.1
- Merge k Sorted Lists147 DSA SheetSolveHard
16Triesafter Binary Trees2 patterns · 2 lessons9
A trie stores strings by their prefixes, so words that start the same way share a path.
Prefix treesYou search many words by prefix, or match them one letter at a time.7
- Tries: one node per prefixRead
- Implement Trie (Prefix Tree)147 DSA SheetSolveMedium
- Design Add and Search Words Data Structure147 DSA SheetSolveMedium
- Longest Word in DictionarySolveMedium
- Implement Trie II (Prefix Tree)SolveMedium
- Word Search II147 DSA SheetSolveHard
- Number of Distinct Substrings in a StringSolveMedium
- Longest Word With All PrefixesSolveMedium
Tries over bitsYou want the pair of numbers with the largest XOR.2
17Greedyafter Sorting1 pattern · 1 lesson15
A greedy solution takes the best-looking choice at each step and never goes back. The hard part is proving that this is safe.
The best choice nowA choice that looks best now can never hurt you later.15
- When greedy works: the exchange argumentRead
- Jump Game147 DSA SheetSolveMedium
- Jump Game II147 DSA SheetSolveMedium
- Gas Station147 DSA SheetSolveMedium
- Partition Labels147 DSA SheetSolveMedium
- Hand of StraightsSolveMedium
- Merge Triplets to Form Target TripletSolveMedium
- Valid Parenthesis String147 DSA SheetSolveMedium
- Candy147 DSA SheetSolveHard
- Assign CookiesSolveEasy
- Lemonade ChangeSolveEasy
- Fractional knapsackSolveMedium
- Fewest coins with greedySolveEasy
- Shortest job firstSolveMedium
- Job sequencingSolveMedium
- Minimum Number of Arrows to Burst BalloonsSolveMedium
18Intervalsafter Greedy1 pattern · 1 lesson8
Sort the intervals by start or by end first. After that, most interval problems take one pass.
Merging and schedulingThe input is a list of start and end times.8
- Sort by start or by end: which one and whyRead
- Merge Intervals147 DSA SheetSolveMedium
- Insert Interval147 DSA SheetSolveMedium
- Non-overlapping Intervals147 DSA SheetSolveMedium
- Meeting RoomsSolveEasy
- Meeting Rooms IISolveMedium
- Minimum Interval to Include Each Query147 DSA SheetSolveHard
- Most meetings in one roomSolveEasy
- Minimum platformsSolveMedium
19Graphsafter Binary Trees7 patterns · 6 lessons40
A graph is a tree that can have cycles. The same DFS and BFS apply, with a visited set so you do not loop forever.
Graph basicsYou need to store a graph and visit every node.3
Grids as graphsThe input is a grid, and each cell connects to its neighbours.8
- Flood Fill147 DSA SheetSolveEasy
- Number of Islands147 DSA SheetSolveMedium
- Max Area of IslandSolveMedium
- Surrounded Regions147 DSA SheetSolveMedium
- Pacific Atlantic Water Flow147 DSA SheetSolveMedium
- Number of Distinct IslandsSolveMedium
- Number of EnclavesSolveMedium
- Number of Closed IslandsSolveMedium
Fewest steps with BFSEvery move costs the same and you want the fewest moves, often from many starting points at once.6
- Rotting Oranges147 DSA SheetSolveMedium
- 01 Matrix147 DSA SheetSolveMedium
- Walls and GatesSolveMedium
- Shortest Path in Binary MatrixSolveMedium
- Word Ladder147 DSA SheetSolveHard
- Shortest path with unit weightsSolveMedium
Traversing a graphThe input is a list of edges or neighbours, not a grid.5
- Clone Graph147 DSA SheetSolveMedium
- Is Graph Bipartite?SolveMedium
- Number of Connected Components in an Undirected GraphSolveMedium
- Graph Valid TreeSolveMedium
- Number of ProvincesSolveMedium
Cycle detectionYou need to know whether a path leads back to where it started.2
Topological sortSome tasks must come before others, and you need a valid order or proof that none exists.7
- Topological sort: DFS order and Kahn's algorithmRead
- Course Schedule147 DSA SheetSolveMedium
- Course Schedule II147 DSA SheetSolveMedium
- Alien DictionarySolveHard
- Topological sort (Kahn's algorithm)SolveMedium
- Find Eventual Safe StatesSolveMedium
- Course Schedule IVSolveMedium
- Minimum Height TreesSolveMedium
Union-findEdges arrive one at a time, and you keep asking whether two nodes are already connected.9
- Disjoint sets: union by rank and path compressionRead
- Redundant Connection147 DSA SheetSolveMedium
- Number of Operations to Make Network ConnectedSolveMedium
- Making A Large IslandSolveHard
- Number of Islands IISolveHard
- Disjoint set unionSolveMedium
- Accounts MergeSolveMedium
- Most Stones Removed with Same Row or ColumnSolveMedium
- Satisfiability of Equality EquationsSolveMedium
- Redundant Connection IISolveHard
20Advanced Graphsafter Graphs, Heaps, Greedy4 patterns · 7 lessons22
When edges have weights, plain BFS no longer finds the shortest path. These algorithms handle weights.
Weighted shortest pathsEdges have different costs and you want the cheapest route.14
- Dijkstra's algorithm and why it fails on negative edgesRead
- Bellman-Ford: relaxing every edge V−1 timesRead
- Floyd-Warshall: all pairs in O(V³)Read
- Network Delay Time147 DSA SheetSolveMedium
- Path With Minimum Effort147 DSA SheetSolveMedium
- Cheapest Flights Within K Stops147 DSA SheetSolveMedium
- Swim in Rising Water147 DSA SheetSolveHard
- Find the City With the Smallest Number of Neighbors at a Threshold DistanceSolveMedium
- Word Ladder IISolveHard
- Shortest path in a DAGSolveMedium
- Dijkstra's algorithmSolveMedium
- Print the shortest pathSolveMedium
- Number of Ways to Arrive at DestinationSolveMedium
- Path with Maximum ProbabilitySolveMedium
- Minimum multiplications to reach the endSolveHard
- Bellman-Ford algorithmSolveMedium
- Floyd-Warshall algorithmSolveHard
0-1 BFSEvery edge costs 0 or 1, so a full heap does more work than you need.2
Minimum spanning treesYou must connect every node at the lowest total cost.2
Special edges and pathsYou must use every edge once, or find the edges whose removal splits the graph.4
211-D Dynamic Programmingafter Recursion and Backtracking4 patterns · 3 lessons24
Dynamic programming is recursion that remembers answers it has already worked out. In 1-D problems, each answer depends on a few earlier ones.
Take it or skip itAt each position you either use it or skip it, and the best answer builds on the ones before.11
- From recursion to memo to tableRead
- Keeping only the last few statesRead
- Climbing Stairs147 DSA SheetSolveEasy
- Min Cost Climbing StairsSolveEasy
- House Robber147 DSA SheetSolveMedium
- House Robber II147 DSA SheetSolveMedium
- Decode Ways147 DSA SheetSolveMedium
- Word Break147 DSA SheetSolveMedium
- N-th Tribonacci NumberSolveEasy
- Frog jump with K stepsSolveEasy
- Perfect SquaresSolveMedium
- Minimum Cost For TicketsSolveMedium
- Training schedule with no repeated activitySolveMedium
PalindromesThe question asks about palindromic substrings.2
- Longest Palindromic Substring147 DSA SheetSolveMedium
- Palindromic Substrings147 DSA SheetSolveMedium
Increasing subsequencesThe answer is a subsequence that must keep going up.6
Buying and selling with statesYou either hold a stock or you do not, and the rules limit how you switch.5
222-D Dynamic Programmingafter 1-D Dynamic Programming6 patterns · 6 lessons48
Here each answer depends on two indexes, such as a row and a column, or a position in each of two strings.
Paths in a gridYou move through a grid and count the paths or find the best one.8
- DP on grids: the state is the cellRead
- Unique Paths147 DSA SheetSolveMedium
- Unique Paths IISolveMedium
- Longest Increasing Path in a Matrix147 DSA SheetSolveHard
- Minimum Path SumSolveMedium
- TriangleSolveMedium
- Minimum Falling Path SumSolveMedium
- Count Square Submatrices with All OnesSolveMedium
- Cherry Pickup IISolveHard
KnapsackYou pick items to reach a target sum or fill a capacity.12
- 0/1 and unbounded knapsackRead
- 0/1 knapsackSolveMedium
- Partition Equal Subset Sum147 DSA SheetSolveMedium
- Coin Change147 DSA SheetSolveMedium
- Coin Change II147 DSA SheetSolveMedium
- Target Sum147 DSA SheetSolveMedium
- Last Stone Weight IISolveMedium
- Subset sumSolveMedium
- Count subsets with sum KSolveMedium
- Count partitions with a given differenceSolveMedium
- Unbounded knapsackSolveMedium
- Rod cuttingSolveHard
- Partition Array Into Two Arrays to Minimize Sum DifferenceSolveHard
Two stringsYou compare two strings one character at a time.14
- DP on two strings: i, j and what matchesRead
- Longest Common Subsequence147 DSA SheetSolveMedium
- Maximum Length of Repeated SubarraySolveMedium
- Edit Distance147 DSA SheetSolveMedium
- Longest Palindromic SubsequenceSolveMedium
- Distinct SubsequencesSolveHard
- Interleaving StringSolveMedium
- Wildcard MatchingSolveHard
- Regular Expression MatchingSolveHard
- Print a longest common subsequenceSolveMedium
- Delete Operation for Two StringsSolveMedium
- Minimum Insertion Steps to Make a String PalindromeSolveHard
- Shortest Common Supersequence SolveHard
- Count palindromic subsequencesSolveHard
- Minimum ASCII Delete Sum for Two StringsSolveMedium
Splitting a rangeYou choose where to split a range, and each side becomes a smaller problem.6
Bitmask DPThere are at most about 20 items, and the answer depends on which ones are already used.4
Digit DPYou must count the numbers up to a huge N whose digits follow a rule.4
23String Matchingafter Strings1 pattern · 3 lessons6
These algorithms find a pattern inside a text faster than checking every starting position.
Pattern matchingYou must find a pattern inside a longer string, and checking every start is too slow.6
24Range Queriesoptionalafter Binary Trees5 patterns · 6 lessons10
Optional. These structures answer many questions about parts of an array, such as a sum or a minimum, even while the array changes. They come up mostly in hard rounds.