The Library
All 188 problems on one shelf, ten free to begin, or follow Blind 75 and NeetCode 150. Search also finds the lessons and skills; the roadmap waits on the map table.
The problem shelf
DifficultyKind
188 problems
- Contains DuplicateDecide whether any value appears twice by remembering every value you have already seen.
- Two SumFind two distinct indices whose values add to a target.
- Valid AnagramCheck whether two strings use exactly the same letters the same number of times.
- Group AnagramsPut words that are anagrams of each other into the same group.
- Merge IntervalsSort intervals by start, then extend the last merged interval or start a new one.
- Best Non-Adjacent Sum for Every PrefixFill the house-robber DP table: the best non-adjacent total from the first i values.
- Best Sum Ending at Each IndexRecord Kadane's running value: the best sum of a run that ends exactly at each index.
- Build Prefix SumsBuild the prefix sum list with a leading 0, so any range sum becomes one subtraction.
- Cancel Adjacent Equal PairsRemove equal neighbors, including pairs created by earlier removals, with one stack pass.
- Clone Records with Random LinksDeep-copy records that link to each other: make every copy first, then wire the links.
- Count VowelsCount how many vowels a string contains, ignoring case.
- Count Word FrequenciesTurn a list of words into a dictionary from each word to how many times it appears.
- Design HashMapBuild a key-value map from an array of buckets, without a built-in dict.
- Design HashSetBuild a set of integers from an array of buckets, without a built-in set or dict.
- Discard Pairs with Two PointersCount pairs in a sorted list whose sum is below a limit, counting a whole block of partners at once.
- Distance to the Nearest SourceFill a grid with each cell's distance to the nearest source, going around blocked cells.
- Extend a Path by One ChoicePractise choose, record a copy, and un-choose on one level of a backtracking search.
- Find a Key in Hash BucketsLook up a key in a hand-built hash table: hash to one bucket, then compare exact keys.
- Find the First True BoundaryBinary search for the first True: if mid is True, save it and keep looking to the left.
- Find the Middle NodeFind the middle node of an index-based linked list in one pass with slow and fast pointers.
- Follow Trie EdgesBuild a trie and measure how far each query follows it from the root.
- Implement Stack Using QueuesBuild a last-in, first-out stack out of a first-in, first-out queue.
- Keep the K Largest ValuesKeep the k largest values with a min-heap of size k and return them in ascending order.
- Mark Seen IndicesRecord which labels from 1 to n appear by sending label v to index v - 1.
- Merge Two Ordered RunsMerge two sorted lists into one sorted list in a single pass.
- Normalize TextLowercase a string and squeeze all of its whitespace down to single spaces.
- Partition Traversal RangesList the index ranges you split when rebuilding a binary tree from its preorder and inorder traversals.
- Practice Deque OperationsRun a list of add and remove commands on both ends of a collections.deque and report what each remove returns.
- Previous Smaller ElementFor each value, find the nearest earlier value that is strictly smaller.
- Rank Top WordsSort words by count, high to low, break ties alphabetically, and keep the first few.
- Reverse One Slice SegmentReverse only text[start:end] by cutting the string into three slices and joining them back.
- Reverse Text with SlicingReverse a string with one slice and learn why start and stop can be left out.
- Root-to-Leaf Path SumsList the sum of every root-to-leaf path by carrying a running total down a DFS.
- Shrink Until the Window Is ValidGrow the window on the right, shrink it from the left while the sum is too big, and keep the longest one.
- Simulate a Circular BufferRun a fixed-size queue in a list with a head index, a count and wraparound.
- Slide a Fixed WindowSlide a window of fixed width: add the value coming in, drop the value going out, record the sum.
- Smallest Square That FitsBinary-search the smallest square side that can hold a given number of items.
- Sum Each Tree LevelAdd up the values on each level of a tree, from the top level down.
- Tokenize WordsSplit text into a list of lowercase words on any whitespace.
- Topological Sort in LayersGroup the nodes of a directed graph into layers that respect every edge, or detect a cycle.
- Track Previously Seen ValuesReport for each value whether it appeared earlier, using a set: look back first, then store.
- Unlink One Node from a Linked ListSkip one node of an index-based linked list by pointing the node before it at the node after it.
- Visit Each Grid ComponentMeasure every connected region of 1s in a grid, in scan order.
- Add Two NumbersAdd two numbers stored as reversed digit lists, carrying just like column addition.
- Answer Connected Queries with Union-FindMerge groups with union and answer connected queries with Union-Find.
- Answer Matrix Region SumsBuild a 2D prefix-sum table once, then answer each rectangle sum from four corners.
- Apply Range AdditionsMark each range update at its two ends, then recover every value with one running sum.
- Binary Search a Globally Sorted MatrixSearch a matrix whose rows, read one after another, form a single sorted list.
- Binary Subarrays With SumCount subarrays of 0s and 1s that add up to goal, using prefix sums and a dictionary of counts.
- Binary Tree Level OrderReturn the values of a binary tree level by level, from left to right.
- Binary Tree Right Side ViewReturn the value you would see at each level when looking at the tree from the right.
- Bottom-Up Level Order TraversalList a tree's levels from the deepest one up to the root.
- Build a KMP Prefix TableBuild the KMP longest-prefix-suffix (LPS) table in one pass, falling back to lps[j - 1] after a mismatch instead of starting over.
- Build a Unique AssignmentGive every position a different allowed value, undoing choices that lead to a dead end.
- Build and Query a Binary Search TreeInsert values into a binary search tree, read them back with an in-order traversal, and answer search queries by walking down one path.
- Build Graph RepresentationsTurn an undirected edge list into a sorted adjacency list and an adjacency matrix.
- Build Tree from Inorder and PostorderRebuild a binary tree from its inorder and postorder traversals.
- Build Tree from Preorder and InorderRebuild a binary tree from its preorder and inorder traversals.
- Car FleetCount how many groups of cars reach the target, scanning from the car closest to it.
- Choose Non-Adjacent Tree ValuesReturn two answers from every subtree, with the node taken and with it skipped, and combine them at the parent.
- Coalesce Busy BlocksMerge overlapping busy blocks with the sort-and-merge template, keeping touching half-open blocks apart.
- Compact Sorted ValuesKeep one copy of each value in a sorted list with a read pointer and a write pointer.
- Compute All-Pairs Shortest PathsFind the cheapest path between every pair of nodes by allowing one more middle stop per round (Floyd-Warshall).
- Compute GCD with EuclidFind the greatest common divisor with Euclid's algorithm: replace (a, b) by (b, a % b) until b is 0.
- Compute Modular PowerCompute base^exponent % modulus in O(log exponent) steps with fast exponentiation by squaring.
- Compute Nonnegative Shortest PathsFind the cheapest distance from a source to every node of a weighted directed graph with the Dijkstra template.
- Copy a Random-Pointer ListDeep-copy a list whose nodes also point at a random node, using a list of [value, random] records.
- Count Components with Union-FindCount the connected components of an undirected graph with the union-find template.
- Count Good Nodes in a Binary TreeCount the nodes that are at least as large as every node above them.
- Count Set BitsCount the 1 bits of a nonnegative integer by clearing the lowest set bit until nothing is left.
- Count Subsequences by Minimum and MaximumCount the subsequences whose smallest plus largest value is at most target.
- Course ScheduleDecide whether every course can be taken by repeatedly taking courses with no unfinished prerequisites.
- Cutting RibbonsFind the longest length you can cut at least k equal pieces of from a set of ribbons.
- Daily TemperaturesFor each day, count the days until a warmer one with a monotonic stack of indices.
- Design a Task QueueKeep tasks in arrival order with a deque, and return a sorted priority view without changing that order.
- Design Circular QueueBuild a fixed-size first-in, first-out queue on a plain list whose free slots are reused by wrapping around.
- Detect a Directed CycleFind a cycle in a directed graph with DFS and three node states: unvisited, on the current path, and finished.
- Diagonal Traverse IIRead a jagged grid diagonal by diagonal, going from the bottom row up inside each diagonal.
- Encode and Decode StringsTurn a list of strings into one string and back, even when the strings contain any character.
- Evaluate Reverse Polish NotationEvaluate an arithmetic expression written in postfix order with a stack.
- Find a Linked-List Cycle EntranceFind where a linked list's cycle begins with fast and slow pointers in O(1) extra space.
- Find a Peak ElementReturn the index of any value that is bigger than both of its neighbors.
- Find All Duplicates in an ArrayFind every value that appears twice, using the array itself as the seen-set.
- Find Every String MatchSlide the pattern along the text, compare it character by character at each start, and record every start where it fully matches, overlaps included.
- Find K Closest ElementsBinary search for where the best block of k neighbours of x starts in a sorted array.
- Find Peak Active SessionsTurn sessions into start and end events, sort them, and track the largest running count.
- Find the Duplicate NumberFind the one repeated value without changing the array or using extra memory.
- Find the First Matching IndexScan a list once and return the index of the first value equal to the target.
- Find the Missing Number with Cyclic SortSend every number to the index that matches its value, then find the empty seat.
- First and Last Target PositionFind where a target's run of copies starts and ends in a sorted array.
- Friends of Appropriate AgesCount one-way friend requests by counting people per age and checking the rules once for every pair of ages.
- Generate Balanced ParenthesesList every balanced string made of n pairs of parentheses.
- Generate Primes with a SieveList every prime up to a limit with the Sieve of Eratosthenes: cross out the multiples of each prime, starting at its square.
- Group Integers into Ordered BucketsSplit integers into equal-width buckets, sort each bucket, and join the buckets in order.
- Grow a Spanning Tree with PrimGrow a minimum spanning tree from node 0 with Prim's algorithm: a min-heap of edges leaving the tree.
- Heap SortSort a list with heap sort: build a max-heap with sift_down, then move the largest value to the end again and again.
- House RobberPick houses to rob so that no two are next to each other and the total is as large as possible.
- House Robber IIRob houses arranged in a circle by solving the straight-street problem twice: once without the first house and once without the last.
- Implement TrieStore words in a prefix tree so you can check whole words and prefixes in time proportional to their length.
- Insert GCD Nodes in a Linked ListInsert a node holding the greatest common divisor between every pair of neighbors.
- Insert Into a Sorted Circular ListInsert a value into a sorted circular list, including at the wrap from largest to smallest.
- K-Radius Subarray AveragesFor each index, average the k values on each side of it, or return -1 when there are not enough.
- Keep the K Smallest Stream ValuesKeep only k candidates in a heap while reading the values, then return the k smallest in order.
- Koko Eating BananasBinary search the eating speed: find the slowest speed that still finishes every pile in time.
- Kruskal's Minimum Spanning TreeConnect every node with the lightest set of edges by taking edges from lightest to heaviest and skipping any edge that would close a cycle.
- Kth Largest Element in an ArrayFind the kth largest value by keeping only the k largest values in a min-heap.
- Kth Smallest in a BSTFind the k-th smallest value in a binary search tree.
- Kth Smallest in a Sorted MatrixMerge the sorted rows with a heap and stop at the kth value.
- Longest Consecutive SequenceFind the length of the longest run of consecutive integers in an unsorted list.
- Longest Continuous Subarray Within LimitFind the longest subarray whose largest and smallest values differ by at most limit.
- Longest Ones After Deleting One ElementDelete exactly one element from a binary array and find the longest run of 1s that is left.
- Longest Repeating Character ReplacementFind the longest substring that can become one repeated letter after at most k replacements.
- Longest Substring Without Repeating CharactersFind the length of the longest contiguous part of a string with no repeated character.
- Lowest Common Ancestor in a BSTFind the lowest common ancestor of two values in a binary search tree.
- LRU CacheBuild a fixed-size cache that throws out the least recently used key, with O(1) get and put.
- Maintain Sliding-Window MaximumsFind the maximum of every window as it slides, using a deque of indexes whose values decrease.
- Map Sum PairsKeep a running total in each trie node so the sum of all keys with a given prefix is one walk away.
- Max Area of IslandMeasure every island in the grid and return the largest area.
- Max Consecutive Ones IIIFind the longest window of 0s and 1s that holds at most k zeros.
- Maximum Container AreaPick two walls that hold the most water between them.
- Maximum Contiguous Subarray SumFind the largest sum of any contiguous, nonempty part of an array.
- Maximum Sum of a Distinct Length-K SubarrayFind the largest sum of k consecutive values that are all different.
- Maximum Unique String SplitCut a string into as many pieces as possible while keeping every piece different.
- Measure a Minimum Spanning TreeFind the weight of a minimum spanning tree with Kruskal's algorithm: sorted edges plus union-find.
- Memoize Grid PathsCount down-and-right paths through a grid with blocked cells, caching each cell's answer.
- Merge Sorted RowsMerge several sorted rows into one sorted list with a heap that holds one value per row.
- Min StackDesign a stack that can also return its smallest value in constant time.
- Minimize Adjacent Merge CostFill a table of the cheapest merge cost for every range, from short ranges to long ones.
- Minimum of a Rotated Sorted ArrayFind the smallest value of a sorted array that has been rotated.
- Navigate a Grid with A*Find the fewest moves across a grid with A*: a min-heap ordered by f = g + h, with Manhattan distance as h.
- Normalize Closed IntervalsSort closed intervals and merge every pair that overlaps or touches.
- Number of IslandsCount the islands of land cells joined up, down, left or right.
- Odd Even Linked ListMove the nodes at odd positions in front of the nodes at even positions, keeping each group in order.
- Palindrome PartitioningCut a string in every way that leaves only palindromes.
- Partition and Quick SortSort a list with quick sort, using the Lomuto partition around the last value.
- Path Sum IIList every root-to-leaf path whose values add up to a target.
- Peak Index in a Mountain ArrayBinary search for the first downhill step of a mountain array.
- Permutation in StringCheck whether some window of s2 holds exactly the same letters, in the same amounts, as s1.
- Permutations of Distinct ValuesGenerate every ordering of a list of distinct integers.
- Phone Keypad Letter CombinationsList every letter string a sequence of phone keypad digits can spell.
- Power Set of Distinct ValuesReturn every subset of a list of distinct integers.
- Product Except SelfFor each position, multiply every other number in the array, without division.
- Profile a Binary TreeWalk a binary tree stored in a list level by level and report its node count, height and number of leaves.
- Recognize Three-Node Tree RotationsSee what every AVL rotation case does to three inserted values: single or double, the median always ends up as the root.
- Relax Signed Edges with Bellman-FordFind cheapest paths when weights can be negative by relaxing every edge in rounds, and detect a reachable negative cycle.
- Remove Nth Node From EndRemove the nth node from the end of a linked list in one pass with two pointers and a dummy head.
- Reorder ListRearrange a list as first, last, second, second-to-last, and so on, in place.
- Resolve a Weighted Random PickTurn a random draw into an index, where each index is picked in proportion to its weight.
- Restore Valid IPv4 AddressesPlace three dots in a digit string to form every valid IPv4 address.
- Reusable-Candidate Combination SumFind every combination of candidates that adds up to target, using each candidate as often as you like.
- Roll a Window HashCompute the polynomial hash of every fixed-size window, sliding from one window to the next in O(1) the way Rabin-Karp does.
- Rotting OrangesFind how many minutes it takes for rot to reach every fresh orange.
- Search a Rotated Array With DuplicatesSearch a rotated sorted array that may contain repeated values.
- Search a Rotated Sorted ArrayFind a target in a sorted array that was rotated, still in O(log n) time.
- Search a Row-and-Column Sorted MatrixSearch a matrix whose rows and columns are each sorted, by walking from the top-right corner.
- Seat Reservation ManagerAlways hand out the smallest free seat, using a counter and a min-heap.
- Select the Kth Smallest ValuePartition around a pivot and keep only the side that holds the kth smallest value.
- Select the Most Non-Overlapping IntervalsChoose as many non-overlapping intervals as possible by always keeping the one that ends first.
- Ship Packages Within D DaysBinary search the ship's capacity: find the smallest one that ships every package, in order, within the given days.
- Shortest Subarray to Remove for Sorted OrderRemove the shortest contiguous piece so that what is left is sorted.
- Shortest Subarray With OR at Least KFind the shortest subarray whose bitwise OR is at least k.
- Simulate Fisher-Yates ShufflingShuffle a copy of a list with Fisher-Yates: walk from the back and swap each position with a random earlier one, using given choices so the result can be checked.
- Simulate Reservoir SamplingKeep a uniform sample of k items from a stream with Algorithm R, using given random numbers so the result can be checked.
- Single-Use Combination SumList every unique combination that hits the target when each position can be used once and values may repeat.
- Sort a Bounded Integer RangeSort integers from a small range by counting how often each value appears.
- Sort an ArrayWrite merge sort: sort each half, then merge the two sorted halves.
- Sort Characters by FrequencyRebuild a string so the most frequent characters come first, with each character's copies kept together.
- Sort Nonnegative Integers by DigitsSort nonnegative integers one decimal digit at a time, from the ones digit up, with ten stable buckets per pass.
- Sorted List to Balanced BSTTurn a sorted linked list into a height-balanced binary search tree.
- Split Linked List in PartsCut a linked list into k consecutive parts whose sizes differ by at most one.
- Surrounded RegionsFlip every region of 'O' cells that cannot reach the edge of the board.
- Tabulate Minimum Coin CountFill a table of the fewest coins for every amount from 0 up to the target.
- Target SumCount how many ways to put + or - in front of every number so the total equals the target.
- Time-Based Key-Value StoreStore several timestamped values per key and return the latest one at or before a given time.
- Top K Frequent ElementsCount each value, group values by how often they appear, and read the groups from most to least frequent.
- Track Stock State with a FeeTrack two states each day, holding a share or not, and charge the fee when you sell.
- Unique Subsets With Duplicate InputsReturn every subset exactly once when the input contains repeated values.
- Unique Zero-Sum TripletsFind every distinct triplet of numbers that adds up to zero.
- Validate a Binary Search TreeCheck that every node fits strictly inside the range its ancestors allow.
- Validate a Bipartite GraphCheck whether an undirected graph can be painted with two colors by BFS coloring every part of it.
- Validate a Partial SudokuCheck that no digit repeats in any row, column, or 3-by-3 box of a partly filled Sudoku board.
- Walls and GatesFill every empty room with its distance to the nearest gate.
- Wildcard Word DictionaryStore words in a trie and search them with patterns where a dot stands for any one letter.
- Word Search in a Character GridDecide whether a word can be traced through neighbouring grid cells without reusing a cell.
- Zigzag Level Order TraversalRead a tree level by level, switching direction on every level.
- Maintain Segment-Tree Range SumsAnswer inclusive range sums while single values change, using a segment tree stored in one array.
- Prefix and Range Sums with a Fenwick TreeKeep prefix and range sums up to date while numbers change, using a Fenwick tree.
- Word Search IIFind every dictionary word on a letter board by walking the board and a trie together.
Keep the craft
