Coding interview problems, explained by pattern
Coding interview problems are short algorithm tasks you solve and explain in roughly 30 to 45 minutes, and most of them are a familiar pattern wearing a new costume. This section walks through common problems one at a time: the idea in plain words, a brute force, the optimal approach with the pattern named, tested code in Python plus JavaScript or C++, and the follow-ups interviewers tend to ask.
By Evin JohnPublished 48 min read
What this section is for
Technical screens at many software companies still include at least one live coding round. The interviewer shares a small problem, watches you reason about it, and asks you to write code that runs. The problems themselves are rarely secret. A short list of classics appears again and again because each one isolates a single idea: can you trade memory for speed with a hash map, can you see that a stack matches nested structure, can you keep a window over a string without rescanning it.
These pages treat each classic as a lesson in one pattern. The goal is not to memorize eight answers. It is to recognize the same shape when it shows up with different nouns, such as transactions instead of numbers or meeting rooms instead of intervals. Many of these problems are commonly practiced on LeetCode and similar judge sites; the statements and examples here are written fresh, so read the problem the way you would hear it from a person.
How to practice: pattern first, problem second
- Name the pattern before you write codeRead the prompt and ask which signal it gives. Pairs that must add up point to hashing. Nested brackets point to a stack. Contiguous runs point to a sliding window. Connected cells point to graph search.
- Say the brute force and its costDescribe the slow answer in one sentence and give its time and space. It proves you understand the task, and the repeated work inside it is usually where the faster idea comes from.
- Remove the repeated workAsk what the brute force recomputes. A lookup table, a sort, a pointer that never moves backward or a queue usually removes it. Name the new complexity before you start typing.
- Write it, then trace it by handCode the optimal version in your main language, then walk a tiny input through it line by line. Check the empty input, a single element and a case with duplicates.
- Rehearse the follow-upsEach walkthrough lists the questions interviewers add once the first version works: a sorted input, a stream, limited memory, many queries. Answering them is often what separates a pass from a strong pass.
- Space the repetitionsReturn to a problem a few days later and solve it cold. If you can rebuild it from the pattern name alone, it has stuck. If you only remember the code, it has not.
The problems, grouped by pattern
| Pattern | Clue in the prompt | Walkthrough |
|---|---|---|
| Hash map lookup | Find two items that relate to each other, fast | Two Sum |
| Counting plus bucket or heap | The most common or the k largest of something | Top K Frequent Elements |
| Stack | Things that open and must close in reverse order | Valid Parentheses |
| Sort, then sweep | Ranges, bookings or time spans that may overlap | Merge Intervals |
| Sliding window | The longest or shortest contiguous run with a rule | Longest Substring Without Repeating Characters |
| Design with two structures | Constant-time get and put with an eviction rule | LRU Cache |
| Graph search on a grid | Count or measure connected regions | Number of Islands |
| Breadth-first search on a tree | Anything reported row by row or by distance | Binary Tree Level Order Traversal |
| Erase the lowest set bit | Count the 1s in a binary value | Number of 1 Bits |
| Reuse a smaller answer by shifting | A bit count for every number up to n | Counting Bits |
| Shift and mask at a fixed width | Mirror a value's 32-bit pattern | Reverse Bits |
| Compare with the complete set (sum or XOR) | One value absent from a known range | Missing Number |
| XOR plus shifted carry | Arithmetic without the arithmetic operators | Sum of Two Integers |
| Overflow check before each step | Rebuild a number digit by digit inside 32 bits | Reverse Integer |
| Length-prefix framing | Pack many strings into one and split them back safely | Encode and Decode Strings |
| Sets keyed by row, column and box | Spot repeats across overlapping groups of a grid | Valid Sudoku |
| Hash set membership | Has this value, or this node, been seen before? | Contains Duplicate |
| Sort, then two pointers | Several values that must add up to a target, without repeats | 3Sum |
| Two pointers from both ends | Choose a left and a right boundary to maximize a score | Container With Most Water |
| Running minimum | The best later value to pair with an earlier one | Best Time to Buy and Sell Stock |
| Kadane's algorithm | The best contiguous run by sum | Maximum Subarray |
| Prefix and suffix products | Everything except the current position, without division | Product of Array Except Self |
| One-dimensional dynamic programming | Count the ways to reach a step from smaller steps | Climbing Stairs |
| Linked list pointer rewiring | Turn a chain of nodes around in place | Reverse Linked List |
| Dummy head and merge | Combine already sorted sequences into one | Merge Two Sorted Lists |
| Fast and slow pointers | A chain that might loop back on itself | Linked List Cycle |
| Sliding window with a letter count | The longest stretch you can make uniform with a few edits | Longest Repeating Character Replacement |
| Fixed-size counting window | Does any block of the text use exactly these letters? | Permutation in String |
| Stack with a running extra value | Undo-style storage that must also report its minimum instantly | Min Stack |
| Stack as an evaluator | Operators that act on the last two values produced | Evaluate Reverse Polish Notation |
| Backtracking with counters | List every string or arrangement that obeys a rule | Generate Parentheses |
| Monotonic stack | For each item, the next one that is larger | Daily Temperatures |
| Sort, then sweep arrival times | Objects that cannot pass each other and merge into groups | Car Fleet |
| Monotonic stack with widths | The biggest area under a skyline of bars | Largest Rectangle in Histogram |
| Post-order with a side result | The longest path anywhere in a tree | Diameter of Binary Tree |
| Post-order with a sentinel | A rule that must hold at every node of a tree | Balanced Binary Tree |
| Two trees in lockstep | Are these two structures identical? | Same Tree |
| Search plus comparison, or serialization | Does one tree appear whole inside another? | Subtree of Another Tree |
| Recursion that reports what it found | The deepest node shared by two others | Lowest Common Ancestor |
| Breadth-first search, last of each level | What can be seen from one side of a tree | Binary Tree Right Side View |
| Depth-first search carrying a value down | Compare each node with everything above it | Count Good Nodes in Binary Tree |
| Depth-first search with bounds | Ordering rules that reach past a node's own children | Validate Binary Search Tree |
| Dynamic programming on two prefixes | Can two sequences be merged, in order, into a third? | Interleaving String |
| Greedy farthest reach | Can you get from the first square to the last? | Jump Game |
| Breadth-first search in bands | The fewest moves when each square limits how far you go | Jump Game II |
| Greedy with a reset | Where to start on a loop so a running total never goes negative | Gas Station |
| Greedy boundary extension | Cut a sequence into the most pieces under a sharing rule | Partition Labels |
| Linear sweep over sorted ranges | Add one booking to a calendar that is already clean | Insert Interval |
| Greedy by earliest end | Drop the fewest bookings so nothing clashes | Non-overlapping Intervals |
| Sort, then check neighbors | Is there any clash at all in a schedule? | Meeting Rooms |
| Bit operations and masks | Pairs that cancel, powers of two, subsets of a small set | Bit manipulation tricks |
| Binary search on a condition | Any local high point, in logarithmic time | Find Peak Element |
| Depth-first search with an explicit stack | Visit a tree left, node, right without recursion | Binary Tree Inorder Traversal |
| Two subtrees in mirrored lockstep | Does the tree read the same flipped left to right? | Symmetric Tree |
| Depth-first search carrying a remainder | Does some root-to-leaf path hit a target? | Path Sum |
| Backtracking on a tree | List every root-to-leaf path that hits a target | Path Sum II |
| Breadth-first search with alternating rows | Read a tree level by level, snaking back and forth | Binary Tree Zigzag Level Order Traversal |
| Pointer rewiring in preorder | Turn a tree into a chain without extra memory | Flatten Binary Tree to Linked List |
| Counting table | Two inputs that must hold the same items in any order | Valid Anagram |
| Canonical key in a hash map | Sort many items into buckets of equivalents | Group Anagrams |
| Hash set with run starts | The longest unbroken run of values, input unsorted | Longest Consecutive Sequence |
| Two pointers from both ends | Compare or combine the outside items, then move inward | Valid Palindrome |
| Converging pointers on sorted data | A pair with a target sum, input already in order | Two Sum on a sorted array |
| Running maximum from each side | How much fills the gaps between taller items | Trapping Rain Water |
| Monotonic deque | The largest value in every fixed-size window | Sliding Window Maximum |
| Variable window with a count table | The shortest stretch that covers a required set | Minimum Window Substring |
| Binary search | Find a value or a boundary in sorted data | Binary Search |
| Binary search on a reshaped input | A grid whose rows continue one another in order | Search a 2D Matrix |
| Binary search on the answer | The smallest value that makes a yes/no check pass | Koko Eating Bananas |
| Binary search with a twist | Sorted data that was cut and swapped | Find Minimum in Rotated Sorted Array |
| Binary search with a sorted-half check | Look up a value in rotated sorted data | Search in Rotated Sorted Array |
| Hash map of sorted histories | Values that change over time, read at a past moment | Time Based Key-Value Store |
| Binary search on a partition | A middle value across two sorted inputs | Median of Two Sorted Arrays |
| Fast and slow pointers, reversal | Rearrange a linked list from both ends | Reorder List |
| Sliding window (pattern guide) | Any contiguous run with a rule that only gets harder as it grows | Sliding window pattern |
| Grid DP, counting | Count routes that only move right or down | Unique Paths II |
| DP folded from the bottom row | Cheapest route down a triangle of numbers | Triangle |
| Grid DP, min of three neighbors | The largest solid square in a 0/1 grid | Maximal Square |
| Stack of indexes with a barrier | The longest balanced run of brackets | Longest Valid Parentheses |
| Two-index DP on text and pattern | Full match with a star that repeats one character | Regular Expression Matching |
| Prefix DP or last-star greedy | Full match with a star that matches any run | Wildcard Matching |
| Interval DP on the last choice | Order of removals where neighbors change the score | Burst Balloons |
| Variable window on positive values | The shortest stretch whose total reaches a target | Minimum Size Subarray Sum |
| Total minus a running prefix | A position where both sides add up the same | Find Pivot Index |
| Voting with two candidates | Every value that appears more than a third of the time | Majority Element II |
| Counting buckets capped at n | The largest h with at least h items scoring h or more | H-Index |
| One pass from each side | Neighbors with higher scores must receive more | Candy |
| Two maps for a one-to-one match | Letters of a pattern standing for words of a sentence | Word Pattern |
| First-seen or last-seen positions | A consistent character substitution between two strings | Isomorphic Strings |
| Count a supply, then spend it | Build one string from the letters of another | Ransom Note |
Pattern guides
- Two pointers pattern: opposite ends, read and write indexes, and fast and slow pointers, with templates.
- Binary search pattern: exact match, first position that passes a test, and searching over possible answers.
- Backtracking pattern: choose, explore, undo, and how pruning keeps the search small.
- Dynamic programming patterns: the five problem families and a recipe for defining state and transitions.
- Graph traversal patterns: BFS, DFS, multi-source BFS and topological order on one adjacency list.
- Heap and priority queue pattern: top k, merging sorted streams and the two-heap running median.
- Monotonic stack pattern: next greater or smaller element and the histogram rectangle in one pass.
Hashing and counting
- Two Sum solution explained: the first problem many people ever practice, and the cleanest demonstration of spending memory to drop a nested loop.
- Top K Frequent Elements solution explained: tally with a dictionary, then pick winners with a heap or with buckets indexed by count.
- Contains Duplicate solution explained: a set of seen values with an early exit, compared with sorting when memory is tight.
- Valid Anagram solution explained: add counts for one string, subtract for the other, and every balance must end at zero.
- Group Anagrams solution explained: turn each word into a signature its anagrams share and bucket by that key.
- Longest Consecutive Sequence solution explained: a set of values, counted upward only from numbers with no predecessor.
- Majority Element II solution explained: at most two values can pass n/3, so two candidates and a recount replace the whole table.
- H-Index solution explained: sort and scan, or bucket the counts with everything above n in the top bucket.
- Word Pattern solution explained: letter to word and word to letter, both checked on every step.
- Isomorphic Strings solution explained: two strings match when each character's first-seen position lines up.
- Ransom Note solution explained: the magazine is a supply of letters and the note spends it.
Stacks and ordering
- Valid Parentheses solution explained: a stack of open brackets that must be closed last-in, first-out.
- Merge Intervals solution explained: sort by start time and the overlaps can only touch their neighbor.
- Longest Valid Parentheses solution explained: a stack of indexes or two counter passes, and why a window fails.
Windows over sequences
- Longest Substring Without Repeating Characters solution explained: two indexes that only move forward, plus a record of where each character was last seen.
- Sliding Window Maximum solution explained: a deque of indexes whose values only decrease, so the front is always the current maximum.
- Minimum Window Substring solution explained: grow the window until it covers every required character, then shrink it from the left.
- The sliding window pattern: the three window shapes, the at-most-k counting trick and when a window does not apply, with templates.
- Minimum Size Subarray Sum solution explained: grow until the total reaches the target, then shrink from the left while it still does.
Designing a data structure
- LRU Cache solution explained: a dictionary for lookups and a doubly linked list for recency, so both reads and writes stay O(1).
Graph and tree traversal
- Number of Islands solution explained: flood fill each unvisited land cell and count how many fills you start.
- Binary Tree Level Order Traversal solution explained: a queue processed one level at a time, the template for most row-by-row tree questions.
- Binary Tree Preorder Traversal solution explained: root before children, with recursion, an explicit stack and Morris threading.
- Binary Tree Postorder Traversal solution explained: children before root, and the one-stack version that knows when a right subtree is done.
- Construct Binary Tree from Inorder and Postorder: the last postorder value is the root; an index map makes the rebuild linear.
- Maximum Width of Binary Tree solution explained: heap-style slot numbers in a BFS, renumbered each level so they never overflow.
- Binary Tree Cameras solution explained: a postorder greedy with three states per node, backed by a small DP.
- Trim a Binary Search Tree solution explained: an out-of-range node takes a whole side with it, so the recursion has three short cases.
- Recover Binary Search Tree solution explained: two swapped values show up as drops in the inorder sequence.
- Minimum Height Trees solution explained: peel leaves layer by layer until the one or two center nodes remain.
Bit manipulation and integer limits
- Number of 1 Bits solution explained: n & (n - 1) erases one set bit per step, and unsigned handling keeps the top bit honest.
- Counting Bits solution explained: each count reuses the count of the number shifted right by one.
- Reverse Bits solution explained: move the lowest bit across 32 times, leading zeros included.
- Missing Number solution explained: subtract from the expected total, or let XOR cancel every value that is present.
- Sum of Two Integers solution explained: XOR for the column sums, a shifted AND for the carries, repeated until no carry is left.
- Reverse Integer solution explained: pop and push decimal digits with an overflow test before every push.
Careful bookkeeping
- Encode and Decode Strings solution explained: write each length before its string so no character is off limits.
- Valid Sudoku solution explained: one scan with a record per row, column and box, and no attempt to solve.
Two pointers
- 3Sum solution explained: sort, fix one value, and close in on the other two from both sides while skipping repeats.
- Container With Most Water solution explained: start with the widest pair and always retire the shorter post, with the argument for why that is safe.
Running values and dynamic programming
- Best Time to Buy and Sell Stock solution explained: carry the cheapest earlier price through one pass and measure each day against it.
- Maximum Subarray solution explained: Kadane's algorithm keeps the best sum ending at each position.
- Product of Array Except Self solution explained: a product from the left times a product from the right, with no division.
- Climbing Stairs solution explained: a recurrence from the last move, shrunk to two rolling variables.
Linked lists
- Reverse Linked List solution explained: save the next node, flip the link, advance, in one pass with constant memory.
- Merge Two Sorted Lists solution explained: a dummy head and a tail pointer that always takes the smaller front node.
- Linked List Cycle solution explained: a slow and a fast pointer that must meet if the chain loops.
More sliding windows
- Longest Repeating Character Replacement solution explained: a window is fixable when its length minus its most common letter's count fits the edit budget.
- Permutation in String solution explained: slide a window the size of the pattern and keep its letter counts in step.
More stacks
- Min Stack solution explained: store the smallest value so far next to every item, so the minimum is always on top.
- Evaluate Reverse Polish Notation solution explained: numbers go on a stack, operators pop two and push one, with care over division.
- Generate Parentheses solution explained: backtracking that only adds a bracket when the string can still end balanced.
- Daily Temperatures solution explained: a stack of days still waiting for a warmer one, resolved the moment it arrives.
- Car Fleet solution explained: sort by distance to the finish and count the cars that arrive later than everything ahead.
- Largest Rectangle in Histogram solution explained: each bar's widest rectangle is fixed when a shorter bar pops it off an increasing stack.
More binary trees
- Diameter of Binary Tree solution explained: return a height from each call and record the longest path that bends at that node.
- Balanced Binary Tree solution explained: bottom-up heights with a -1 sentinel that stops at the first uneven node.
- Same Tree solution explained: walk two trees together and stop at the first difference in shape or value.
- Subtree of Another Tree solution explained: a same-tree check from every node, then a linear preorder-and-KMP version.
- Lowest Common Ancestor solution explained: one recursive pass where the node that hears back from both sides is the answer, plus the search tree shortcut.
- Binary Tree Right Side View solution explained: the last node of each level, or the first node a right-first search meets at each depth.
- Count Good Nodes in Binary Tree solution explained: pass the largest value seen so far down the tree and count the nodes that match or beat it.
- Validate Binary Search Tree solution explained: carry a lower and upper bound to each node, or check that an in-order walk strictly rises.
Greedy choices and dynamic programming
- Interleaving String solution explained: a grid over how many letters each string has used, because a greedy merge guesses wrong on repeated letters.
- Jump Game solution explained: every square before the farthest reachable one is reachable too, so one number answers the question.
- Jump Game II solution explained: squares reachable in k jumps form a band, so a breadth-first search needs no queue.
- Gas Station solution explained: a total-fuel check plus a start that resets whenever the running tank dips below zero.
- Partition Labels solution explained: push the cut to the last copy of every letter seen, then cut as early as allowed.
More intervals
- Insert Interval solution explained: copy, absorb, copy, in one pass over a list that is already sorted.
- Non-overlapping Intervals solution explained: keep the range that ends first, and defend it with an exchange argument.
- Meeting Rooms solution explained: after sorting by start, any clash shows up between two neighbors.
Tree traversals and paths
- Binary Tree Inorder Traversal explained: recursion, an explicit stack that dives left, and Morris threading in constant space.
- Symmetric Tree solution explained: compare the two halves in pairs with the children crossed.
- Path Sum solution explained: pass the remaining target down and test for zero only at real leaves.
- Path Sum II solution explained: one shared path with append, recurse, pop, and a copy on every match.
- Binary Tree Zigzag Level Order Traversal explained: ordinary level order where only the output row changes direction.
- Flatten Binary Tree to Linked List explained: splice each left subtree in front of the right one, in place.
Bits and binary search
- Bit manipulation tricks: the handful of bit operations interviews use, and how Python and JavaScript treat negative numbers.
- Find Peak Element solution explained: binary search that follows the slope uphill instead of a sorted order.
- Valid Palindrome solution explained: indexes at both ends skip what does not count and compare what does.
- Two Sum on a sorted array explained: steer two pointers by whether the sum is too small or too large.
- Trapping Rain Water solution explained: move the side with the lower wall, because that wall decides the water level there.
Prefix sums and two-pass scans
- Find Pivot Index solution explained: the right side is the total minus the left side minus the current value.
- Candy solution explained: one pass enforces the left neighbor, one the right, and each child keeps the larger need.
Binary search
- Binary Search solution explained: the halving loop, one boundary convention kept throughout, and the first-position variant.
- Search a 2D Matrix solution explained: a chained grid read as one sorted list, with the staircase walk for its sibling.
- Koko Eating Bananas solution explained: search the range of possible speeds with a monotone yes/no check.
- Find Minimum in Rotated Sorted Array explained: compare the middle with the right end to locate the drop.
- Search in Rotated Sorted Array solution explained: at every midpoint one half is in order, so test the target against it.
- Time Based Key-Value Store solution explained: append versions in time order and search for the last one at or before t.
- Median of Two Sorted Arrays solution explained: search the split of the shorter list so both left sides sit below both right sides.
- Reorder List solution explained: find the middle, reverse the back half, then weave the two halves together.
Dynamic programming
- Unique Paths II solution explained: ways from above plus ways from the left, with blocked cells set to zero and one row of memory.
- Triangle solution explained: fold each row into the one above, so the answer ends at the top.
- Maximal Square solution explained: the largest square ending at a cell is one more than its weakest neighbor.
- Regular Expression Matching solution explained: at each starred token, skip it or use it once and stay.
- Wildcard Matching solution explained: a prefix table, then a greedy that only backtracks to the last star.
- Burst Balloons solution explained: choose the last balloon between two walls so the two sides split.
- First Bad Version solution explained: halve the range around the point where a yes/no check flips, with the loop condition that cannot skip the answer.
If you are short on time, a sensible order is Two Sum, Valid Parentheses, Merge Intervals, Longest Substring, Top K Frequent Elements, Binary Tree Level Order Traversal, Number of Islands and LRU Cache last, since the cache combines two structures and invites the longest follow-up discussion.
Every problem, A to Z
The full list of walkthroughs in alphabetical order, with the key idea for each in a few words.
0-9 and A to C
- 3Sum: Sort, fix one value, then two pointers, with duplicates skipped.
- 3Sum Closest: Sort, fix one, squeeze two pointers toward the target.
- 3Sum Smaller: Count triples under a target by adding the gap between pointers.
- 4Sum: Sort, fix two values, close in on the last two with pointers.
- 132 Pattern: Scan from the right; the largest value a stack pops is the best middle.
- Accounts Merge: Emails are the nodes; each connected group is one person.
- Add Two Numbers: Grade-school addition with a carry on linked lists.
- Alien Dictionary: First differing letters become edges; topologically sort them.
- All Nodes Distance K in a Binary Tree: Add parent links, then BFS k steps outward.
- All Paths From Source to Target: Backtracking on a DAG, with complexity set by the output.
- Arithmetic Slices: Count the slices ending at each index: one more while the step repeats, zero when it changes.
- Arranging Coins: Find the largest k whose triangular number fits, by search or by formula.
- Assign Cookies: Sort both lists and match from the small end.
- Asteroid Collision: Keep survivors on a stack and let each left-moving rock fight the top.
- At Most K Distinct Characters: A forward-only window that shrinks when a (k+1)th kind arrives.
- At Most Two Distinct Characters: Two remembered kinds and the trailing run: no map needed.
- Backtracking pattern: Choose, explore, undo, and prune early.
- Bag of Tokens: Spend cheap tokens for points and cash in expensive ones for power.
- Balanced Binary Tree: Bottom-up heights with a sentinel that stops at the first uneven node.
- Basic Calculator: Evaluate plus, minus and nested brackets in one pass with a small stack.
- Basic Calculator II: Remember the operator before each number; * and / rewrite the top term.
- Best Time to Buy and Sell Stock: One pass with a running minimum: the cheapest buy before each sale.
- Best Time to Buy and Sell Stock II: Unlimited trades: add up every rise, and prove why that is best.
- Big O cheat sheet: Growth classes, operation costs and the rules for deriving them.
- Binary Search: Halve the range each step, and keep one boundary convention throughout.
- Binary search pattern: Three templates that cover most binary search questions.
- Binary Subarrays With Sum: Count exact sums with prefix counts, or with two at-most windows.
- Binary Tree Cameras: Three states per node and a camera only when a child needs one.
- Binary Tree Inorder Traversal: Dive left pushing nodes, pop one, record it, then go right.
- Binary Tree Level Order Traversal: Breadth-first search that reads a tree one level at a time.
- Binary Tree Maximum Path Sum: Return one-sided gains, record two-sided paths, in one pass.
- Binary Tree Postorder Traversal: Left, right, root: recursion, a reverse trick and one stack.
- Binary Tree Preorder Traversal: Root, left, right: recursion, a stack, and Morris threading.
- Binary Tree Right Side View: The last node of each level, or the first node a right-first search meets per depth.
- Bit Manipulation Tricks: About eight bit operations, when to spot them, and how languages differ on negatives.
- Boats to Save People: Pair the heaviest with the lightest using two pointers.
- Break a Palindrome: First non-'a' in the left half becomes 'a', or the last letter becomes 'b'.
- Buildings With an Ocean View: Walk from the ocean side and keep the tallest height seen so far.
- Burst Balloons: Pick the last balloon between two walls; the sides split cleanly.
- Bus Routes: Search in waves of buses boarded, and read each route only once.
- Buy and Sell Stock IV: At most k trades, solved with two states per trade count.
- Candy: One pass per direction, then take the larger requirement at each child.
- Capacity to Ship Packages: Binary search the ship capacity with a one-pass day count.
- Car Fleet: Sort by distance to the finish and count the cars that arrive later than everything ahead.
- Car Pooling: Turn rides into load changes and keep a running total along the road.
- Cheapest Flights Within K Stops: Shortest path with an edge budget: k + 1 rounds of Bellman-Ford.
- Cherry Pickup: Collect the most cherries on a round trip with a two-walker DP.
- Climbing Stairs: A first dynamic programming recurrence, solved with two variables.
- Clone Graph: Deep-copy a connected graph with one traversal and an original-to-copy map.
- Coin Change: Fewest coins for an amount: greedy breaks, a table from 0 upward does not.
- Coin Change II: Count coin combinations for an amount, and why loop order matters.
- Combination Sum: Backtrack on sorted candidates, reuse by staying on the same index.
- Combination Sum II: Distinct groups that hit a target, each entry used once.
- Combination Sum III: Sets of k distinct digits from 1 to 9 that sum to n.
- Concatenated Words: Find words built from two or more other words in the list.
- Concatenation of All Words: A word-sized window per offset, with counts for duplicate words.
- Connecting Cities With Minimum Cost: A classic minimum spanning tree, plus the check for a map that cannot be joined.
- Construct Tree From Inorder and Postorder: Last postorder value is the root; inorder splits the rest.
- Container With Most Water: Two pointers from both ends, always retiring the shorter post.
- Contains Duplicate: Set membership with an early exit, and when sorting is the better trade.
- Convert Sorted Array to BST: Middle becomes the root; each half builds a subtree.
- Copy List with Random Pointer: Deep copy with a map, or by weaving clones in.
- Count Good Nodes in Binary Tree: Pass the largest value seen so far down the tree and count nodes that match or beat it.
- Count Number of Nice Subarrays: Exactly k odd values: prefix counts or at most k minus at most k - 1.
- Count of Range Sum: Subarray sums in a range: prefix pairs counted during merge sort.
- Count of Smaller After Self: Later smaller values per position: Fenwick tree or merge sort.
- Count Primes: Count the primes below n with the Sieve of Eratosthenes.
- Count Servers That Communicate: Row and column totals instead of a graph search.
- Count Square Submatrices with All Ones: The largest square ending at each cell is also the number of squares ending there, so sum the table.
- Count Sub Islands: Fill each island of the second grid and let one water cell in the first fail it.
- Count Vowels Permutation: Count vowel strings of length n where each vowel limits what comes next.
- Counting Bits: Every number reuses the bit count of half of itself.
- Course Schedule: Cycle detection on prerequisites with in-degree counters or a three-state search.
- Course Schedule II: Return a valid order of prerequisites, or nothing when a loop blocks it.
- Course Schedule IV: Precompute reachability once, answer every query in O(1).
- Custom Sort String: Count the text, then write letters out in the order you were given.
- Cut Off Trees for Golf Event: Fixed order, many legs: sort by height and BFS each one.
D to G
- Daily Temperatures: A stack of days still waiting for a warmer one, settled the moment it arrives.
- Data Stream as Disjoint Intervals: Summarize a stream of numbers as merged runs of consecutive values.
- Decode String: Expand nested repeat counts like 2[a3[b]] with one pass and a stack.
- Decode Ways: Count, do not list: a one-digit case plus a two-digit case, and careful zeros.
- Decode Ways II: Count decodings with wildcard stars using a weighted DP.
- Delete and Earn: Total each value, then no two consecutive values.
- Delete Node in a BST: Leaf, one child, or two: the successor fills the gap.
- Design Browser History: One array and two indexes make visit, back and forward constant time.
- Design Circular Queue: A fixed array that wraps around, with every queue operation in constant time.
- Design HashMap: Build put, get and remove on plain arrays, and explain what makes them O(1).
- Design Hit Counter: Queue of per-second counts with a running total, or 300 fixed slots.
- Design Linked List: Sentinels, a size field, and clear index rules.
- Design Twitter: Keep each user's posts in time order and merge the newest ends with a heap.
- Design Underground System: Keep only what the average needs: a sum and a count per station pair.
- Detonate the Maximum Bombs: Draw one-way edges from each blast circle, then count what every bomb can reach.
- Diameter of Binary Tree: One post-order pass that returns a height and records the longest bend.
- Diameter of N-ary Tree: Add the two tallest arms at every node.
- Dice Rolls With Target Sum: Count the rolls of d dice with f faces that add up to a target.
- Different Ways to Add Parentheses: Divide and conquer on the operator applied last, with a cache per range.
- Dijkstra's algorithm: Shortest paths from one start node when no edge weight is negative.
- Distinct Subsequences: Count the ways a pattern can be picked out of a longer string.
- Divide Chocolate: Maximize the smallest piece with a guess, a greedy sweep and binary search.
- Domino and Tromino Tiling: Count the tilings of a 2 by n board with dominoes and L-shaped trominoes.
- Dungeon Game: Fill from the last room back to the first.
- Dynamic programming patterns: A recipe for state and transitions, and the six families to know.
- Edit Distance: Fewest inserts, deletes and replacements, from a table you can trace back.
- Employee Free Time: Shared gaps across sorted schedules: a sweep or a heap merge.
- Encode and Decode Strings: Frame each string with its length so any character is safe.
- Equal Substrings Within Budget: Costs per position, then the longest window that stays on budget.
- Evaluate Division: Multiply edge weights along a path, or store each ratio to a root.
- Evaluate Reverse Polish Notation: A stack used as a calculator, with the negative-division trap.
- Exclusive Time of Functions: The top of the stack owns the time between events; ends count their own unit.
- Fibonacci Number: From exponential recursion to a two-variable loop and fast doubling.
- Find All Anagrams in a String: Slide a pattern-width window and compare letter counts.
- Find All Possible Recipes: A topological sort hiding behind ingredient lists.
- Find Duplicate Subtrees: Key each subtree by (left id, value, right id).
- Find Eventual Safe States: Unsafe means you can reach a cycle; peel safe nodes back from the dead ends.
- Find K Closest Elements: Binary search where the k-length window starts.
- Find K Pairs with Smallest Sums: Seed a heap with the first column of the sum grid and move right on each pop.
- Find Median from Data Stream: A max-heap for the low half and a min-heap for the high half.
- Find Minimum in Rotated Sorted Array: Compare the middle with the right end to see which side holds the drop.
- Find Minimum in Rotated Sorted Array II: Locate the smallest value in a rotated list with repeats, and why ties cost speed.
- Find Peak Element: Binary search on the slope: always move toward the higher neighbor.
- Find Pivot Index: The right side is the total minus the left side minus the current value.
- Find the City: All-pairs shortest distances, a count per city, and ties to the larger number.
- Find the Duplicate Number: Floyd's cycle detection on an array of indexes.
- Find the Town Judge: Score each person by arrows in minus arrows out; the judge hits n - 1.
- First Bad Version: Binary search for the point where a yes/no check flips.
- First Missing Positive: Use the array's indices as a lookup table for the values 1 to n.
- First Unique Character: Index of the first character that appears only once.
- Fizz Buzz: Numbers 1 to n with Fizz, Buzz and FizzBuzz, written to take new rules.
- Flatten Binary Tree to Linked List: Hang the right subtree under the left subtree's rightmost node, then shift left to right.
- Flood Fill: Repaint a connected grid region with DFS or BFS.
- Frog Jump: Track which hop sizes land on each stone, not just whether it is reached.
- Fruit Into Baskets: Reframe the orchard as the longest stretch with at most two values, then slide a window.
- Furthest Building You Can Reach: Give every climb a ladder for now; move the smallest onto bricks when short.
- Gas Station: Check total fuel, then reset the start every time the running tank goes negative.
- Generate Parentheses: Backtracking that only adds a bracket when the string can still end balanced.
- Graph traversal patterns: BFS, DFS, multi-source BFS and topological order, and when each fits.
- Graph Valid Tree: Exactly n - 1 edges and one connected piece: the definition of a tree, checked in linear time.
- Group Anagrams: Give every word a signature, then bucket words by it in one pass.
- Grumpy Bookstore Owner: Count the happy-anyway customers once, then slide for the best bonus.
- Guess Number Higher or Lower: Binary search with an oracle: guess the middle and let the hint cut the range.
- Guess Number Higher or Lower II: Least money to always win: minimax over every guess in a range.
H to L
- H-Index: Cap counts at n, then walk the buckets down until papers catch up.
- H-Index II: Binary search for the first paper whose citations cover everything to its right.
- Happy Number: Reach 1 or loop: detect the cycle.
- Heap and priority queue: Top k, k-way merge, running median and scheduling with heaps.
- House Robber: Take it or skip it: the first dynamic programming recurrence most people learn.
- House Robber II: A circle is two lines: run the straight-line solution twice.
- House Robber IV: Binary search the limit, greedy check per guess.
- Implement Trie: Store words letter by letter so prefix lookups cost the query length.
- Insert Delete GetRandom O(1): An array and an index map, kept packed by swapping with the last element.
- Insert Interval: Copy what ends before, absorb what overlaps, copy what starts after.
- Integer Break: Split n into parts with the largest product.
- Integer to Roman: Spell 1 to 3999 as a Roman numeral with a greedy table of 13 values.
- Interleaving String: A grid over how many letters each string has used, filled from above and from the left.
- Intersection of Two Arrays: Find shared values with a set or a sorted merge.
- Intersection of Two Linked Lists: Walk A then B, and B then A; meet at the join.
- Interval List Intersections: Overlaps of two sorted interval lists with one pointer each.
- Intervals pattern: Sort by start to merge, by end to keep the most, or sweep events.
- Invert Binary Tree: Swap the children at every node to mirror a tree.
- IPO: Unlock projects by required capital, then always take the largest profit.
- Is Graph Bipartite: Two-colour as you search; a same-colour edge says no.
- Island Perimeter: Measure a grid island's coastline by counting sides.
- Isomorphic Strings: Compare where each character was seen, not the characters themselves.
- Job Scheduling: Weighted interval scheduling with a sort and a binary search.
- Jump Game: Track the farthest reachable index; a gap past it means the end is out of reach.
- Jump Game II: Breadth-first search in bands: count how many bands it takes to cover the last square.
- Jump Game III: Two-way jumps make it a graph; a visited array makes it linear.
- Jump Game VII: Pull reachability from a sliding window instead of pushing it forward.
- K Closest Points to Origin: Rank by squared distance and keep the k best in a max-heap.
- K-th Smallest Prime Fraction: Each denominator is a sorted row: merge rows with a heap or binary search the value.
- Keys and Rooms: Search from room 0 and check that every room was reached.
- Knight Dialer: Count the numbers a chess knight can dial on a phone keypad.
- Koko Eating Bananas: Binary search the speed, not an array: the check flips from no to yes once.
- Kth Largest Element in a Stream: Keep only the k largest values in a min-heap and read the top.
- Kth Largest Element in an Array: Keep a size-k min-heap, or quickselect for average linear time.
- Kth Missing Positive Number: Binary search on how many numbers are missing so far.
- Kth Smallest Element in a BST: Walk a search tree in order and stop at the kth value.
- Kth Smallest in a Sorted Matrix: Heap merge or binary search on value with a staircase count.
- Kth Smallest Number in Multiplication Table: Count cells below a guess with division, then binary search the guess.
- Largest Divisible Subset: Sort, then find the longest chain where each number divides the next, and rebuild it from parent links.
- Largest Number: Sort digit strings by which join is bigger, then handle the zeros.
- Largest Rectangle in Histogram: An increasing stack that measures each bar's widest rectangle when a shorter bar arrives.
- Largest Time for Given Digits: Twenty-four orderings, two range checks, and no greedy trap.
- Last Stone Weight: Pop the two heaviest stones from a max-heap until one or none is left.
- Last Stone Weight II: Find the lightest stone that can be left after smashing pairs in any order.
- Lemonade Change: Two counters and one greedy rule for breaking a twenty.
- Letter Combinations of a Phone Number: Spell every word a keypad digit string allows, one recursion level per digit.
- LFU Cache: Evict the least frequently used key, oldest first on ties, in constant time.
- Linked List Cycle: Floyd's tortoise and hare: a fast pointer that must catch a slow one.
- Linked List Cycle II: Meet in the loop, then walk from the head.
- Logger Rate Limiter: Store when each message may print again; only real prints move the clock.
- Longest Absolute File Path: Keep the path length per depth; a file adds its name to its parent's length.
- Longest Arithmetic Subsequence: Give every index a map from step to the longest run ending there, and extend it from each earlier index.
- Longest Common Subsequence: Fill a two-string table, then walk it back to recover the LCS.
- Longest Consecutive Sequence: A hash set and one rule: only start counting where a run begins.
- Longest Cycle in a Graph: Timestamped walks on a graph where each node has one arrow.
- Longest Increasing Path in a Matrix: Memoize the longest path from each cell; strict increase means no cycles.
- Longest Increasing Subsequence: Find the longest strictly increasing subsequence in O(n log n).
- Longest Palindrome: Use every pair of matching letters and at most one leftover in the middle.
- Longest Palindromic Substring: Every palindrome has a middle: expand from all 2n - 1 of them.
- Longest Repeating Character Replacement: A sliding window that keeps its most common letter and rewrites the rest.
- Longest Substring Without Repeating Characters: The sliding window, with a left edge that never moves backward.
- Longest Valid Parentheses: A stack of indexes with a barrier at the bottom, or two counter passes.
- Longest ZigZag Path in a Binary Tree: Two counters per node: arrived left, arrived right.
- Loud and Rich: Dynamic programming on a DAG, richest to poorest.
- Lowest Common Ancestor: The node that hears back from both sides is the answer, plus the search tree shortcut.
- LRU Cache: Hash map plus doubly linked list, for O(1) get, put and eviction.
M to P
- Magnetic Force Between Two Balls: Maximize the smallest gap with a greedy check inside a binary search.
- Majority Element: Keep one candidate and a lead counter; verify if a majority is not promised.
- Majority Element II: Two candidates, cancel triples, then verify the survivors.
- Making A Large Island: Label islands once, then add up the different islands around each zero.
- Matrix Chain Multiplication: The classic interval DP: try every split, fill the table by chain length.
- Max Area of Island: Measure each island with one flood fill and keep the biggest.
- Max Chunks To Make Sorted: Cut wherever the running maximum equals the index; a stack handles repeats.
- Max Consecutive Ones III: Stop choosing flips: find the longest window holding at most k zeros.
- Maximal Rectangle: All-1 rectangles in a grid: row histograms plus a monotonic stack.
- Maximal Square: One plus the smallest of top, left and top-left, then square it.
- Maximum Candies to K Children: Binary search on the share size, with a one-line sum as the check.
- Maximum Depth of Binary Tree: Recursion or a level-by-level count.
- Maximum Frequency Stack: Pop the most frequent value: a stack per frequency level.
- Maximum Length of Repeated Subarray: A table of runs ending at each pair of positions, reset to zero on a mismatch.
- Maximum Points from Cards: Only the split between left and right picks matters, so sweep it.
- Maximum Product Subarray: Kadane with a twist: a negative turns the smallest product into the largest.
- Maximum Subarray: Kadane's algorithm: the best sum ending here, carried in one pass.
- Maximum Width of Binary Tree: Slot numbers 2p and 2p + 1, renumbered level by level.
- Median of a Row-Wise Sorted Matrix: Count entries below a guess, then binary search the guess.
- Median of Two Sorted Arrays: Search where to split the shorter list so both left sides sit below both right sides.
- Meeting Rooms: Sort by start time; any clash shows up between two neighbors.
- Meeting Rooms II: Sort starts and ends apart; the answer is the peak overlap.
- Merge Intervals: Sort by start, then sweep: overlaps can only touch their neighbor.
- Merge k Sorted Lists: Min-heap of heads, or pairwise merging in rounds.
- Merge Sorted Array: Merge two sorted arrays in place by filling from the end.
- Merge Two Sorted Lists: A dummy head, a tail pointer, and the smaller front node each step.
- Min Cost Climbing Stairs: A first DP problem: one recurrence, then two rolling variables.
- Min Cost to Connect All Points: A minimum spanning tree on a complete graph: Prim with a plain array fits best.
- Min Insertions for a Palindrome: Insertions needed = length minus the longest palindromic subsequence.
- Min Stack: A stack that remembers its minimum at every level, so every operation is O(1).
- Minimize Max Distance to Gas Station: Binary search a real-valued answer by counting stations per gap.
- Minimum Arrows to Burst Balloons: Sort by right edge, shoot at it, skip what it pops.
- Minimum Cost For Tickets: Cover travel days with 1, 7 and 30-day passes: a look-back DP.
- Minimum Cost to Hire K Workers: Fix the rate by sorting on ratio, then keep the k smallest qualities.
- Minimum Cost Tree From Leaf Values: Interval DP, then a greedy monotonic stack in O(n).
- Minimum Deletions for Unique Frequencies: Turn the string into counts, then cap each count below the one before.
- Minimum Falling Path Sum: Cheapest top-to-bottom walk, one row of totals at a time.
- Minimum Height Trees: Peel leaves until one or two center nodes remain.
- Minimum Jumps to Reach Home: BFS where the state remembers whether the last jump went backward.
- Minimum Knight Moves: Fold the target into one quadrant and BFS with a small margin.
- Minimum Path Cost in a Grid: Cheapest top-to-bottom route when every move has a price.
- Minimum Path Sum: Cheapest right-and-down grid route with dynamic programming.
- Minimum Remove to Make Valid Parentheses: Mark unmatched brackets with a stack of indexes, then rebuild once.
- Minimum Score Triangulation: Interval DP on polygon corners, from Catalan blow-up to a cubic table.
- Minimum Size Subarray Sum: Grow the window to reach the target, shrink it to find the shortest run.
- Minimum Swaps to Group 1s: A window as long as the number of 1s; the fewest zeros inside wins.
- Minimum Taps to Water a Garden: Turn each tap into a segment, then cover the line greedily.
- Minimum Time to Complete Trips: Count trips finished by time T, then binary search for the first T that is enough.
- Minimum Vertices to Reach All Nodes: In a DAG, the starts you need are exactly the nodes nothing points to.
- Minimum Window Substring: Grow until every needed character is covered, then shrink from the left.
- Missing Number: Compare against the complete range with a sum or an XOR.
- Monotonic stack pattern: Next greater, spans and the histogram rectangle in one pass.
- Most Frequent Subtree Sum: Post-order sums, counted, ties all returned.
- Most Stones Removed with Same Row or Column: Every linked group can shrink to one stone, so the answer is stones minus groups.
- Move Zeroes: Pack non-zero values forward with a write pointer, then zero the tail.
- Moving Average from Data Stream: Add the new value, subtract the one leaving the window, divide by the count.
- My Calendar I: Accept a booking only if neither neighbor in the sorted calendar clashes with it.
- My Calendar II: Reject a booking that would make any moment booked three times.
- N-ary Tree Level Order Traversal: One queue round per level, children in order.
- N-Queens: Place n non-attacking queens row by row, with O(1) column and diagonal checks.
- Nearest Exit from Entrance in Maze: Single-source BFS that stops at the first open border cell.
- Network Delay Time: The latest arrival is the largest shortest-path distance, found with Dijkstra.
- Next Greater Element: Values waiting for an answer sit on a decreasing stack until a bigger one arrives.
- Next Greater Element II: Two laps with a stack of waiting indexes; the second lap only resolves.
- Next Permutation: Find the pivot, swap it with the next larger value, reverse the tail.
- Non-overlapping Intervals: Remove fewest by keeping most: always keep the range that finishes earliest.
- Nth Digit: Find a digit deep in 123456789101112 without building the string.
- Number of 1 Bits: Count set bits by erasing the lowest one until nothing is left.
- Number of Closed Islands: Islands that never touch the edge of the grid.
- Number of Connected Components: Start at n groups and subtract one for every edge that joins two of them.
- Number of Enclaves: Flood fill from the edge, then count the land that is left.
- Number of Good Paths: Add nodes in value order, merge with union-find, and count each component.
- Number of Islands: Count connected land regions with one flood fill per island.
- Number of Islands II: Keep the island count up to date as land appears, with union-find.
- Number of Longest Increasing Subsequence: Track the longest run and how many ways reach it at every index; ties add, longer runs replace.
- Number of Operations to Make Network Connected: Return -1 without n - 1 cables, otherwise count components and subtract one.
- Number of Provinces: Count connected components when the graph comes as a matrix.
- Odd Even Linked List: Two chains by position, then join them.
- Ones and Zeroes: Pick the most binary strings that fit a zero budget and a one budget.
- Online Stock Span: Merge every beaten price into the new one and keep a falling stack.
- Open the Lock: BFS over 10,000 codes, eight neighbours each, skipping blocked ones.
- Optimize Water Distribution: Turn wells into edges from a fake node, then build a minimum spanning tree.
- Pacific Atlantic Water Flow: Climb from each coastline and keep the cells both searches reach.
- Palindrome Linked List: Reverse the back half, compare, put it back.
- Palindrome Partitioning: List every palindromic split of a string with backtracking and a cached table.
- Palindrome Partitioning II: Fewest cuts so every piece is a palindrome.
- Palindromic Substrings: Count, by position, every slice that reads the same both ways.
- Pancake Sorting: Selection sort with a spatula: bring the largest to the top, then flip it down.
- Parallel Courses: Count terms as layers of Kahn's algorithm and return -1 when a cycle blocks courses.
- Partition Equal Subset Sum: Split numbers into two equal-total groups with a reachable-sums table.
- Partition Labels: Stretch the boundary to the last copy of every letter seen, and cut when you reach it.
- Partition to K Equal Sum Subsets: Can a list be split into k groups with equal sums?.
- Path Sum: Pass the remaining target down and test for zero only at leaves.
- Path Sum II: Append, recurse, pop, and save a copy whenever a leaf hits the target.
- Path with Maximum Probability: Dijkstra with a max-heap, multiplying chances instead of adding lengths.
- Path With Minimum Effort: Dijkstra where a route costs its single worst step.
- Perfect Squares: Fewest squares summing to n: DP, BFS and a number theory shortcut.
- Permutation in String: A fixed-size counting window that checks for a shuffled copy of a pattern.
- Permutations: Try every unused value at each position, or swap values into place.
- Permutations II: Every distinct ordering of a list with repeated values.
- Plus One: Carry from the right; all nines grow the list.
- Populating Next Right Pointers: Walk the linked level above to wire the one below.
- Pow(x, n): Square the base, halve the exponent.
- Power of Two: One set bit: check n > 0 and n & (n - 1) == 0.
- Predict the Winner: Two-player game DP: the best lead the mover can secure on each slice.
- Prefix sum pattern: Running totals that turn range sums into one subtraction.
- Process Tasks Using Servers: Assign tasks to the lightest free server with two heaps.
- Product of Array Except Self: Left products times right products, two passes and no division.
- Profitable Schemes: Count the job sets that fit the team and reach a profit target.
- Pseudo-Palindromic Paths: Parity bitmask down the path, one-bit test at leaves.
Q to S
- Queue Reconstruction by Height: Place the tallest people first, then insert each person at their count.
- Queue Using Stacks: Two stacks make a queue, and each item is moved only once.
- Random Pick With Weight: Running totals of the weights, then a binary search for each draw.
- Range Module: Track half-open ranges: merge on add, split on remove, query fast.
- Range Sum Query: Prefix sums when the array is fixed, a Fenwick tree when it changes.
- Ransom Note: Count the magazine as a supply, then spend it on the note.
- Recover Binary Search Tree: Two swapped values show up as drops in the inorder walk.
- Redundant Connection: A tree plus one edge: union-find rejects the edge that closes the only loop.
- Redundant Connection II: Find a node with two parents, then let union-find decide which candidate edge to remove.
- Regions Cut by Slashes: Split each cell into four triangles, join what each wall allows, and count groups.
- Regular Expression Matching: Skip the starred token, or use it once and stay.
- Relative Sort Array: Count first, emit in the given order, sort only the leftovers.
- Remove Boxes: A three-index DP that carries matching boxes forward to square the score.
- Remove Duplicate Letters: Pop a bigger letter only if it appears again later; skip letters already kept.
- Remove Duplicates from Sorted Array: Compact a sorted array in place with two pointers.
- Remove K Digits: Pop bigger digits while removals remain, then trim the end and the zeros.
- Remove Max Edges, Graph Traversable: Two disjoint sets and a greedy order: shared edges before private ones.
- Remove Nth Node From End: Two pointers a fixed gap apart, plus a sentinel node.
- Reorder List: Find the middle, reverse the back half, then weave the two halves.
- Reorder Routes to City Zero: Root the tree at city 0 and count the roads that point away.
- Reorganize String: No equal neighbors: a counting bound and even-then-odd placement.
- Replace Words: Swap each word for its shortest dictionary root with a trie.
- Restore IP Addresses: Four parts, each 0 to 255, no leading zeros.
- Reverse Bits: Move the lowest bit across 32 times, leading zeros included.
- Reverse Integer: Reverse the digits and catch 32-bit overflow before it happens.
- Reverse Linked List: Save, flip, advance: reversing every link in one pass.
- Reverse Nodes in k-Group: Block-by-block in-place reversal of a linked list.
- Reverse Pairs: Count pairs where an earlier value is more than twice a later one.
- Roman to Integer: Add symbol values, subtracting any symbol that sits before a larger one.
- Rotate Array: Reverse all, reverse the first k, reverse the rest.
- Rotate Image: Transpose, then reverse each row: a quarter turn in place.
- Rotate List: Count, reduce k mod n, cut once, re-join.
- Rotting Oranges: Spread rot from every rotten orange at once and count BFS layers as minutes.
- Russian Doll Envelopes: Sort by width, break ties by height descending, then find the longest increasing run of heights.
- Same Tree: Walk two trees in lockstep and stop at the first difference in shape or value.
- Satisfiability of Equality Equations: Merge letters joined by == with union-find, then make sure no != pair shares a group.
- Score of Parentheses: Push 0 per open bracket; each empty pair is worth 2 to its depth.
- Scramble String: Decide if one string is a recursive scramble of another.
- Search a 2D Matrix: Read the grid as one sorted list and binary search positions.
- Search in Rotated Sorted Array: At every midpoint one half is sorted; check whether the target fits there.
- Search in Rotated Sorted Array II: Binary search a rotated list that repeats values, and know when it turns linear.
- Search Insert Position: A binary search that returns where a value is, or where it would go.
- Sequence Reconstruction: Check that Kahn's algorithm never has a choice and that it produces the proposed order.
- Serialize and Deserialize Binary Tree: Null markers let one traversal capture a tree's shape.
- Set Matrix Zeroes: Mark in the first row and column, clear them last.
- Shortest Common Supersequence: Build the shortest string containing both inputs, from an LCS table.
- Shortest Path in Binary Matrix: BFS in eight directions; the start counts as length 1.
- Shortest Path to Get All Keys: Cell plus keys held as the BFS state, packed into a bitmask.
- Shortest Path Visiting All Nodes: BFS over node plus visited bitmask, started from every node.
- Similar String Groups: Test pairs for a single crossed swap, link them with union-find and count the groups.
- Simplify Path: Split on slashes, push names, pop on two dots, join with one slash.
- Single Element in a Sorted Array: Find the unpaired value in O(log n) by checking pair alignment.
- Single Number: XOR everything: pairs cancel, the loner stays.
- Single-Threaded CPU: Sort by arrival, choose from a heap by duration, and jump over idle time.
- Sliding Puzzle: Whole boards as graph nodes, and BFS for the fewest slides.
- Sliding Window Maximum: A deque of indexes with decreasing values keeps each window's maximum at the front.
- Sliding Window Median: A sorted window for clarity, or two heaps with lazy deletion for O(n log n).
- Sliding window pattern: Three window shapes, one counting trick, and when a window fails.
- Smallest Equivalent String: Union-find over letters, where the smaller letter always becomes the root.
- Smallest Letter Greater Than Target: An upper-bound search that skips copies of the target and wraps around.
- Smallest String With Swaps: Group swappable positions with union-find, then sort the letters in each group.
- Snakes and Ladders: Flatten the zigzag board, then BFS over squares with six moves each.
- Snapshot Array: Per-index change logs, read back with a binary search.
- Sort Characters by Frequency: Count each character, bucket by count, and write blocks from the top down.
- Sort Colors: Three pointers split 0s, 1s and 2s in a single pass.
- Sort List: Merge sort: split at the middle, merge by re-linking.
- Spiral Matrix: Four shrinking walls, one ring per loop, two guards.
- Split Array Largest Sum: Binary search the largest piece sum, check it greedily.
- Sqrt(x): Integer square root without built-ins: binary search or Newton.
- Squares of a Sorted Array: Sort squares in one pass with pointers at both ends.
- Stock III: At most two trades: from a split day to four running states.
- Stock with Cooldown: Unlimited trades with a rest day after each sale: a three-state machine.
- Stock with Transaction Fee: Two running states, cash and hold, that pay the fee once per trade.
- Stone Game: Two players take piles from either end; show the first player wins.
- Stone Game II: Take up to 2M piles from the front: DP over position and limit.
- Strange Printer: Interval DP where a stroke is shared only when two letters match.
- Stream of Characters: Detect words at the end of a letter stream with a reversed trie.
- String to Integer (atoi): Read a signed 32-bit integer off the front of a string and clamp it.
- Student Attendance Record II: Count valid attendance strings with a six-state DP.
- Subarray Sum Equals K: Count earlier prefix sums equal to the current prefix minus k.
- Subarrays with K Different Integers: Exactly k distinct values via two at-most windows.
- Subsets: Backtrack with a start index, double the list, or count through bitmasks.
- Subsets II: Every distinct subset of a list with repeated values.
- Subtree of Another Tree: A same-tree check from every node, then a linear serialize-and-search version.
- Sudoku Solver: Fill a 9 by 9 Sudoku with constraint-aware backtracking.
- Sum of Two Integers: Addition rebuilt from XOR, AND and a carry that moves left.
- Sum Root to Leaf Numbers: Carry the number down; add it only at leaves.
- Surrounded Regions: Mark every O the border can reach, then capture the rest in one sweep.
- Swim in Rising Water: Minimize the highest cell on a path with a min-heap keyed by max.
- Symmetric Tree: Compare the two subtrees in pairs, outer with outer and inner with inner.
T to Z
- Target Sum: Count sign patterns that hit a target by counting subsets.
- Task Scheduler: Count the most frequent task, build frames around it, or simulate with a heap.
- The Skyline Problem: Sweep the edges with a heap of live heights.
- Time Based Key-Value Store: Append versions in time order, then binary search for the last one at or before t.
- Top K Frequent Elements: Count with a map, then pick winners with a heap or buckets.
- Top K Frequent Words: Counting plus an ordering where the tie-break runs the other way.
- Topological sort: Order tasks so every rule points forward, and catch cycles.
- Trapping Rain Water: The lower of the two tallest walls sets the water level above every bar.
- Tree from Preorder and Inorder: Preorder names each root, inorder splits its subtrees.
- Triangle: Fold each row into the one above, keeping the cheaper child.
- Tribonacci Number: Turn a three-way recursion into a three-value sliding window.
- Trim a Binary Search Tree: Out-of-range nodes take a whole side with them.
- Two City Scheduling: Sort by the cost gap and split the list in half.
- Two pointers pattern: Opposite ends, read and write, fast and slow: when each one fits.
- Two Sum: The hash map complement trick, from nested loops to one pass.
- Two Sum II (sorted): Converging pointers, and the argument for why they never skip the pair.
- Ugly Number II: The n-th number made only of 2s, 3s and 5s, by merging three streams.
- Uncrossed Lines: Non-crossing lines between equal values: LCS on integers.
- Union-Find: Track which items share a group while links keep arriving, in near-constant time.
- Unique Binary Search Trees: Count BST shapes with a size-based DP and meet the Catalan numbers.
- Unique Binary Search Trees II: Build every BST on 1 to n by pairing all left and right subtrees per root.
- Unique Paths: Count right-and-down routes across a grid with DP or a binomial.
- Unique Paths II: Ways from above plus ways from the left, zero on a blocked cell.
- Valid Anagram: One count table decides whether two strings share the same letters.
- Valid Palindrome: Two indexes walk inward, skipping anything that is not a letter or digit.
- Valid Palindrome II: Can one deletion make it a palindrome? Two pointers and two checks.
- Valid Parentheses: The stack pattern for brackets that must close in reverse order.
- Valid Perfect Square: Search for the root instead of computing it, and watch the overflow.
- Valid Sudoku: One scan, three records per digit: its row, column and box.
- Validate Binary Search Tree: Carry a lower and upper bound to each node, or check that an in-order walk strictly rises.
- Validate Stack Sequences: Push in order and pop while the top is the next value to remove.
- Vertical Order Traversal: Record column, row, value; sort once; group.
- Video Stitching: Cover a timeline with the fewest clips using a farthest-reach greedy.
- Walls and Gates: Seed every gate at once and let the BFS flood claim each room.
- Wiggle Sort II: Sort, split, and fill both halves from the back so median copies never touch.
- Wiggle Subsequence: Two counters, one for wiggles ending on a rise and one for a fall; equal neighbors change nothing.
- Wildcard Matching: A prefix table, or two pointers with a bookmark at the last star.
- Word Break: Decide if a string splits into dictionary words with a prefix table.
- Word Break II: List every split with backtracking; memoize completions per index.
- Word Ladder: A hidden graph of one-letter changes, searched breadth first from both ends.
- Word Ladder II: Layered BFS plus backtracking to list every shortest word chain.
- Word Pattern: Map letters to words and words back to letters, in one pass.
- Word Search: Trace a word across a letter grid with backtracking.
- Word Search II: Find many words on one grid by walking a trie and the board together.
- Zigzag Conversion: Write a string down and up across rows, then read it row by row.
- Zigzag Level Order Traversal: Plain level order, with every other row written right to left.
What a typical coding round rewards
| Signal | What you can do to show it |
|---|---|
| Clarifying the task | Ask about input size, empty input, duplicates and what to return when nothing matches before you plan anything. |
| Problem solving | Offer a brute force, explain why it is slow, and move to a better idea with a stated complexity. |
| Working code | Write code that runs on the first trace, with clear names and no unused branches. |
| Testing | Pick your own small cases, including at least one edge case, and walk them through the code. |
| Communication | Narrate decisions as you make them and check in when you change direction. |
Exact rubrics differ between companies, so treat this as a common shape rather than a rule. The software engineer interview questions guide covers the full loop around the coding round, and the system design hub covers the architecture round that usually follows for mid-level and senior candidates. For every role and question type, start at the interview questions hub. If you want a schedule, the four-week interview prep plan shows how to fit pattern practice around everything else.
Practicing with Natively
Natively is a desktop assistant for Mac and Windows. In practice sessions it can read one of these problems from a screenshot of your screen and suggest which pattern fits and how you might approach it, and it transcribes a mock round so you can reread where you rushed past the brute force or forgot an edge case. Sessions are saved with their transcript and notes. The AI assistant for coding interviews page shows the coding features in more detail.
Questions people ask
Which coding problems should I practice first?
Start with problems that each teach one pattern: Two Sum for hash maps, Valid Parentheses for stacks, Merge Intervals for sorting, then a sliding window, a graph search and a design problem such as an LRU cache.
Is it better to practice many problems or a few patterns?
Patterns. Interviewers change the story around a problem, so recognizing hashing, stacks, windows or breadth-first search transfers further than remembering any single answer.
How long should a coding interview problem take?
Many live rounds give about 30 to 45 minutes for one or two problems, including questions, a brute force, the optimal code and testing. Practice with a timer so the pace feels normal.
Which language should I use in a coding interview?
The one you write fastest without looking things up. Python is popular because it is short, but Java, JavaScript and C++ are all widely accepted. Ask the recruiter if the company has a preference.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
