DSA Interview Questions and Answers, by Pattern
223 data structures and algorithms questions asked in coding interviews, grouped by the pattern that solves them. Each has the approach in a sentence or two, its time and space cost, and a link to a step-by-step visual solution.
Freshers: start with the Easy questions in each pattern before the Medium ones. Learning the pattern matters more than memorising any one answer, because interviewers change the details. For the order to study them in, see the 12-week FAANG preparation roadmap, and for a template per pattern, the patterns cheat sheet.
Two Pointers interview questions
How the two pointers pattern worksEasy · Time O(n) · Space O(1)
Reverse String
Reverse an array of characters in place with two pointers that swap the ends and walk toward the middle.
Answer: Solve Reverse String in place with two pointers: swap the first and last characters, move inward, and stop when they meet. O(n) time, O(1) space, 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Two Sum II - Input Array Is Sorted
The integer array numbers is sorted in non-decreasing order and indexed from 1. Find the two entries whose sum equals target and return their positions.
Answer: Solve Two Sum II in O(n) time and O(1) space: move two pointers inward on the sorted array and return 1-based indices.
Visual solution and codeEasy · Time O(n) · Space O(1)
Valid Palindrome
Check whether a string reads the same both ways, ignoring case and non-alphanumeric characters, with two pointers.
Answer: Check a palindrome in O(1) space: walk two pointers inward, skip anything that is not a letter or digit, and compare ignoring case, step by step.
Visual solution and codeEasy · Time O(m + n) · Space O(1)
Merge Sorted Array
Merge two sorted arrays in place in O(m + n) by filling nums1 from the back with three pointers.
Answer: Solve Merge Sorted Array in place: fill nums1 from the back with the larger of nums1[i] and nums2[j], so nothing is overwritten early. O(m + n), 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Remove Duplicates from Sorted Array
Remove duplicates from a sorted array in place with a read pointer and a write pointer, and return how many unique values remain.
Answer: Solve Remove Duplicates from Sorted Array in place: a write pointer k keeps the unique prefix while i reads ahead. O(n) time, O(1) space, code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Remove Element
Remove every copy of a value from an array in place with a read pointer and a write pointer, and return how many values remain.
Answer: Solve Remove Element in place: a write pointer k collects every value that is not val while i reads the array. O(n) time, O(1) space, with code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Rotate Array
Rotate an array right by k steps in place with three reversals: the whole array, then the first k, then the rest.
Answer: Solve Rotate Array in place with three reversals: reverse all, then the first k, then the rest. O(n) time, O(1) space, visualized step by step in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(n)
Squares of a Sorted Array
Return the sorted squares of a sorted array in O(n): the largest square is always at one end, so fill the output from the back with two pointers.
Answer: Solve Squares of a Sorted Array in O(n) without sorting: compare the absolute values at both ends and fill the output from the largest square down. 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Is Subsequence
Check whether s is a subsequence of t in one pass with two pointers, matching each character of s at its first chance in t.
Answer: Solve Is Subsequence in O(n): walk t with one pointer and move a pointer in s on every match. Greedy, visualized, with code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Valid Palindrome II
Decide whether a string becomes a palindrome after deleting at most one character, by trying both deletions only at the first mismatch.
Answer: Solve Valid Palindrome II in O(n): move two pointers inward, and at the first mismatch check whether skipping the left or right character leaves a palindrome.
Visual solution and codeMedium · Time O(n²) · Space O(1)
Longest Palindromic Substring
Find the longest substring that reads the same both ways by expanding two pointers outward from every possible centre.
Answer: Solve Longest Palindromic Substring by expanding around centres: 2n − 1 centres, two pointers stepping out while characters match.
Visual solution and codeMedium · Time O(n²) · Space O(1)
Palindromic Substrings
Count every palindromic substring of a string by expanding two pointers outward from each of its 2n − 1 centres.
Answer: Count palindromic substrings in O(n²) time and O(1) space: expand two pointers from every character and every gap, counting each match.
Visual solution and codeMedium · Time O(n) · Space O(n)
Encode and Decode Strings
Encode a list of strings into one string and decode it back with length prefixes, read by two pointers.
Answer: Encode and decode a list of strings with length prefixes: write length#word, then read it back with two pointers, safe even when words contain '#'.
Visual solution and codeMedium · Time O(n) · Space O(1)
Container With Most Water
Pick the two vertical lines that, with the x-axis as the floor, hold the most water between them.
Answer: Find the container that holds the most water in O(n): start with the widest pair and move the shorter line inward. Compare it with checking every pair.
Visual solution and codeMedium · Time O(n²) · Space O(log n)
3-Sum
Find every group of three values, taken from different positions in the integer array nums, that adds up to 0, listing each distinct triplet once.
Answer: Find every unique triplet that sums to zero: sort, fix one value, and close two pointers on the rest while skipping duplicates.
Visual solution and codeMedium · Time O(n²) · Space O(1)
3Sum Closest
Find the sum of three numbers closest to a target in O(n²): sort, fix one number, and move two pointers toward the target.
Answer: Solve 3Sum Closest in O(n²): sort, fix one number, move two pointers toward the target, and keep the sum with the smallest distance. Visualized, 6 languages.
Visual solution and codeMedium · Time O(n³) · Space O(1)
4Sum
Find every unique quadruplet that sums to a target: sort, fix two numbers with nested loops, and sweep the rest with two pointers, skipping duplicates.
Answer: Solve 4Sum in O(n³): sort, fix two numbers, sweep the rest with two pointers, and skip duplicates at every level. Watch the four pointers move. 6 languages.
Visual solution and codeMedium · Time O(n²) · Space O(log n)
Valid Triangle Number
Count how many triples of values from the integer array nums could be the three side lengths of a valid triangle.
Answer: Count the triplets that form a triangle: sort, fix the longest side, and count every valid pair at once with two pointers.
Visual solution and codeEasy · Time O(n) · Space O(1)
Move Zeroes
Shift every 0 in the integer array nums to the back, in place, keeping the non-zero values in their original order.
Answer: Move every zero to the end in place while keeping the order of the other values, with a read pointer and a write pointer.
Visual solution and codeMedium · Time O(n) · Space O(1)
Sort Colors
Sort an array of 0s, 1s and 2s (red, white and blue) in place and in one pass, so equal colours sit together in the order red, white, blue.
Answer: Sort 0s, 1s and 2s in one pass and in place with low, mid and high pointers — the Dutch National Flag partition. Step through it.
Visual solution and codeHard · Time O(n) · Space O(1)
Trapping Rain Water
Compute how much water can be trapped after raining.
Answer: Compute trapped rain water in O(n) time and O(1) space by moving the pointer on the side with the lower wall. Step through it.
Visual solution and codeMedium · Time O(m · n) · Space O(m + n)
Multiply Strings
Multiply two numbers given as strings without converting them, using grade-school multiplication into an array of m + n digit positions.
Answer: Solve Multiply Strings without BigInteger: digit i times digit j lands on positions i + j and i + j + 1. Step-by-step dry run and code in 6 languages.
Visual solution and codeEasy · Time O(max(m, n)) · Space O(max(m, n))
Add Binary
Add two binary strings with two pointers from the right and a carry: each column's sum mod 2 is the bit, sum / 2 the carry.
Answer: Solve Add Binary by adding columns from the right: bit = total % 2, carry = total / 2, and keep going while a carry is left. Dry run and code in 6 languages.
Visual solution and codeEasy · Time O(max(m, n)) · Space O(max(m, n))
Add Strings
Add two non-negative numbers given as strings with two pointers from the right and a carry, without converting them to integers.
Answer: Solve Add Strings without converting to integers: add digits from the right, write total % 10, carry total / 10. Dry run, edge cases and code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Plus One
Add one to a number stored as an array of digits: walk from the end, turn trailing 9s into 0s, and grow the array only when every digit was 9.
Answer: Solve Plus One by walking from the last digit: a digit under 9 takes the +1 and you return, a 9 becomes 0 and carries. All 9s grow the array. 6 languages.
Visual solution and code
Hash Map interview questions
How the hash map pattern worksEasy · Time O(n) · Space O(n)
Two Sum
Find the indices of two numbers that add up to a target in one pass with a hash map.
Answer: Solve Two Sum in one pass: store each number, look up its complement, and watch the map fill step by step. Brute force and.
Visual solution and codeEasy · Time O(n) · Space O(n)
Contains Duplicate
Return true if any value appears at least twice in the array, using one pass with a hash set.
Answer: Solve Contains Duplicate in one pass: check each number against a hash set, stop at the first repeat, and watch the set fill step by step.
Visual solution and codeEasy · Time O(n) · Space O(k)
Valid Anagram
Decide whether two strings are anagrams by counting letters in a hash map.
Answer: Check whether two strings are anagrams with one hash map: count every letter of s, spend them on t, and watch the counts rise and fall step by step.
Visual solution and codeMedium · Time O(n · k log k) · Space O(n · k)
Group Anagrams
Group words that are anagrams of each other, using each word's sorted letters as a hash map key.
Answer: Group anagrams in one pass: sort each word's letters into a key, collect words under their key in a hash map, and watch every group form step by step.
Visual solution and codeMedium · Time O(n) · Space O(n)
Top K Frequent Elements
Return the k most frequent values in an array in O(n) with a count map and buckets indexed by frequency.
Answer: Find the k most frequent elements in O(n): count with a hash map, drop each value into a bucket by its count, and read the buckets from the top down.
Visual solution and codeMedium · Time O(n) · Space O(n)
Longest Consecutive Sequence
Find the length of the longest run of consecutive integers in an unsorted array in O(n) with a hash set.
Answer: Find the longest consecutive run in O(n) without sorting: put the numbers in a hash set and count each run only from its start, step by step.
Visual solution and codeMedium · Time O(81) · Space O(81)
Valid Sudoku
Check that a partly filled Sudoku board has no repeated digit in any row, column or 3×3 box, in one pass with hash sets.
Answer: Solve Valid Sudoku in one pass: a set for every row, column and 3×3 box, with box = (r / 3) * 3 + c / 3. Watch each digit get checked.
Visual solution and codeEasy · Time O(n) · Space O(1)
Majority Element
Find the value that appears more than n/2 times: count with a hash map, or use Boyer-Moore voting for O(n) time and O(1) space.
Answer: Solve Majority Element with a hash map count, then in O(1) space with Boyer-Moore voting: a candidate and a count that cancels. Code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(k)
Isomorphic Strings
Check whether two strings are isomorphic with two hash maps, s to t and t to s, that must stay consistent for every pair of letters.
Answer: Solve Isomorphic Strings in O(n) with two hash maps, s→t and t→s; see why one map misses cases like badc and baba. Visual walkthrough, code in 6 languages.
Visual solution and codeEasy · Time O(n + m) · Space O(n + m)
Word Pattern
Check whether a string of words follows a letter pattern with two hash maps, letter to word and word to letter, after checking the counts match.
Answer: Solve Word Pattern in O(n + m): split s, check the word count, then keep letter→word and word→letter maps consistent. Visual walkthrough, code in 6 languages.
Visual solution and codeEasy · Time O(m + n) · Space O(1)
Ransom Note
Decide whether a ransom note can be built from a magazine's letters by counting the magazine in a hash map and spending one count per note letter.
Answer: Solve Ransom Note in O(m + n): count the magazine's letters, then spend one per note letter; fail when a count hits 0. Visual walkthrough, 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
First Unique Character in a String
Find the index of the first non-repeating character with two passes: count every letter in a hash map, then return the first index with count 1.
Answer: Solve First Unique Character in a String in O(n): count letters in a hash map, then scan again for the first count of 1. Visual walkthrough, 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Roman to Integer
Convert a Roman numeral to an integer in one pass with a symbol-value map: subtract a symbol that is smaller than the next one, otherwise add it.
Answer: Solve Roman to Integer in one pass: map each symbol to its value, subtract it when the next symbol is bigger, add it otherwise. Visual walkthrough, 6 languages.
Visual solution and code
Sliding Window interview questions
How the sliding window pattern worksMedium · Time O(n) · Space O(min(n, charset))
Longest Substring Without Repeating Characters
Find the length of the longest substring without repeating characters.
Answer: Solve Longest Substring Without Repeating Characters in O(n): store each character’s last index and jump the window past repeats.
Visual solution and codeMedium · Time O(n) · Space O(1)
Longest Repeating Character Replacement
Replace characters to get the longest repeating character substring.
Answer: Find the longest substring you can turn into one letter with at most k replacements: a sliding window with letter counts.
Visual solution and codeHard · Time O(|s| + |t|) · Space O(k)
Minimum Window Substring
Find the shortest part of s that contains every character of t, duplicates included, with a window that grows until it covers t and shrinks while it still does.
Answer: Solve Minimum Window Substring in O(|s| + |t|): extend right until the window covers t, then shrink from the left while it still does.
Visual solution and codeMedium · Time O(n) · Space O(1)
Minimum Size Subarray Sum
Find the shortest subarray whose sum reaches a target in O(n) with a sliding window that grows on the right and shrinks from the left.
Answer: Solve Minimum Size Subarray Sum in O(n): grow the window right, and while its sum reaches the target, record its length and shrink from the left. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Max Consecutive Ones III
Find the longest run of 1s after flipping at most k zeros, as the longest sliding window containing at most k zeros.
Answer: Solve Max Consecutive Ones III in O(n): keep a window with at most k zeros, shrink it from the left when one zero too many arrives, track the longest.
Visual solution and codeMedium · Time O(n) · Space O(1)
Fruit Into Baskets
Pick the most fruit with two baskets from consecutive trees: the longest sliding window with at most two distinct values.
Answer: Solve Fruit Into Baskets in O(n): it is the longest window with at most two distinct values. Count kinds in a map and shrink when a third arrives. 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(min(n, k))
Contains Duplicate II
Check whether two equal values sit at most k positions apart, with a sliding set that holds only the last k values.
Answer: Solve Contains Duplicate II in O(n): keep a set of the last k values; if the next value is already in it, two copies are at most k apart. Code in 6 languages.
Visual solution and codeMedium · Time O(k) · Space O(1)
Maximum Points You Can Obtain from Cards
Find the maximum score you can get by taking k cards from either end of the row.
Answer: Take k cards from either end for the highest score: start with all k from the left, then trade one left card for one right card at a time.
Visual solution and codeMedium · Time O(n) · Space O(k)
Maximum Sum of Distinct Subarrays With Length K
Find the maximum sum of a fixed-size subarray where all elements are distinct.
Answer: Find the largest sum of k consecutive distinct values: slide a window with a running sum and a count map, and skip windows that repeat a value.
Visual solution and codeMedium · Time O(n) · Space O(1)
Permutation in String
Check whether s2 contains a permutation of s1 by sliding a fixed window of len(s1) and comparing letter counts.
Answer: Solve Permutation in String with a fixed sliding window: keep 26 letter counts for the last len(s1) characters of s2 and compare them with s1's. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Find All Anagrams in a String
Find every start index of an anagram of p in s with a fixed-size sliding window that keeps letter counts up to date as it moves.
Answer: Solve Find All Anagrams in a String in O(n) with a fixed sliding window: add the entering letter, drop the leaving one, compare 26 counts. Code in 6 languages.
Visual solution and codeHard · Time O(n) · Space O(k)
Sliding Window Maximum
Return the maximum of every window of size k in O(n) with a monotonic deque that keeps only indexes that could still become a maximum.
Answer: Solve Sliding Window Maximum in O(n) with a monotonic deque: drop expired indexes from the front, smaller values from the back.
Visual solution and code
Intervals interview questions
How the intervals pattern worksMedium · Time O(n log n) · Space O(n)
Merge Intervals
Merge all overlapping intervals.
Answer: Solve Merge Intervals in O(n log n): sort by start, then extend the last merged interval or append a new one. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(n)
Insert Interval
Insert a new interval into a sorted non-overlapping list.
Answer: Insert a new interval into a sorted, non-overlapping list in O(n): copy what ends before it, absorb what overlaps it, then copy the rest.
Visual solution and codeMedium · Time O(n log n) · Space O(log n)
Non-overlapping Intervals
Find the minimum number of intervals to remove to eliminate all overlaps.
Answer: Find the fewest intervals to remove so none overlap: sort by end, keep each interval that starts at or after the last kept end, and count the rest.
Visual solution and codeEasy · Time O(n log n) · Space O(log n)
Meeting Rooms
Determine if a person can attend all meetings.
Answer: Decide whether one person can attend every meeting: sort by start time and check each meeting against the one before it.
Visual solution and codeMedium · Time O(n log n) · Space O(n)
Meeting Rooms II
Find the minimum number of conference rooms required.
Answer: Find the minimum number of meeting rooms in O(n log n): sort start and end times separately and walk them with two pointers.
Visual solution and codeMedium · Time O(n log n) · Space O(log n)
Min Arrows to Burst Balloons
Find the minimum number of arrows to burst overlapping balloons.
Answer: Find the fewest arrows that burst every balloon: sort balloons by end, shoot at each uncovered balloon’s end, and count the arrows.
Visual solution and code
Linked List interview questions
How the linked list pattern worksEasy · Time O(n) · Space O(1)
Reverse Linked List
Reverse a singly linked list in place by flipping one link at a time.
Answer: Reverse a linked list in place with three pointers and watch each next link flip one node at a time. Iterative and recursive.
Visual solution and codeEasy · Time O(n) · Space O(1)
Middle of the Linked List
Find the middle node of a linked list in one pass with slow and fast pointers: when fast reaches the end, slow is halfway.
Answer: Solve Middle of the Linked List in one pass: slow moves 1, fast moves 2, and slow is the middle when fast hits the end. Visual walkthrough, code in 6 languages.
Visual solution and codeEasy · Time O(m + n) · Space O(1)
Intersection of Two Linked Lists
Find the node where two linked lists merge in O(1) space: two pointers that each walk one list then the other meet at the intersection or at NULL.
Answer: Solve Intersection of Two Linked Lists in O(m + n) time, O(1) space: each pointer walks its list then the other, so both meet at the shared node. 6 languages.
Visual solution and codeEasy · Time O(n + m) · Space O(1)
Merge Two Sorted Lists
Merge two sorted linked lists into one sorted list by splicing nodes after a dummy head.
Answer: Merge two sorted linked lists in place: hang nodes off a dummy head, take the smaller head each step, and attach the leftover list at the end.
Visual solution and codeMedium · Time O(max(m, n)) · Space O(max(m, n))
Add Two Numbers
Add two numbers stored as reversed linked lists of digits, column by column with a carry, building the result through a dummy head.
Answer: Solve Add Two Numbers: walk both reversed digit lists, add each column and the carry, append the digit through a dummy head. Step through it.
Visual solution and codeEasy · Time O(n) · Space O(1)
Linked List Cycle
Detect if a linked list has a cycle.
Answer: Detect a cycle in a linked list with O(1) space: move slow one node and fast two, and watch them meet inside the loop.
Visual solution and codeEasy · Time O(n) · Space O(1)
Palindrome Linked List
Check if a linked list is a palindrome.
Answer: Check whether a linked list is a palindrome in O(1) space: find the middle, reverse the second half in place, then compare both halves.
Visual solution and codeMedium · Time O(n) · Space O(1)
Remove Nth Node From End of List
Remove the nth node from the end of the list.
Answer: Remove the n-th node from the end in one pass: a dummy node, a fast pointer n + 1 ahead, and one unlink. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(1)
Reorder List
Reorder a linked list in a specific pattern.
Answer: Reorder a linked list to L0 → Ln → L1 → Ln-1 in O(1) space: find the middle, reverse the second half, and merge the two halves.
Visual solution and codeMedium · Time O(n) · Space O(1)
Swap Nodes in Pairs
Swap every two adjacent nodes.
Answer: Swap every two adjacent nodes by changing pointers, not values: a dummy node, then three next assignments per pair.
Visual solution and codeMedium · Time O(1) · Space O(capacity)
LRU Cache
Design a least recently used cache with O(1) get and put, using a hash map over a doubly linked list.
Answer: Implement an LRU cache with O(1) get and put: a hash map finds nodes, a doubly linked list keeps recency. Watch each move and eviction.
Visual solution and codeMedium · Time O(n) · Space O(1)
Find the Duplicate Number
Find the one repeated value in O(n) time and O(1) space by reading the array as a linked list and using Floyd's cycle detection.
Answer: Find the duplicate in O(n) time and O(1) space: treat nums[i] as a next pointer, and Floyd's tortoise and hare finds the cycle entrance. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Copy List with Random Pointer
Deep-copy a linked list whose nodes also point to a random node: copy every node first, then wire next and random through a map.
Answer: Deep-copy a linked list with random pointers: copy every node into a map, then wire next and random. Plus the O(1)-space interleaving trick. 6 languages.
Visual solution and codeHard · Time O(n) · Space O(1)
Reverse Nodes in k-Group
Reverse a linked list k nodes at a time in O(1) extra space: find each group of k, reverse it in place, and relink it to the rest.
Answer: Solve Reverse Nodes in k-Group iteratively: a dummy node, a k-step check, in-place reversal per group and careful relinking. Visualized, 6 languages.
Visual solution and codeEasy · Time O(log n) · Space O(1)
Happy Number
Decide whether repeatedly summing the squares of a number's digits reaches 1, using Floyd's slow and fast pointers to detect the loop.
Answer: Solve Happy Number with Floyd's cycle detection: the digit-square sequence is a linked list, so slow and fast pointers find 1 or a loop. Code in 6 languages.
Visual solution and code
Stack interview questions
How the stack pattern worksEasy · Time O(n) · Space O(n)
Valid Parentheses
Determine if the input string has valid matching brackets.
Answer: Check whether brackets are balanced and correctly nested: push every opener and match each closer against the top of the stack.
Visual solution and codeMedium · Time O(n · L) · Space O(n + L)
Decode String
Decode an encoded string with nested repetition rules.
Answer: Decode strings like 3[a2[c]] with one stack of chunks: pop to the "[", read the count, and push the repeated group back.
Visual solution and codeHard · Time O(n) · Space O(n)
Longest Valid Parentheses
Measure the longest stretch of a bracket string in which every parenthesis is matched.
Answer: Find the longest well-formed parentheses substring in O(n) with a stack of indices and a -1 base, and watch each valid run get measured.
Visual solution and codeMedium · Time O(n) · Space O(n)
Daily Temperatures
Find how many days you have to wait for a warmer temperature.
Answer: For each day, count the days until a warmer one: a stack of waiting days pops whenever a warmer day arrives. O(n), step by step.
Visual solution and codeHard · Time O(n) · Space O(n)
Largest Rectangle in Histogram
Find the area of the largest rectangle in the histogram.
Answer: Find the largest rectangle in a histogram in O(n): keep bars in increasing order, and measure each bar’s rectangle as it is popped.
Visual solution and codeHard · Time O(rows · cols) · Space O(cols)
Maximal Rectangle
Find the largest rectangle of 1s in a binary matrix by turning each row into a histogram of column heights and solving it with a monotonic stack.
Answer: Solve Maximal Rectangle by turning each row into a histogram of 1s and finding its largest rectangle with a monotonic stack. O(rows · cols), 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation (Postfix).
Answer: Evaluate postfix expressions with one stack: push numbers, and let each operator pop its two operands and push the result.
Visual solution and codeMedium · Time O(1) · Space O(n)
Min Stack
Design a stack that supports retrieving the minimum element in constant time.
Answer: Design a stack with push, pop, top and getMin in O(1): a second stack records the minimum at every height. Duplicates included.
Visual solution and codeMedium · Time O(n log n) · Space O(n)
Car Fleet
Count the car fleets that reach a target by sorting cars from the front back and keeping a stack of fleet arrival times.
Answer: Solve Car Fleet: sort cars from the front back, compute each arrival time, and push a new fleet only when a car is slower than the one ahead. 6 languages.
Visual solution and codeEasy · Time O(m + n) · Space O(n)
Next Greater Element I
Find the next greater element for each value of nums1 inside nums2 with one monotonic-stack pass over nums2 and a lookup map.
Answer: Solve Next Greater Element I in O(m + n): one pass over nums2 with a decreasing stack records each value's next greater element in a map. Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Next Greater Element II
Find the next greater element of every value in a circular array with a monotonic stack of indexes and two passes over the array.
Answer: Solve Next Greater Element II in O(n): loop i to 2n − 1, read nums[i % n], and pop a stack of waiting indexes. Visual walkthrough and code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Asteroid Collision
Simulate asteroid collisions with a stack of survivors: only a left-mover meeting a right-mover on top can collide, and the smaller one explodes.
Answer: Solve Asteroid Collision in O(n) with a stack of survivors: a left-mover pops smaller right-movers until it meets a bigger or equal one. Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Online Stock Span
Return each day's stock span in amortised O(1) with a monotonic stack of (price, span) pairs that folds smaller prices into today's span.
Answer: Solve Online Stock Span with a monotonic stack of (price, span) pairs: each call absorbs smaller prices' spans in amortised O(1). Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Remove K Digits
Remove k digits to make the smallest number with a greedy monotonic stack: drop a digit whenever a smaller one comes after it.
Answer: Solve Remove K Digits in O(n) with a greedy increasing stack: pop bigger digits while removals remain, trim the end, strip zeros. Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Simplify Path
Turn a Unix-style absolute path into its canonical form with a stack of directory names: skip empty parts and '.', pop on '..', push names.
Answer: Solve Simplify Path in O(n) with a stack: split on '/', ignore empty parts and '.', pop on '..', push names, then join. Visual walkthrough, code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Basic Calculator II
Evaluate an expression with + - * / and no parentheses in one pass: a stack of terms where * and / are applied to the top right away.
Answer: Solve Basic Calculator II in O(n): push +num or -num, apply * and / to the stack top at once, then sum the stack. Visual walkthrough and code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(n)
Remove All Adjacent Duplicates in String
Repeatedly remove adjacent equal letters in one pass with a stack: a letter equal to the top cancels it, otherwise it is kept.
Answer: Solve Remove All Adjacent Duplicates in String in O(n) with a stack: pop when a letter matches the top, push otherwise. Visual walkthrough, 6 languages.
Visual solution and code
Binary Search interview questions
How the binary search pattern worksEasy · Time O(log n) · Space O(1)
Binary Search
Efficiently find an element in a sorted array by repeatedly dividing the search interval in half.
Answer: Find a target in a sorted array in O(log n) by halving the search range on every comparison. Step through left, mid and right.
Visual solution and codeEasy · Time O(log n) · Space O(1)
Search Insert Position
Find where a target is, or where it would be inserted, in a sorted array with the lower-bound binary search template.
Answer: Solve Search Insert Position in O(log n): binary search for the first index whose value is at least the target, over the half-open range [0, n). 6 languages.
Visual solution and codeEasy · Time O(log n) · Space O(1)
First Bad Version
Find the first bad version with the fewest isBadVersion calls by binary searching for the first true in a false-then-true sequence.
Answer: Solve First Bad Version in O(log n) API calls: binary search for the first true, keep a bad mid, skip a good one, and avoid overflow. Code in 6 languages.
Visual solution and codeEasy · Time O(log x) · Space O(1)
Sqrt(x)
Compute the integer square root of x without a built-in by binary searching for the largest k whose square is at most x.
Answer: Solve Sqrt(x) in O(log x) with binary search: find the largest k with k² ≤ x, using 64-bit math so mid * mid never overflows. Visual walkthrough, 6 languages.
Visual solution and codeEasy · Time O(log num) · Space O(1)
Valid Perfect Square
Decide whether a number is a perfect square without sqrt by binary searching for a whole k whose square equals it.
Answer: Solve Valid Perfect Square in O(log n) without sqrt: binary search k in [1, num], compare k² to num, and use 64-bit math to avoid overflow. Code in 6 languages.
Visual solution and codeMedium · Time O(log n) · Space O(1)
Find Peak Element
Find any peak in an unsorted array in O(log n) by binary searching on the slope: go right while rising, left while falling.
Answer: Solve Find Peak Element in O(log n): compare nums[mid] with nums[mid + 1] and move toward the higher side. See why it works on an unsorted array. 6 languages.
Visual solution and codeMedium · Time O(n log M) · Space O(1)
Apple Harvest (Koko Variant)
Find the minimum eating speed to finish all piles within H hours.
Answer: Find the slowest eating speed that finishes every pile within h hours by binary searching the speed itself. Step through each try.
Visual solution and codeMedium · Time O(log n) · Space O(1)
Search in Rotated Sorted Array
Search for a target value in an array that has been rotated at an unknown pivot.
Answer: Search a rotated sorted array in O(log n): at every midpoint one half is sorted, so test whether the target lies inside it. Step through.
Visual solution and codeMedium · Time O(log n) · Space O(1)
Find Minimum in Rotated Sorted Array
Find the smallest element of a rotated sorted array of distinct values in O(log n) with binary search.
Answer: Find the minimum of a rotated sorted array in O(log n): compare mid with right, keep the half that holds the drop, and watch the range shrink step by step.
Visual solution and codeMedium · Time O(log(m · n)) · Space O(1)
Search a 2D Matrix
Search a row-sorted matrix in O(log(m·n)) with one binary search over the matrix read as a flat sorted array.
Answer: Search a 2D matrix in O(log(m·n)): treat it as one sorted array and map index i to row i / n, column i % n. Watch the search jump rows.
Visual solution and codeMedium · Time O(m + n) · Space O(1)
Search a 2D Matrix II
Search a matrix whose rows and columns are each sorted: start at the top-right corner and drop a whole row or column with every comparison.
Answer: Solve Search a 2D Matrix II in O(m + n): start top-right, move left when the cell is too big and down when too small. Visual walkthrough, 6 languages.
Visual solution and codeMedium · Time O(log n) · Space O(n)
Time Based Key-Value Store
Design a key-value store that returns the value at any past time: append on set, and binary search the timestamps on get.
Answer: Solve Time Based Key-Value Store: append (timestamp, value) pairs on set, then binary search for the last timestamp ≤ t on get. Visualized, in 6 languages.
Visual solution and codeHard · Time O(log min(m, n)) · Space O(1)
Median of Two Sorted Arrays
Find the median of two sorted arrays in O(log min(m, n)) by binary searching where to cut the shorter array.
Answer: Solve Median of Two Sorted Arrays in O(log min(m, n)): binary search a cut in the shorter array so the left parts hold half the numbers. 6 languages.
Visual solution and code
Heap / Priority Queue interview questions
How the heap / priority queue pattern worksMedium · Time O(n log k) · Space O(k)
Kth Largest Element in an Array
Find the kth largest element in an unsorted array.
Answer: Find the kth largest element with a min-heap that never holds more than k values: O(n log k) time, O(k) space. Step through it.
Visual solution and codeMedium · Time O(n log k) · Space O(k)
K Closest Points to Origin
Find the K closest points to the origin (0, 0).
Answer: Find the k points nearest the origin with a max-heap that evicts the farthest point once it holds more than k. O(n log k).
Visual solution and codeMedium · Time O(n) · Space O(k)
Find K Closest Elements
Find k closest integers to a given value x.
Answer: Find the k values closest to x in a sorted array: shrink a window from its farther end in O(n), keeping the smaller value on a tie.
Visual solution and codeHard · Time O(N log k) · Space O(k)
Merge K Sorted Lists
Merge k sorted linked lists into one sorted linked list.
Answer: Merge k sorted linked lists by keeping each list's front node in a min-heap: pop the smallest, link it, push its next. O(N log k).
Visual solution and codeMedium · Time O(k log min(n, k)) · Space O(min(n, k))
Kth Smallest Element in a Sorted Matrix
Find the kth smallest value in a matrix whose rows and columns are sorted by merging the rows with a min-heap: pop k - 1 times, then read the top.
Answer: Solve Kth Smallest Element in a Sorted Matrix with a min-heap: seed it with each row's first cell, pop k - 1 times pushing right neighbours. Binary search too.
Visual solution and codeHard · Time O(log n) · Space O(n)
Find Median from Data Stream
Keep a running median of a stream with two heaps: a max-heap for the smaller half and a min-heap for the larger half.
Answer: Maintain a running median with two heaps: a max-heap of the lower half and a min-heap of the upper half, balanced on every insert, step by step.
Visual solution and codeEasy · Time O(n log n) · Space O(n)
Last Stone Weight
Smash the two heaviest stones until at most one is left, using a max-heap to find the heaviest pair each round.
Answer: Solve Last Stone Weight with a max-heap: pop the two heaviest stones, push back their difference, and repeat. Python's min-heap trick and 6 languages.
Visual solution and codeMedium · Time O(E log E) · Space O(V + E)
Network Delay Time
Find how long a signal takes to reach every node with Dijkstra's algorithm: a min-heap always settles the closest node next.
Answer: Solve Network Delay Time with Dijkstra and a min-heap: pop the closest node, relax its edges, skip stale entries. Answer = max distance or -1. 6 languages.
Visual solution and codeMedium · Time O(n² log n) · Space O(n²)
Min Cost to Connect All Points
Connect every point at the least total Manhattan distance with Prim's algorithm: a min-heap always attaches the cheapest new point to the tree.
Answer: Solve Min Cost to Connect All Points with Prim's algorithm and a min-heap: grow one tree, always add the cheapest new point. Dry run and code in 6 languages.
Visual solution and codeHard · Time O(n² log n) · Space O(n²)
Swim in Rising Water
Find the earliest time you can swim from the top-left to the bottom-right of an elevation grid with Dijkstra, where a path costs its highest cell.
Answer: Solve Swim in Rising Water with a min-heap: a path costs its highest elevation, so always expand the cell reachable at the lowest time. Dry run, 6 languages.
Visual solution and code
Depth-First Search interview questions
How the depth-first search pattern worksEasy · Time O(n) · Space O(h)
Return Values in DFS
Understanding how to bubble up information from the bottom of the tree.
Answer: Compute a tree’s height two ways: children returning their heights up, or parents passing depth down. Compare bottom-up and top-down DFS.
Visual solution and codeEasy · Time O(n) · Space O(h)
Invert Binary Tree
Mirror a binary tree by swapping every node's left and right children with a depth-first traversal.
Answer: Invert a binary tree with one recursive DFS: swap each node's left and right children, then recurse — and watch the subtrees trade sides step by step.
Visual solution and codeEasy · Time O(n) · Space O(h)
Maximum Depth of Binary Tree
Find the maximum depth (height) of a binary tree.
Answer: Solve LeetCode 104 with bottom-up DFS: an empty node returns 0 and every node returns max(left, right) + 1. O(n) time, step by step.
Visual solution and codeEasy · Time O(n) · Space O(h)
Same Tree
Check whether two binary trees have the same shape and the same values by walking both in lockstep with DFS.
Answer: Solve Same Tree with one recursive DFS over both trees at once: match empty nodes, compare values, and stop at the first difference, step by step.
Visual solution and codeEasy · Time O(n) · Space O(h)
Balanced Binary Tree
Check whether every node's two subtrees differ in height by at most one, in one bottom-up DFS that returns -1 for unbalanced.
Answer: Check if a binary tree is height-balanced in one pass: return each subtree's height, or -1 as soon as two heights differ by more than 1.
Visual solution and codeEasy · Time O(m · n) · Space O(h)
Subtree of Another Tree
Check whether one binary tree appears as an exact subtree of another by running the Same Tree check from every node.
Answer: Solve Subtree of Another Tree: try every node of root as a start, run the Same Tree check against subRoot, and watch each comparison step by step.
Visual solution and codeEasy · Time O(n) · Space O(h)
Path Sum
Determine if the tree has a root-to-leaf path summing to a target.
Answer: Solve LeetCode 112 by subtracting each node’s value on the way down and checking for 0 at a leaf. It stops as soon as a path is found.
Visual solution and codeMedium · Time O(n) · Space O(h)
Passing Values Down (State)
Learn how to pass information (state) from parents to children in DFS.
Answer: Solve LeetCode 1448 by passing the largest value on the path down as an argument: a node is good if nothing above it is larger. O(n).
Visual solution and codeMedium · Time O(n) · Space O(h)
Validate Binary Search Tree
Determine if a binary tree is a valid Binary Search Tree (BST).
Answer: Solve LeetCode 98 by passing an open (low, high) range down the tree, so a violation deep inside a subtree is caught. O(n) time.
Visual solution and codeMedium · Time O(n) · Space O(h)
Kth Smallest Element in a BST
Find the k-th smallest value in a binary search tree by walking it in order — ascending — and stopping at the k-th node.
Answer: Solve Kth Smallest Element in a BST with an iterative inorder walk: push left, pop and count, and return the k-th node popped.
Visual solution and codeMedium · Time O(n) · Space O(n)
Construct Binary Tree from Preorder and Inorder Traversal
Rebuild a binary tree from its preorder and inorder traversals: preorder names each root, and the root's inorder position splits its left and right subtrees.
Answer: Construct a binary tree from preorder and inorder: read roots from preorder, split each range at the root's inorder index, in O(n).
Visual solution and codeHard · Time O(n) · Space O(n)
Serialize and Deserialize Binary Tree
Turn a binary tree into a string and back with a preorder DFS that writes a marker for every empty child.
Answer: Serialize a binary tree with preorder DFS and '#' for empty children, then rebuild it token by token. Watch both directions step by step.
Visual solution and codeEasy · Time O(n) · Space O(h)
Binary Tree Tilt
Add up the tilt of every node, where a node's tilt is how far apart the value sums of its left and right subtrees are: |left sum − right sum|.
Answer: Solve LeetCode 563 with postorder DFS: return each subtree’s sum to its parent and add |left − right| to a running total. O(n).
Visual solution and codeEasy · Time O(n) · Space O(h)
Diameter of Binary Tree
Measure the longest path, counted in edges, between any two nodes of a binary tree. The path does not have to pass through the root.
Answer: Solve LeetCode 543: return heights up the tree and record left + right at every node, since the longest path need not pass through the root.
Visual solution and codeMedium · Time O(n) · Space O(h)
Lowest Common Ancestor of a Binary Tree
Find the deepest node that has both p and q as descendants with one depth-first pass.
Answer: Find the lowest common ancestor of two nodes in one DFS: each subtree reports p, q or null, and the first node hearing from both sides is the answer.
Visual solution and codeMedium · Time O(n²) · Space O(n)
Path Sum II
Find all root-to-leaf paths where each path's sum equals the targetSum.
Answer: Solve LeetCode 113: push each node onto the path, save a copy at a matching leaf, and pop on the way back. Step through the backtracking.
Visual solution and codeMedium · Time O(n) · Space O(h)
Count Good Nodes in Binary Tree
Count the nodes with no bigger value above them by passing the maximum seen so far down a DFS: one comparison per node.
Answer: Solve Count Good Nodes in Binary Tree by passing the path maximum down a DFS: a node is good if its value is at least that maximum. Dry run, 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(h)
Longest Univalue Path
Measure the longest path, in edges, along which every node holds one and the same value.
Answer: Solve LeetCode 687: each node returns its longest same-value arrow, reset to 0 when a child’s value differs, while best tracks paths that bend.
Visual solution and codeMedium · Time O(V + E) · Space O(V + E)
Graph Representation: Adjacency List
How to build and store graphs efficiently.
Answer: Turn an edge list into an adjacency list with one list per node, then answer LeetCode 1971 with a stack-based DFS from source.
Visual solution and codeMedium · Time O(V + E) · Space O(V)
Clone Graph
Deep copy a connected undirected graph.
Answer: Deep copy a connected undirected graph (LeetCode 133) with DFS and a map from each original node to its copy, so cycles never recurse forever.
Visual solution and codeMedium · Time O(V + E) · Space O(V + E)
Graph Valid Tree
Determine if a set of edges forms a valid tree.
Answer: Check whether n nodes and a list of edges form a tree (LeetCode 261): DFS with a parent finds any cycle, then every node must be visited.
Visual solution and codeEasy · Time O(m·n) · Space O(m·n)
Flood Fill
Implement the 'Paint Bucket' tool found in image editors.
Answer: Solve LeetCode 733 by painting a pixel and recursing down, up, right and left into pixels of the original colour. Every call shown.
Visual solution and codeMedium · Time O(m·n) · Space O(m·n)
Number of Islands
Count the number of connected groups of 1s in a grid.
Answer: Solve LeetCode 200 by scanning the grid and sinking each new island with DFS, so every piece of land is counted exactly once.
Visual solution and codeMedium · Time O(m·n) · Space O(m·n)
Surrounded Regions
Capture regions that are fully surrounded by 'X'.
Answer: Solve LeetCode 130 by marking every 'O' the border can reach, then capturing the rest in one pass. Both passes shown step by step.
Visual solution and codeMedium · Time O(m·n) · Space O(m·n)
Pacific Atlantic Water Flow
Find cells that can flow to both oceans.
Answer: Solve LeetCode 417 by climbing uphill from each ocean's edges and keeping the cells both oceans reach. Both DFS passes shown.
Visual solution and codeHard · Time O(m · n) · Space O(m · n)
Longest Increasing Path in a Matrix
Find the longest strictly increasing path in a grid with DFS and memoisation: each cell's answer is 1 plus its best bigger neighbour, computed once.
Answer: Solve Longest Increasing Path in a Matrix with DFS and memoisation: dfs(r, c) = 1 + best bigger neighbour, cached so each cell is solved once. 6 languages.
Visual solution and code
Breadth-First Search interview questions
How the breadth-first search pattern worksMedium · Time O(n) · Space O(n)
Level Order Sum / Averages
Sum every level with BFS and return the smallest level with the largest sum.
Answer: Solve LeetCode 1161 by summing each level with BFS and keeping the smallest level with the largest sum. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(w)
Binary Tree Level Order Traversal
Return a binary tree's values level by level with BFS: read the queue size to know how many nodes form the current level, then enqueue their children.
Answer: Solve Binary Tree Level Order Traversal with a BFS queue: read the queue size to take exactly one level, then enqueue its children. Code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(w)
Symmetric Tree
Check whether a binary tree is a mirror of itself by comparing mirror pairs through a queue: outer children with outer, inner with inner.
Answer: Solve Symmetric Tree by comparing mirror pairs: match values, then queue outer (left.left, right.right) and inner (left.right, right.left) pairs. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Binary Tree Rightmost Node (Right Side View)
List the node visible on each level when the tree is viewed from the right, top level first.
Answer: Solve LeetCode 199 with BFS: the last node dequeued on each level is the one you see from the right.
Visual solution and codeMedium · Time O(n) · Space O(n)
Zigzag Level Order Traversal
Traverse levels in alternating order (left-to-right, then right-to-left).
Answer: Solve LeetCode 103 with ordinary level-order BFS, reversing the collected list on every odd level. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(n)
Maximum Width of Binary Tree
Find the widest level of the tree (including nulls between end nodes).
Answer: Solve LeetCode 662 by giving each node its slot index, 2i and 2i + 1, so null gaps count toward the width.
Visual solution and codeEasy · Time O(V + E) · Space O(V + E)
BFS in Graphs
Walk a graph outwards from one node in layers of equal distance, with a queue and a visited stamp.
Answer: Run BFS on an undirected graph to decide whether a path exists, and see why its layers give the shortest distance. LeetCode 1971.
Visual solution and codeMedium · Time O(max(|x|, |y|)²) · Space O(max(|x|, |y|)²)
Minimum Knight Moves
Fold the board into one quadrant and BFS across a pruned window to the fewest knight moves.
Answer: Solve LeetCode 1197 by folding the target into one quadrant and running BFS across a pruned window.
Visual solution and codeMedium · Time O(R × C) · Space O(R × C)
Rotting Oranges
Spread rot from every source at once, one queue pass per minute, and decide with the fresh count.
Answer: Solve LeetCode 994 with a BFS that starts from every rotten orange at once, counts a minute per layer, and returns -1 when a fresh one is cut off.
Visual solution and codeMedium · Time O(R × C) · Space O(R × C)
01 Matrix
Flood outwards from every zero at once so each cell takes the distance of the first one to reach it.
Answer: Solve LeetCode 542 by queueing every zero at once and flooding distances outwards, so each cell takes the first distance offered.
Visual solution and codeHard · Time O(S) · Space O(S)
Bus Routes
Find the fewest buses between two stops with a BFS whose levels count rides, not stops.
Answer: Solve LeetCode 815 by indexing stop to buses and running a BFS whose level counter is the number of rides.
Visual solution and codeHard · Time O(N · L · 26) · Space O(N · L)
Word Ladder
Find the shortest sequence of one-letter changes from one word to another with BFS, visiting each word once, level by level.
Answer: Solve Word Ladder with BFS: words are nodes, one-letter changes are edges, and the first time you reach endWord is the shortest ladder. Visualized, 6 languages.
Visual solution and codeMedium · Time O(k · E) · Space O(n)
Cheapest Flights Within K Stops
Find the cheapest route with at most k stops using Bellman-Ford limited to k + 1 rounds: each round lets every route take one more flight.
Answer: Solve Cheapest Flights Within K Stops with k + 1 Bellman-Ford rounds: relax every flight from last round's prices so routes grow one flight at a time.
Visual solution and code
Backtracking interview questions
How the backtracking pattern worksMedium · Time O(n × 2ⁿ) · Space O(n) depth, O(n × 2ⁿ) output
Solution Space Trees
See the whole search space as a tree: one decision per level, and 2^n leaves that are the answers.
Answer: Every backtracking problem walks a tree of candidates. See it on LeetCode 78: one decision per level, 2^n leaves, and where pruning would cut.
Visual solution and codeMedium · Time O(n × 2ⁿ) · Space O(n) depth, O(n × 2ⁿ) output
Subsets (Power Set)
Generate every subset of distinct numbers by deciding each one in turn: leave it out, take it, undo.
Answer: Generate the power set with backtracking: decide each number in turn, record at depth n, and step through the call tree.
Visual solution and codeMedium · Time O(n · n!) · Space O(n)
Permutations
Generate every permutation of distinct numbers with backtracking: choose an unused number, recurse, then un-choose it so the next branch starts clean.
Answer: Solve Permutations with backtracking: mark a number used, append, recurse, then pop and unmark. Step through the choose and un-choose tree. Code in 6 languages.
Visual solution and codeMedium · Time O(n · n!) · Space O(n)
Permutations II
Generate all unique permutations of numbers that may repeat: sort, then skip a value when its equal left neighbour is not yet in the path.
Answer: Solve Permutations II: sort, then skip nums[i] when it equals nums[i − 1] and that twin is unused, so no ordering repeats. Visual walkthrough, 6 languages.
Visual solution and codeMedium · Time O(k · C(n, k)) · Space O(k)
Combinations
Generate every way to choose k numbers from 1 to n with backtracking that only moves forward, so each set is built exactly once.
Answer: Solve Combinations with backtracking: choose numbers in increasing order from a start index, record paths of length k, then backtrack. Code in 6 languages.
Visual solution and codeMedium · Time O(n · 2^k) · Space O(n)
Letter Case Permutation
Generate every string from changing each letter's case with backtracking: each letter branches into lower and upper case, digits pass through.
Answer: Solve Letter Case Permutation with backtracking: branch on lower and upper case for each letter, keep digits, record full strings. 2^k results, 6 languages.
Visual solution and codeHard · Time O(n!) · Space O(n)
N-Queens
Place n queens on an n × n board so none attack each other with backtracking: one queen per row, and sets for columns and both diagonals.
Answer: Solve N-Queens with backtracking: one queen per row, O(1) conflict checks with column, r − c and r + c sets. Visual board walkthrough, 6 languages.
Visual solution and codeMedium · Time O(n · 2^n) · Space O(n)
Subsets II
List every subset of an array that may contain duplicates, each exactly once: sort, then skip a repeated value at the same level.
Answer: Solve Subsets II with backtracking: sort, record every path, and skip a value already tried at the same level so no subset repeats. Visualized, 6 languages.
Visual solution and codeMedium · Time O(n^(T/m + 1)) · Space O(T/m) depth
Combination Sum
Find every combination that sums to a target, reusing numbers freely, and prune with a sorted break.
Answer: Find every combination that sums to a target with reuse allowed. Sort, recurse on the same index, and break early — step through it.
Visual solution and codeMedium · Time O(n · 2^n) · Space O(n)
Combination Sum II
Find every unique combination that adds up to a target, using each number once: sort, skip repeats on the same level, and break early.
Answer: Solve Combination Sum II with backtracking: sort, use each number once, and skip a value already tried at the same level so no combination repeats. 6 languages.
Visual solution and codeMedium · Time O(4ⁿ / √n) · Space O(n) depth, O(4ⁿ / √n) output
Generate Parentheses
Build only well-formed strings of n pairs, using two guards instead of generating and filtering.
Answer: Generate every well-formed string of n pairs with backtracking: open while under n, close while under open. Step through the call tree.
Visual solution and codeMedium · Time O(m × n × 3ᴸ) · Space O(L) stack
Word Search
Find whether a word can be traced through adjacent cells of a letter grid, marking each cell on the way down and restoring it on the way back.
Answer: Solve Word Search with backtracking: mark a cell, try its four neighbours, write the letter back. Step through the board.
Visual solution and codeMedium · Time O(4^n · n) · Space O(n)
Letter Combinations of a Phone Number
List every letter string a phone number's digits can spell with a backtracking DFS: choose a letter, recurse, undo.
Answer: Solve Letter Combinations of a Phone Number with backtracking: one letter per digit, choose, recurse, undo. Watch the keys cycle like an odometer. 6 languages.
Visual solution and codeMedium · Time O(n · 2^n) · Space O(n)
Palindrome Partitioning
List every way to cut a string into palindromes with backtracking: cut a palindrome off the front, partition the rest, undo.
Answer: Solve Palindrome Partitioning with backtracking: try every palindrome prefix, partition the rest, then undo. Step through the cuts, with code in 6 languages.
Visual solution and code
Graphs (Topological Sort) interview questions
How the graphs (topological sort) pattern worksMedium · Time O(V + E) · Space O(V + E)
Course Schedule
Decide whether every course can be finished, by counting how many Kahn's algorithm can take before a prerequisite cycle stops it.
Answer: Solve Course Schedule with Kahn's algorithm: count prerequisites, take the courses that reach zero, and spot the cycle. Step through it.
Visual solution and codeMedium · Time O(V + E) · Space O(V + E)
Course Schedule II
Return an order in which every course can be taken — Kahn's algorithm writes it out, and a prerequisite cycle empties it.
Answer: Return a valid order for Course Schedule II with Kahn's algorithm, and an empty array when a prerequisite cycle makes it impossible.
Visual solution and codeHard · Time O(C) · Space O(U + E)
Alien Dictionary
Recover the letter order of an alien alphabet from a sorted word list: compare neighbouring words for facts, then topologically sort the letters.
Answer: Solve Alien Dictionary: compare adjacent words for letter-order facts, then run Kahn's algorithm on the letters, detecting cycles.
Visual solution and code
Dynamic Programming interview questions
How the dynamic programming pattern worksEasy · Time O(n) · Space O(1)
Fibonacci Number
Compute the nth Fibonacci number bottom-up in O(n) time and O(1) space by keeping only the last two values, instead of exponential recursion.
Answer: Solve Fibonacci Number in O(n) time and O(1) space: see why plain recursion is exponential, then build up with two variables. Visual walkthrough, 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(1)
Counting Bits
Given an integer n, return an array of the number of 1's for each number from 0 to n.
Answer: Count the 1 bits of every number up to n in O(n) using dp[i] = dp[i >> 1] + (i & 1). Step through the shift.
Visual solution and codeEasy · Time O(n²) · Space O(n²)
Pascal's Triangle
Generate the first numRows rows of Pascal's triangle bottom-up: every row starts and ends with 1, and each inside value is the sum of the two above.
Answer: Solve Pascal's Triangle with simple DP: each row starts and ends with 1, and row[j] = prev[j - 1] + prev[j]. Visual walkthrough and code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(n)
Min Cost Climbing Stairs
Find the cheapest way to the top of a staircase where each step has a cost, with a one-line DP over the two ways into every step.
Answer: Solve Min Cost Climbing Stairs with DP: dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]), and the top is one past the last stair. Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
House Robber
Maximise the money robbed from a row of houses without robbing two adjacent ones, with a one-dimensional DP.
Answer: Solve House Robber with one recurrence, dp[i] = max(dp[i-1], dp[i-2] + nums[i-1]), and watch the table fill and the robbed houses traced back.
Visual solution and codeMedium · Time O(n) · Space O(1)
House Robber II
Rob houses arranged in a circle, where the first and last are neighbours, by running House Robber twice on two straight streets.
Answer: Solve House Robber II: the first and last houses are neighbours, so run House Robber on houses 0..n-2 and 1..n-1 and take the larger.
Visual solution and codeMedium · Time O(n) · Space O(h)
House Robber III
Rob a binary tree of houses without robbing two linked ones: a post-order DFS returns, for every house, the best total if you rob it and if you skip it.
Answer: Solve House Robber III with tree DP: each node returns (rob, skip). rob = val + children skipped, skip = best of each child. Dry run and code in 6 languages.
Visual solution and codeMedium · Time O(amount · k) · Space O(amount)
Coin Change
Find the fewest coins that make up an amount, or -1 if it cannot be made, with a bottom-up DP over amounts.
Answer: Find the fewest coins for an amount with dp[a] = min(dp[a - coin] + 1), see why greedy fails, and watch the table fill and the answer trace back.
Visual solution and codeMedium · Time O(amount · coins) · Space O(amount)
Coin Change II
Count the combinations of coins that make an amount with a 1D DP, looping over coins outside so each combination is counted once.
Answer: Solve Coin Change II with a 1D DP: dp[a] += dp[a − coin], coins in the outer loop so 1+2 and 2+1 count once. Visualized, with code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Maximum Product Subarray
Find the largest product of a contiguous subarray in one pass by tracking both the largest and the smallest running product.
Answer: Solve Maximum Product Subarray in O(n): track the largest and smallest product ending here, swap them on a negative, and watch each step.
Visual solution and codeMedium · Time O(target · n) · Space O(target)
Combination Sum IV
Count the ordered sequences of numbers that add up to a target with a one-dimensional DP over every total.
Answer: Solve Combination Sum IV with a 1D DP: dp[t] adds dp[t - num] for every num that can come last. Watch the table fill step by step.
Visual solution and codeMedium · Time O(n · sum) · Space O(sum)
Partition Equal Subset Sum
Decide whether an array splits into two halves with equal sums, using a 0/1 knapsack row of reachable sums filled right to left.
Answer: Solve Partition Equal Subset Sum with a 1D 0/1 knapsack: track which sums are reachable and sweep right to left so each number is used once. 6 languages.
Visual solution and codeMedium · Time O(n · sum) · Space O(sum)
Target Sum
Count the ways to put + and − in front of each number to reach a target, by turning it into counting subsets with sum (total + target) / 2.
Answer: Solve Target Sum by turning signs into a subset-sum count: the plus group must add up to (total + target) / 2. 1D 0/1 knapsack, code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Decode Ways
Determine the total number of ways to decode a string of digits into letters (A-Z).
Answer: Count decodings of a digit string with dp[i] = dp[i-1] + dp[i-2] under two rules, and see why a zero is never a letter.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Maximal Square
In an m x n grid of 0s and 1s, find the biggest square made entirely of 1s and return how many cells it covers.
Answer: Find the largest all-ones square with dp[i][j] = min(top, left, diagonal) + 1, and see why it is a minimum and why the answer is an area.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Unique Paths
Count the distinct routes a robot can take from the top-left cell of an m x n grid to the bottom-right cell when every step goes one cell down or one cell right.
Answer: Count a robot’s right-and-down paths across an m by n grid with dp[i][j] = dp[i-1][j] + dp[i][j-1]. Step through the fill.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Unique Paths II
Count right-and-down paths through a grid with obstacles using DP: an obstacle holds 0 paths, every open cell adds the paths from above and from the left.
Answer: Solve Unique Paths II with grid DP: obstacles hold 0 paths, open cells add the counts from above and from the left. Visual walkthrough, code in 6 languages.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Minimum Path Sum
Find the cheapest top-left to bottom-right path in a grid moving only right or down, with a DP table where each cell takes the cheaper of above and left.
Answer: Solve Minimum Path Sum with grid DP: each cell costs its value plus the cheaper of above and left; edges have one way in. Code in 6 languages.
Visual solution and codeMedium · Time O(n²) · Space O(n)
Triangle
Find the minimum path sum from the top of a triangle to the bottom with bottom-up DP: each cell adds the cheaper of its two children.
Answer: Solve Triangle bottom-up: start from the last row and set each cell to its value plus the cheaper child below. One array, O(n) space. Dry run, 6 languages.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Longest Common Subsequence
Find the length of the longest common subsequence of two strings with a 2D DP table: extend the diagonal on a match, otherwise take the better of up and left.
Answer: Solve Longest Common Subsequence with a 2D DP table: match gives diagonal + 1, otherwise max of up and left. See the table fill and the LCS rebuild.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Edit Distance
Find the minimum number of inserts, deletes and replaces to turn one word into another with a 2D DP table, and rebuild the edits from it.
Answer: Solve Edit Distance with a 2D DP table: a match is free, otherwise 1 + min(replace, delete, insert). Watch the table fill and the edits rebuild. 6 languages.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Interleaving String
Decide whether s3 is s1 and s2 woven together with a 2D DP table: each cell asks whether two prefixes can build a prefix of s3.
Answer: Solve Interleaving String with a 2D DP table: dp[i][j] is true when s1[:i] and s2[:j] build s3[:i+j]. Why greedy fails, a dry run, and code in 6 languages.
Visual solution and codeHard · Time O(m · n) · Space O(m · n)
Distinct Subsequences
Count the ways t appears as a subsequence of s with a 2D DP table: every letter of s is skipped, or used when it matches the next letter of t.
Answer: Solve Distinct Subsequences with DP: dp[i][j] = dp[i-1][j] + dp[i-1][j-1] when the letters match. Why column 0 is 1, a dry run, and code in 6 languages.
Visual solution and codeHard · Time O(m · n) · Space O(m · n)
Regular Expression Matching
Match a string against a pattern with '.' and '*' using a 2D DP table: a star pair matches zero copies or eats one more letter.
Answer: Solve Regular Expression Matching with a 2D DP table: '.' matches any letter, 'x*' matches zero copies or one more. Dry run, edge cases, 6 languages.
Visual solution and codeHard · Time O(m · n) · Space O(m · n)
Wildcard Matching
Match a string against a pattern with '?' and '*' using a 2D DP table: a star matches the empty sequence or eats one more letter.
Answer: Solve Wildcard Matching with a 2D DP table: '?' matches one letter, '*' matches the empty sequence or one more letter. Dry run, edge cases, 6 languages.
Visual solution and codeHard · Time O(n³) · Space O(n²)
Burst Balloons
Maximise the coins from bursting every balloon with interval DP: guess which balloon in a range bursts last, so its neighbours are the range's walls.
Answer: Solve Burst Balloons with interval DP: pick the last balloon k in (l, r), earn vals[l]·vals[k]·vals[r] plus both sides. Why last, not first, plus 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Best Time to Buy and Sell Stock with Cooldown
Maximise stock profit when every sale is followed by a one-day cooldown, with three DP states per day: hold, sold and rest.
Answer: Solve Best Time to Buy and Sell Stock with Cooldown with three states: hold, sold, rest. Each day's transitions, a dry run and O(1)-space code in 6 languages.
Visual solution and codeMedium · Time O(n²) · Space O(n)
Longest Increasing Subsequence
Find how long the longest strictly increasing subsequence of the integer array nums is; its elements do not have to sit next to each other.
Answer: Solve LIS with dp[i] = the longest run ending at i, and see why the answer is max(dp) and not the last cell.
Visual solution and codeMedium · Time O(n² · k) · Space O(n + d)
Word Break
Decide whether the string s can be cut, end to end, into pieces that each appear in a given list of dictionary words, where any word may be used more than once.
Answer: Decide if a string splits into dictionary words with dp over prefixes: dp[i] is true when some reachable j leaves a word behind.
Visual solution and codeHard · Time O(n log n) · Space O(n)
Maximum Profit in Job Scheduling
Given n jobs where every job has a start time, end time, and profit, return the maximum profit without overlapping jobs.
Answer: Maximise profit over non-overlapping jobs: sort by end time, binary search the last compatible job, take or leave each one.
Visual solution and code
Greedy Algorithms interview questions
How the greedy algorithms pattern worksEasy · Time O(n) · Space O(1)
Best Time to Buy and Sell Stock
Find the best profit from one buy followed by one later sell.
Answer: Track the cheapest price so far and the best sale so far in one pass: O(n) time, O(1) space. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(1)
Best Time to Buy and Sell Stock II
Maximise profit with unlimited stock transactions greedily: add every day-to-day price rise, since any climb is the sum of its daily gains.
Answer: Solve Best Time to Buy and Sell Stock II in O(n) greedily: add every positive day-to-day difference. See why it equals the best set of trades. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Gas Station
Find the starting gas station to complete the circuit.
Answer: Find the station that completes the circuit in one pass with two running tanks: O(n) time, O(1) space. Step through it.
Visual solution and codeMedium · Time O(n) · Space O(1)
Jump Game
Determine if you can reach the last index.
Answer: Decide if you can reach the last index by tracking the furthest reachable index in one pass. See why a single number is enough.
Visual solution and codeMedium · Time O(n) · Space O(1)
Jump Game II
Find the fewest jumps to the last index in one greedy pass: each jump covers a window, and the next window ends at the farthest reach.
Answer: Solve Jump Game II in O(n) time and O(1) space: treat each jump as a BFS window and jump when i reaches the window's end. Step through it in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Task Scheduler
Find the fewest CPU intervals to run every task with n idle gaps between repeats, from a frame set by the most frequent task.
Answer: Solve Task Scheduler in O(n): the most frequent task builds a frame of (maxCount − 1) · (n + 1) + ties slots, and the rest fill its gaps. 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Partition Labels
Split a string into as many parts as possible so each letter appears in only one part, by cutting when every letter seen has ended.
Answer: Solve Partition Labels in O(n): record each letter's last index, stretch the part's end as you scan, and cut when i reaches it. Visualized, 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Valid Parenthesis String
Check a string of '(', ')' and '*' in one greedy pass by tracking the lowest and highest number of open brackets any choice could give.
Answer: Solve Valid Parenthesis String in O(n) time and O(1) space: track the range [lo, hi] of possible open brackets, since each * can be (, ) or empty. 6 languages.
Visual solution and codeMedium · Time O(n log n) · Space O(n)
Hand of Straights
Decide whether cards can be split into groups of consecutive values: the smallest card left must start a group, so build groups greedily from it.
Answer: Solve Hand of Straights greedily: the smallest card left must begin a group, so take groupSize consecutive values from it using a sorted count map. 6 languages.
Visual solution and codeMedium · Time O(1) · Space O(1)
Integer to Roman
Convert an integer to a Roman numeral greedily: walk a 13-entry value table, subtraction pairs included, and write each symbol while it fits.
Answer: Solve Integer to Roman greedily: walk 13 values from 1000 down to 1, including CM, CD, XC, XL, IX and IV, writing each while it fits. Code in 6 languages.
Visual solution and code
Trie interview questions
How the trie pattern worksMedium · Time O(L) · Space O(N·L)
Implement Trie (Prefix Tree)
Design a data structure that supports insert, search, and startsWith.
Answer: Implement insert, search and startsWith for a trie. Step through node creation and path walks, and see why search checks the end-of-word flag.
Visual solution and codeMedium · Time O(N) · Space O(total letters)
Design Add and Search Words Data Structure
Store words in a trie and search them with '.' wildcards using a DFS that branches at every dot.
Answer: Solve Design Add and Search Words with a trie: addWord inserts, search runs a DFS that tries every child at a '.' and backs up.
Visual solution and codeHard · Time O(m · n · 3^L) · Space O(total letters)
Word Search II
Find every word from a list on a letter grid with one backtracking DFS per cell, guided by a trie of the words.
Answer: Solve Word Search II with a trie: one DFS from each cell follows only prefixes some word has, records words as it reaches them.
Visual solution and code
Prefix Sum interview questions
How the prefix sum pattern worksMedium · Time O(N + Q) · Space O(N + Q)
Count Vowels in Ranges
Answer range queries counting the words that start and end with a vowel — one pass to build a prefix count, then one subtraction per query.
Answer: Mark each word that starts and ends with a vowel, build a prefix count, and answer every range query with one subtraction.
Visual solution and codeMedium · Time O(n) · Space O(1)
Product of Array Except Self
Return the product of every element except the current one, without division, using prefix and suffix products.
Answer: Solve Product of Array Except Self without division: a left pass of prefix products and a right pass of suffix products in one output array.
Visual solution and codeMedium · Time O(N) · Space O(N)
Subarray Sum Equals K
Count the contiguous subarrays whose sum equals k in one pass, using a running prefix sum and a hash map of the sums seen so far.
Answer: Count subarrays that sum to k in one pass: keep a running sum and look up how many earlier prefix sums equal sum - k. Step through it.
Visual solution and code
Matrices interview questions
How the matrices pattern worksMedium · Time O(m·n) · Space O(1)
Spiral Matrix
Return all elements of the matrix in spiral order.
Answer: Solve Spiral Matrix by shrinking four boundaries layer by layer. Step through every pass of the walk, with the.
Visual solution and codeMedium · Time O(n²) · Space O(1)
Rotate Image
Rotate the matrix by 90 degrees clockwise in-place.
Answer: Rotate an n × n matrix 90° clockwise in place: transpose across the diagonal, then reverse every row. Step through both phases.
Visual solution and codeMedium · Time O(m·n) · Space O(1)
Set Matrix Zeroes
Spread every 0 in a matrix across its full row and column, in place.
Answer: Zero every row and column that holds a zero, in place, using row 0 and column 0 as markers. Step through each pass with the.
Visual solution and code
Bit Manipulation interview questions
How the bit manipulation pattern worksEasy · Time O(32) · Space O(1)
Number of 1 Bits
Count the set bits of an integer by clearing the lowest one with n & (n - 1) until nothing is left.
Answer: Count set bits with Brian Kernighan's trick: n & (n - 1) clears the lowest 1, so the loop runs once per set bit. Watch each bit clear.
Visual solution and codeEasy · Time O(n) · Space O(1)
Single Number
Find the one number that appears once when every other appears twice, in O(n) time and O(1) space with XOR.
Answer: Solve Single Number in O(n) time and O(1) space: XOR every value so each pair cancels, leaving the one that appears once.
Visual solution and codeEasy · Time O(n) · Space O(1)
Missing Number
Find the one number missing from 0..n in O(n) time and O(1) space by XORing every index and value so the pairs cancel.
Answer: Solve Missing Number in O(n) time and O(1) space: XOR every index and value so each pair cancels and only the missing number is left.
Visual solution and codeEasy · Time O(32) · Space O(1)
Reverse Bits
Reverse the 32 bits of an unsigned integer by shifting each bit off n and onto the result.
Answer: Reverse the bits of a 32-bit integer: shift the result left, copy n & 1 into it, shift n right, 32 times. Watch each bit cross over.
Visual solution and codeMedium · Time O(32) · Space O(1)
Sum of Two Integers
Add two integers without the + or - operators: XOR adds without carrying, and AND shifted left is the carry.
Answer: Add two integers without +: a ^ b adds each column without the carry, (a & b) << 1 is the carry, repeat until it is 0. Step through each round.
Visual solution and codeMedium · Time O(log n) · Space O(1)
Pow(x, n)
Compute x to the power n in O(log n) by squaring: read n in binary and multiply in x^1, x^2, x^4, ... for every 1 bit.
Answer: Solve Pow(x, n) in O(log n) with exponentiation by squaring: square the base each round, multiply it in on 1 bits, flip negative n. Code in 6 languages.
Visual solution and codeMedium · Time O(log |x|) · Space O(1)
Reverse Integer
Reverse the digits of a 32-bit integer by popping the last digit and pushing it onto the result, checking for overflow before each push.
Answer: Solve Reverse Integer by popping digits with % 10 and pushing them with × 10, checking INT_MAX / 10 before each push so nothing overflows. 6 languages.
Visual solution and code
