DSA Interview Questions and Answers, by Pattern
328 DSA interview questions and answers: the 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 codeEasy · Time O(n) · Space O(n)
Reverse Vowels of a String
Reverse the order of the vowels in a string while every consonant stays in place, using two pointers that skip consonants and swap vowels.
Answer: Reverse only the vowels of a string with two pointers that skip consonants and swap when both land on vowels. O(n) time, with code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(n)
Reverse Words in a String
Reverse the order of the words in a string, dropping leading, trailing and repeated spaces, by splitting into words and swapping them with two pointers.
Answer: Reverse Words in a String: reverse the order of words and collapse extra spaces: split into words, swap them with two pointers, join with single spaces.
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: Two Sum II - Input Array Is Sorted: 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 codeMedium · Time O(n log n) · Space O(1)
Max Number of K-Sum Pairs
Count the most operations that each remove two numbers summing to k, by sorting the array and moving two pointers toward each other.
Answer: Max Number of K-Sum Pairs: count how many pairs summing to k can be removed: sort, then move two pointers inward by comparing the sum with k.
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: Valid 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(m + n)
Merge Strings Alternately
Merge two strings by alternating their letters, starting with the first word, and append whatever is left of the longer word at the end.
Answer: Merge Strings Alternately: merge two strings by taking one letter from each in turn, then append the rest of the longer one.
Visual solution and codeEasy · Time O(m + n) · Space O(m + n)
Greatest Common Divisor of Strings
Find the largest string that divides both inputs: compare str1 + str2 with str2 + str1, then take the prefix whose length is the gcd of the two lengths.
Answer: Greatest Common Divisor of Strings, step by step: why str1 + str2 == str2 + str1 decides it, and why the answer is the gcd-length prefix.
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 codeMedium · Time O(n) · Space O(1)
String Compression
Compress an array of characters in place by replacing each run of a repeated letter with the letter and its count, using a read and a write pointer.
Answer: String Compression: compress runs of repeated characters in place: a read pointer scans each run, a write pointer stores the letter and its count.
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 codeMedium · Time O(n) · Space O(1)
Next Permutation
Rearrange an array into the next lexicographically larger permutation in place: find the pivot from the right, swap it with its successor, reverse the suffix.
Answer: Solve Next Permutation in O(n): find the pivot from the right, swap it with the next larger value, reverse the suffix. Visual dry run, 6 languages.
Visual solution and codeMedium · Time O(n · (n + m)) · Space O(n + m)
Repeated String Match
Find the minimum number of times string a must be repeated so that b becomes a substring of it, by checking only the two repeat counts that can possibly work.
Answer: Repeated String Match: fewest copies of a so that b is a substring: repeat a until it is at least as long as b, then check that count and one more.
Visual solution and codeEasy · Time O(n · m) · Space O(1)
Find the Index of the First Occurrence in a String
Return the index where needle first appears in haystack, or -1, by lining needle up at each start and comparing character by character with two pointers.
Answer: LeetCode 28 (strStr) with two pointers: slide needle along haystack, compare character by character, and stop at the first full match. Code in 6 languages.
Visual solution and codeHard · Time O(n) · Space O(n)
Shortest Palindrome
Turn a string into the shortest palindrome by adding characters only in front, using the KMP prefix function to find the longest prefix that is already a palindrome.
Answer: Shortest Palindrome: make s a palindrome by adding the fewest characters in front: find its longest palindromic prefix with KMP's lps on s + '#' + reverse(s).
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: 3Sum: 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 (LeetCode 18) in O(n³): sort, fix two numbers, sweep the rest with two pointers, and skip duplicates at every level.
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: Valid Triangle Number: 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 Zeroes: 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 Colors: 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: Trapping Rain Water: compute trapped rain water in O(n) time and O(1) space by moving the pointer on the side with the lower wall.
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 codeMedium · Time O(n) · Space O(1)
String to Integer (atoi)
Convert a string to a 32-bit signed integer the way C's atoi does: skip leading spaces, read an optional sign and digits, and clamp on overflow.
Answer: Parse a string into a 32-bit integer the way atoi does: skip spaces, read a sign, read digits and clamp before it overflows. 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 + m) · Space O(n + m)
Find the Difference of Two Arrays
List the distinct values that appear in only one of two arrays by turning each into a hash set and checking every value against the other set.
Answer: Find the Difference of Two Arrays: return the distinct values only in nums1 and only in nums2: build two hash sets, then keep each value the other set lacks.
Visual solution and codeEasy · Time O(n) · Space O(n)
Unique Number of Occurrences
Decide whether each value in an array occurs a different number of times by counting the values, then checking the counts for a repeat.
Answer: Unique Number of Occurrences: Check whether every value in an array occurs a different number of times: count with a hash map.
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: Valid Anagram with one hash map: count every letter of s, spend the counts on t, and watch them rise and fall step by step.
Visual solution and codeEasy · Time O(n) · Space O(1)
Longest Palindrome
Find the length of the longest palindrome that can be built from a string's letters by counting them, using every pair and adding one middle letter.
Answer: Find the longest palindrome you can build from a string's letters: use every pair, then one leftover letter in the middle. O(n) time, code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Determine if Two Strings Are Close
Decide whether one string can become another by swapping characters and swapping two letters everywhere: compare lengths, letter sets and sorted letter counts.
Answer: Determine if Two Strings Are Close: two strings are close when they have the same length, the same letters and the same counts once sorted.
Visual solution and codeMedium · Time O(n²) · Space O(n²)
Equal Row and Column Pairs
Count the pairs of a row and a column in a square grid that hold the same values in the same order, by hashing every row and looking up every column.
Answer: Equal Row and Column Pairs: count the row and column pairs that hold the same values: hash every row as a key, then look up each column.
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: Longest Consecutive Sequence (LeetCode 128) in O(n) without sorting: put the numbers in a hash set and count each run only from its start. Step-by-step dry run.
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 codeMedium · Time O(p) · Space O(p)
Detect Squares
Count the axis-aligned squares a query point can complete with stored points: a hash map of point counts, and each stored point tried as the diagonal corner.
Answer: Solve Detect Squares by counting points in a hash map and trying each stored point as the opposite corner. Duplicates multiply. Visual dry run, 6 languages.
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 codeMedium · Time O(n) · Space O(1)
Majority Element II
Return every value that appears more than n/3 times, in linear time and constant space, with two-candidate Boyer-Moore voting and a second counting pass.
Answer: Majority Element II: find every value appearing more than n/3 times in O(n) time and O(1) space: Boyer-Moore voting with two candidates, then a count.
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(1)
Maximum Number of Vowels in a Substring of Given Length
Find the most vowels in any substring of length k with a fixed-size sliding window that updates its vowel count in O(1) per step.
Answer: LeetCode 1456: count vowels in every substring of length k with a fixed sliding window: add the letter entering, subtract the one leaving.
Visual solution and codeMedium · Time O(n) · Space O(1)
Longest Subarray of 1's After Deleting One Element
Find the longest subarray of 1s left after deleting exactly one element, using a sliding window that allows at most one zero inside it.
Answer: Longest Subarray of 1's After Deleting One Element: Find the longest run of 1s after deleting exactly one element.
Visual solution and codeMedium · 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: Longest Repeating Character Replacement (LeetCode 424) solution: a sliding window with letter counts that allows at most k replacements. Dry run.
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)
Binary Subarrays With Sum
Count the non-empty subarrays of a binary array whose sum equals goal, by counting sums at most goal and at most goal - 1 with two sliding windows.
Answer: Binary Subarrays With Sum: count subarrays with sum exactly goal as atMost(goal) minus atMost(goal - 1), each one sliding window.
Visual solution and codeMedium · Time O(n) · Space O(1)
Count Number of Nice Subarrays
Count the contiguous subarrays that contain exactly k odd numbers, as subarrays with at most k odds minus those with at most k - 1, each a sliding window.
Answer: Count Number of Nice Subarrays: count subarrays with exactly k odd numbers in O(n): atMost(k) minus atMost(k - 1), two sliding windows over parity.
Visual solution and codeMedium · Time O(n) · Space O(1)
Number of Substrings Containing All Three Characters
Count the substrings of a string of a, b and c that contain at least one of each letter, with a sliding window that counts all right-hand extensions at once.
Answer: Number of Substrings Containing All Three Characters in O(n): once a window holds a, b and c, every extension to the right counts too.
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 codeMedium · Time O(n) · Space O(k)
Longest Substring with At Most K Distinct Characters
Find the length of the longest substring that contains at most k distinct characters, with a sliding window whose character counts never exceed k keys.
Answer: Longest Substring with At Most K Distinct Characters (LeetCode 340): grow right, shrink left at k + 1 distinct, keep the longest. 6 languages.
Visual solution and codeEasy · Time O(1) · Space O(W)
Number of Recent Calls
Count the requests made in the last 3000 milliseconds by keeping their times in a queue and dropping the oldest ones as they fall out of the window.
Answer: Number of Recent Calls: count the pings in the last 3000 ms with a queue: append each ping, pop the ones that fell out of the window, return the size.
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(n) · Space O(1)
Fixed-Length Sliding Window
Master the fixed-size sliding window pattern: slide one element out, slide one element in.
Answer: Fixed-length sliding window: the maximum sum of any k consecutive values in O(n). Sum the first window, then add the entering value, subtract the leaving one.
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: Maximum Points You Can Obtain from Cards: Take k cards from either end for the highest score: start with all k from the left.
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: Maximum Sum of Distinct Subarrays With Length K: 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: Non-overlapping Intervals: find the fewest intervals to remove. Sort by end, keep each interval that starts at or after the last kept end, 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: Meeting Rooms: 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: Meeting Rooms II: 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(n)
Divide Intervals Into Minimum Number of Groups
Split inclusive intervals into the fewest groups so that no two intervals in a group intersect, by counting the most intervals that cover a single point.
Answer: Divide Intervals Into Minimum Number of Groups: LeetCode 2406: the fewest groups is the most intervals covering one point.
Visual solution and codeHard · Time O(n log n + m log m) · Space O(n + m)
Minimum Interval to Include Each Query
For each query, find the size of the smallest interval that contains it: answer queries in sorted order with a sweep over starts and a min-heap by size.
Answer: Solve Minimum Interval to Include Each Query: sort the queries, sweep the intervals by start, keep a min-heap by size and pop the ones that ended. 6 languages.
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: Min arrows to burst balloons: sort the balloons by end, shoot at each uncovered balloon's end, and count the arrows, step by step.
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 codeMedium · Time O(n) · Space O(1)
Delete the Middle Node of a Linked List
Remove the middle node of a linked list in one pass by starting the fast pointer two nodes ahead, so the slow pointer stops on the node before the middle.
Answer: Delete the Middle Node of a Linked List: delete the middle node in one pass: start fast two nodes ahead so slow stops just before the middle, then unlink it.
Visual solution and codeMedium · Time O(n) · Space O(1)
Odd Even Linked List
Move every node at an odd position ahead of the nodes at even positions, in place, by growing an odd chain and an even chain and joining them.
Answer: Odd Even Linked List: group the odd-position nodes before the even ones by relinking two chains in place, then joining them.
Visual solution and codeMedium · Time O(n) · Space O(1)
Maximum Twin Sum of a Linked List
Return the largest sum of a node and its twin, the node the same distance from the other end, by reversing the back half of the list and walking both halves at once.
Answer: Maximum Twin Sum of a Linked List: Find the largest sum of twin nodes: find the middle with slow and fast, reverse the back half.
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 codeMedium · Time O(n) · Space O(1)
Linked List Cycle II
Return the node where a linked list's cycle begins, or null, using Floyd's cycle detection and a second walk from the head, in O(1) extra space.
Answer: Linked List Cycle II: find the node where a linked list cycle begins in O(1) space: Floyd's slow and fast pointers meet, then walk one from head.
Visual solution and codeMedium · Time O(n log n) · Space O(log n)
Sort List
Sort a singly linked list in O(n log n) time with merge sort: split at the middle using slow and fast pointers, sort each half, and merge.
Answer: Sort a linked list in O(n log n): find the middle with slow and fast pointers, sort both halves, merge them. Visual dry run and code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Rotate List
Rotate a linked list to the right by k places in one pass plus a walk: count the nodes, reduce k modulo n, close the list into a ring and cut it at the new tail.
Answer: Rotate a linked list right by k in O(n): count n, take k % n, link the tail to the head, cut n - k nodes in. Visual dry run and code in 6 languages.
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: Solve Remove Nth Node From End of List (LeetCode 19) in one pass: dummy head node and fast/slow two-pointer gap visualizer with O(1) auxiliary space.
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 codeHard · Time O(1) · Space O(capacity)
LFU Cache
Design a least frequently used cache with O(1) get and put, breaking ties between equally used keys by evicting the least recently used one.
Answer: Build an LFU cache with O(1) get and put: a key map, one list per use count and a minFreq pointer. Ties go to the least recent key. Code in 6 languages.
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 Number in O(n) time and O(1) space: treat nums[i] as a next pointer and let Floyd's tortoise and hare find the cycle entrance.
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: Valid Parentheses: 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: Daily Temperatures: for each day, count the days until a warmer one: a stack of waiting days pops whenever a warmer day arrives.
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 Reverse Polish Notation: 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 codeEasy · Time O(n) · Space O(n)
Implement Queue using Stacks
Build a first-in, first-out queue from two last-in, first-out stacks, moving values across only when the output stack runs empty.
Answer: Implement Queue using Stacks: build a FIFO queue from two stacks: push onto one, pop from the other, and pour across only when it runs empty.
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 (LeetCode 853) with an interactive visualizer: sort by position descending, compute arrival times, and merge fleets with a monotonic stack.
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)
Sum of Subarray Minimums
Add up min(b) over every contiguous subarray b, in linear time, by counting with a monotonic stack how many subarrays each value is the minimum of.
Answer: Sum of Subarray Minimums: sum the minimum of every subarray in O(n): a monotonic stack finds how many subarrays each value is the minimum of.
Visual solution and codeMedium · Time O(n) · Space O(n)
Sum of Subarray Ranges
Add up the range (largest minus smallest) of every subarray in linear time, as the sum of subarray maximums minus the sum of subarray minimums.
Answer: Sum of Subarray Ranges: sum max - min over all subarrays in O(n): sum of subarray maximums minus sum of minimums, each counted with a monotonic stack.
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 codeHard · Time O(n) · Space O(n)
Basic Calculator
Evaluate an expression of +, - and nested brackets without eval, using a running sum and a stack that saves the sum and sign at every open bracket.
Answer: Basic Calculator: evaluate + and - with nested brackets: keep a running sum, push it with the sign at each '(', and fold the bracket back in at ')'.
Visual solution and codeMedium · Time O(n) · Space O(n)
Removing Stars From a String
Apply every star, which erases itself and the closest remaining letter to its left, in one pass by pushing letters onto a stack and popping on each star.
Answer: Removing Stars From a String: each star erases itself and the nearest letter to its left: push letters onto a stack, pop on every star, and join what is left.
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: Binary Search: 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 n) · Space O(1)
Guess Number Higher or Lower
Find a hidden number in [1, n] with binary search, guessing the middle of the remaining range and using the guess() answer to discard half of it.
Answer: Guess Number Higher or Lower: find the picked number with binary search: guess the middle, and let guess() tell you which half to drop.
Visual solution and codeMedium · Time O((n + m) log m) · Space O(log m)
Successful Pairs of Spells and Potions
For each spell, count the potions whose product with it reaches success. Sort the potions once, then binary search each spell’s first successful potion; everything after it succeeds too.
Answer: Successful Pairs of Spells and Potions, step by step: sort the potions, then binary search each spell’s first successful potion. O((n + m) log m).
Visual solution and codeMedium · Time O((n + L) log n) · Space O(log n)
Search Suggestions System
After each letter typed, suggest up to three products that start with the prefix, smallest first. Sort the products, then binary search each prefix and take up to three matches from there.
Answer: Search Suggestions System, step by step: sort the products, binary search the first product >= each typed prefix, and take up to three matches.
Visual solution and codeMedium · Time O(log n) · Space O(1)
Single Element in a Sorted Array
Find the one value that appears once in a sorted array of pairs in O(log n): binary search on whether the pair at an even index is still intact.
Answer: Single Element in a Sorted Array with binary search: snap mid to an even index; if nums[mid] equals nums[mid + 1], the single is to the right. 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: Sqrt(x) (LeetCode 69): find the largest k with k² ≤ x by binary search in O(log x), using 64-bit math so mid * mid never overflows. 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 (LeetCode 367) without sqrt using a binary search visualizer: avoid 32-bit integer overflow and compare mid * mid in O(log n).
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(m log n) · Space O(1)
Find a Peak Element II
Find any cell in a 2D grid that is strictly larger than its four neighbours, by binary searching on columns and comparing each column's maximum with its left and right neighbours.
Answer: Find a Peak Element II: find a peak in a 2D grid in O(m log n): binary search on columns, take each column's maximum and move toward a bigger neighbour.
Visual solution and codeMedium · Time O(n log M) · Space O(1)
Koko Eating Bananas (Apple Harvest)
Find the minimum eating speed to finish all piles within H hours.
Answer: Koko Eating Bananas, told as an apple harvest: find the slowest eating speed that finishes every pile within h hours by binary searching the speed itself.
Visual solution and codeHard · Time O(n log S) · Space O(1)
Split Array Largest Sum
Split an array into k pieces so the largest piece sum is as small as possible: binary search on that sum, with a greedy count of pieces for each try.
Answer: Solve Split Array Largest Sum by binary searching the answer: for each cap, cut greedily and count pieces. Visual walkthrough, dry run, 6 languages.
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(n) · Space O(1)
Search in Rotated Sorted Array II
Decide whether a target is in a rotated sorted array that may contain duplicates, with binary search plus a shrink step when duplicates hide the sorted half.
Answer: Search in Rotated Sorted Array II: binary search with duplicates. Find the sorted half, and shrink both ends when left, mid and right are equal.
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: Kth Largest Element in an Array: find the kth largest element with a min-heap that never holds more than k values: O(n log k) time, O(k) space.
Visual solution and codeMedium · Time O(log n) · Space O(n)
Smallest Number in Infinite Set
Design a set that starts with every positive integer, supports popSmallest and addBack. Keep a counter for the untouched tail of the set and a min-heap for numbers that were added back.
Answer: Smallest Number in Infinite Set, step by step: a counter stands for the infinite tail and a min-heap holds the numbers added back. O(log n) per call.
Visual solution and codeMedium · Time O(n log n) · Space O(n)
Maximum Subsequence Score
Pick k indices to maximise sum(nums1) × min(nums2). Sort the pairs by nums2, largest first, and keep the k largest nums1 seen so far in a min-heap; each pair in turn plays the minimum.
Answer: Maximum Subsequence Score, step by step: sort the pairs by nums2 descending and keep the k largest nums1 in a min-heap. O(n log n).
Visual solution and codeMedium · Time O((k + c) log c) · Space O(c)
Total Cost to Hire K Workers
Hire k workers, each round taking the cheapest among the first and last candidates workers. Keep two min-heaps, one per end, hire the cheaper top and refill from the untouched middle.
Answer: Total Cost to Hire K Workers, step by step: one min-heap per end of the line, hire the cheaper top, refill from the middle with two pointers.
Visual solution and codeEasy · Time O(log k) · Space O(k)
Kth Largest Element in a Stream
Design a class that returns the kth largest value after each new number arrives, by keeping a min-heap of the k largest values between calls.
Answer: Kth Largest Element in a Stream: keep a min-heap of the k largest values. Each add() pushes, pops past k, and returns the root. Code in 6 languages.
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: K Closest Points to Origin: find the k points nearest the origin with a max-heap that evicts the farthest point once it holds more than 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 K Closest Elements: 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(f + 10 log f) · Space O(tweets + follows)
Design Twitter
Design a mini Twitter: post tweets, follow and unfollow, and return the 10 most recent tweets in a user's news feed with a k-way merge on a heap.
Answer: Solve Design Twitter: timestamp each tweet, keep a follow set, and build the news feed with a k-way heap merge of followed users. tweets. 6 languages.
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: Find Median from Data Stream with two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalanced 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: Return Values in DFS: compute a tree's height two ways: children returning their heights up, or parents passing depth down.
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: Maximum Depth of Binary Tree: solve LeetCode 104 with bottom-up DFS: an empty node returns 0 and every node returns max(left, right) + 1.
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 + m) · Space O(n + m)
Leaf-Similar Trees
Two binary trees are leaf-similar when their leaves, read left to right, form the same sequence. Collect each tree’s leaves with a DFS and compare the two lists.
Answer: Leaf-Similar Trees, step by step: a DFS that visits left before right collects each tree’s leaves in order, then the two sequences are compared.
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: Path Sum: 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: Passing Values Down: 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.
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: Validate Binary Search Tree: solve LeetCode 98 by passing an open (low, high) range down the tree, so a violation deep inside a subtree is caught.
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(h) · Space O(h)
Delete Node in a BST
Remove a key from a binary search tree and return the root: search for it, splice it out if it has at most one child, otherwise replace it with its inorder successor.
Answer: Delete Node in a BST: delete a key from a binary search tree in O(h): search, splice out a node with 0 or 1 child, or copy in its inorder successor.
Visual solution and codeEasy · Time O(n) · Space O(1)
Search in a Binary Search Tree
Return the subtree rooted at the node holding a given value in a binary search tree, walking a single path from the root by comparing at each node.
Answer: Search in a Binary Search Tree: walk one path, left when smaller and right when larger, and return the subtree where it stops. O(h), code in 6 languages.
Visual solution and codeMedium · Time O(h) · Space O(1)
Insert into a Binary Search Tree
Insert a new value into a binary search tree by walking down from the root to the empty child where it belongs and attaching it as a leaf.
Answer: Insert into a Binary Search Tree: insert a value into a BST in O(h): walk left or right from the root until the child is empty and attach the new leaf there.
Visual solution and codeMedium · Time O(h) · Space O(1)
Inorder Successor in BST
Return the node that comes right after p in an inorder traversal of a binary search tree, the smallest value larger than p, using one walk down from the root.
Answer: Find the inorder successor of a node in a BST in one walk from the root: record each node larger than p and go left, otherwise go right. Code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(h)
Largest BST Subtree
Find the size of the largest subtree of a binary tree that is a valid binary search tree, by passing each subtree's BST status, size, minimum and maximum up to its parent.
Answer: Largest BST Subtree: find the biggest subtree that is a valid BST in one pass: each node gets is-BST, size, min and max from its children.
Visual solution and codeHard · Time O(n log n) · Space O(n)
Vertical Order Traversal of a Binary Tree
Return a binary tree's values column by column, top to bottom, breaking same-position ties by value, by tagging each node with its column and row and sorting.
Answer: Vertical Order Traversal of a Binary Tree: group a binary tree's nodes by column: DFS records (column, row, value), sort, then split by column.
Visual solution and codeMedium · Time O(n) · Space O(h)
Recover Binary Search Tree
Repair a binary search tree in which exactly two nodes' values were swapped, without changing its structure, by finding where the inorder sequence stops increasing.
Answer: Recover Binary Search Tree: fix a BST with two swapped nodes: walk inorder, take the larger value at the first drop and the smaller at the last, swap them back.
Visual solution and codeMedium · Time O(n) · Space O(h)
Construct Binary Search Tree from Preorder Traversal
Build the binary search tree whose preorder traversal is given, in a single pass, by passing each recursive call an upper bound for the values its subtree may take.
Answer: Construct Binary Search Tree from Preorder Traversal: Rebuild a binary search tree from its preorder traversal in O(n).
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 Binary Tree from Preorder and Inorder Traversal: take roots from preorder and 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 and Deserialize Binary Tree: serialize a binary tree with preorder DFS and '#' for empty children, then rebuild it token by token.
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: Binary Tree Tilt (LeetCode 563) solution with postorder DFS: return each subtree's sum and add |left − right| to a running total. O(n), dry run.
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: Diameter of Binary Tree (LeetCode 543): return heights up the tree and record left + right at every node, since the longest path may skip 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: Path Sum II: solve LeetCode 113: push each node onto the path, save a copy at a matching leaf, and pop on the way back.
Visual solution and codeMedium · Time O(n) · Space O(n)
Path Sum III
Count the downward paths in a binary tree that sum to a target. Keep the prefix sums of the current root-to-node path in a hash map and look up prefix − target at every node.
Answer: Path Sum III, step by step: a DFS that keeps root-to-node prefix sums in a hash map counts every downward path to the target in O(n).
Visual solution and codeMedium · Time O(n) · Space O(h)
Longest ZigZag Path in a Binary Tree
Find the longest path that alternates left and right steps. A DFS carries two lengths into each node: the zigzag that arrived by a left step and the one that arrived by a right step.
Answer: Longest ZigZag Path in a Binary Tree, step by step: one DFS passes down the zigzag lengths that arrive from a left and a right step. O(n).
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: Longest Univalue Path (LeetCode 687): each node returns its longest same-value arrow, reset to 0 on a different child, while best tracks bent paths.
Visual solution and codeMedium · Time O(V + E) · Space O(V + E)
Graph Representation: Adjacency List
How to build and store graphs efficiently.
Answer: Graph representation as an adjacency list: turn an edge list into one list per node, then answer LeetCode 1971 with a stack-based DFS.
Visual solution and codeMedium · Time O(V + E) · Space O(V)
Clone Graph
Deep copy a connected undirected graph.
Answer: Clone Graph: 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: Graph Valid Tree: 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: Flood Fill: solve LeetCode 733 by painting a pixel and recursing down, up, right and left into pixels of the original colour.
Visual solution and codeEasy · Time O(n) · Space O(h)
Binary Tree Inorder Traversal
Return a binary tree's values in inorder (left subtree, node, right subtree), iteratively with an explicit stack instead of recursion.
Answer: Inorder traversal of a binary tree without recursion: push left, pop and record, go right. Visual stack walkthrough, dry run and code in 6 languages.
Visual solution and codeEasy · Time O(n) · Space O(n)
Two Sum IV - Input is a BST
Decide whether two different nodes of a binary search tree sum to k, with a DFS that checks each node's partner against a set of values already visited.
Answer: Two Sum IV (Input Is a BST): check whether two nodes add up to k in O(n) with a set of seen values, or inorder plus two pointers. Dry run, 6 languages.
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: Number of Islands: 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 codeHard · Time O(R·C) · Space O(R·C)
Making A Large Island
Find the largest island you can make by turning at most one 0 into a 1, by labeling islands with ids and sizes and then scoring each water cell from its neighbors.
Answer: Making a Large Island: label each island by DFS with an id and size, then for every 0 add its distinct neighbouring islands + 1. Dry run, 6 languages.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Number of Distinct Islands
Count how many differently shaped islands a grid contains, where two islands are the same if one can be shifted onto the other, by hashing each island's cell offsets.
Answer: Number of Distinct Islands: DFS each island, record every cell's offset from the start, and keep the offset lists in a set to count shapes. 6 languages.
Visual solution and codeMedium · Time O(m·n) · Space O(m·n)
Surrounded Regions
Capture regions that are fully surrounded by 'X'.
Answer: Surrounded Regions: solve LeetCode 130 by marking every 'O' the border can reach, then capturing the rest in one pass.
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: Pacific Atlantic Water Flow: solve LeetCode 417 by climbing uphill from each ocean's edges and keeping the cells both oceans reach.
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)
Maximum Level Sum of a Binary Tree
Sum every level with BFS and return the smallest level with the largest sum.
Answer: Maximum Level Sum of a Binary Tree: solve LeetCode 1161 by summing each level with BFS and keeping the smallest level with the largest sum.
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 Right Side View
List the node visible on each level when the tree is viewed from the right, top level first.
Answer: Binary Tree Right Side View: 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: Zigzag Level Order Traversal: solve LeetCode 103 with ordinary level-order BFS, reversing the collected list on every odd level.
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: Maximum Width: solve LeetCode 662 by giving each node its slot index, 2i and 2i + 1, so null gaps count toward the width.
Visual solution and codeMedium · Time O(n) · Space O(n)
All Nodes Distance K in Binary Tree
Return the values of all nodes exactly k edges away from a target node, by adding parent links and running a level-by-level BFS from the target.
Answer: All Nodes Distance K in Binary Tree: find every node exactly k edges from a target in a binary tree: record parents with DFS, then BFS outward k levels.
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: BFS in Graphs: run BFS on an undirected graph to decide whether a path exists, and see why its layers give the shortest distance.
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: Minimum Knight Moves: 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: Rotting Oranges (LeetCode 994): BFS from every rotten orange at once, one minute per layer, and -1 when a fresh orange is cut off. Code in 6 languages.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Nearest Exit from Entrance in Maze
Find the fewest steps from the entrance to any empty cell on the border of a maze, not counting the entrance itself. BFS from the entrance reaches cells in order of distance, so the first border cell it finds is the answer.
Answer: Nearest Exit from Entrance in Maze, step by step: BFS from the entrance, mark cells when queued, and stop at the first empty border cell.
Visual solution and codeMedium · Time O(m · n) · Space O(m · n)
Walls and Gates
Fill every empty room with its distance to the nearest gate using one breadth-first search that starts from all the gates at once.
Answer: Solve Walls and Gates with one multi-source BFS: queue every gate first, then fill each empty room once with its distance to the nearest gate. 6 languages.
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: 01 Matrix (LeetCode 542) solution: queue every zero at once and flood distances outward with multi-source BFS, so each cell gets its nearest-zero distance.
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: Bus Routes: 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: Solution space trees: every backtracking problem walks one. 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: Subsets (LeetCode 78): 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 (LeetCode 46) with backtracking: mark a number used, append, recurse, then pop and unmark. Step through the choose and un-choose tree.
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 (LeetCode 77) with backtracking: choose numbers in increasing order from a start index, record paths of length k, then backtrack.
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 codeHard · Time O(9^m) · Space O(m)
Sudoku Solver
Fill a 9×9 sudoku in place by backtracking: try the digits each empty cell allows, recurse, and erase the digit when the recursion hits a dead end.
Answer: LeetCode 37: solve a sudoku by backtracking: fill each empty cell with the first digit its row, column and box allow, and erase it on a dead end.
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(C(9, k) · k) · Space O(k)
Combination Sum III
Find every set of k different digits from 1 to 9 that adds up to n. Backtrack over the digits in increasing order and stop a branch as soon as the next digit is larger than what remains.
Answer: Combination Sum III, step by step: choose digits 1 to 9 in increasing order, stop at k digits, and break once a digit is bigger than what remains.
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 Parentheses: generate every well-formed string of n pairs with backtracking: open while under n, close while under open.
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 codeMedium · Time O(n) · Space O(n)
Minimum Height Trees
Find every root that gives a tree the smallest possible height by trimming its leaves layer by layer until the one or two centres are left.
Answer: Minimum Height Trees: find the roots that give a tree its minimum height by trimming leaves layer by layer until one or two centres remain.
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 codeMedium · Time O(n · α(n)) · Space O(n)
Redundant Connection
Find the one edge that turns a tree into a graph with a cycle, using union-find: the first edge whose two ends are already connected.
Answer: Solve Redundant Connection with union-find: add edges in order, the first edge whose ends already share a root closes the cycle. Visual dry run, 6 languages.
Visual solution and codeMedium · Time O(E log E) · Space O(E)
Accounts Merge
Merge the accounts that belong to one person, joined by any shared email, using union-find over emails and a final group-and-sort pass.
Answer: Merge accounts that share an email: union each account's first email with the rest, then group emails by root and sort. Visual walkthrough, 6 languages.
Visual solution and codeHard · Time O(V + E) · Space O(V + E)
Critical Connections in a Network
Find every connection whose removal disconnects the network, the bridges of the graph, with one DFS that tracks discovery times and low-link values (Tarjan's algorithm).
Answer: Critical Connections in a Network: find every bridge in a network with one DFS: discovery times, low-link values and the low[v] > disc[u] test, step by step.
Visual solution and codeMedium · Time O(rooms + keys) · Space O(rooms)
Keys and Rooms
Room 0 is unlocked and every room holds keys to other rooms. Search from room 0 through the keys you find, and check whether every room gets opened.
Answer: Keys and Rooms, step by step: treat keys as edges, search from room 0 with a stack, and return whether every room was opened. O(rooms + keys).
Visual solution and codeMedium · Time O(n²) · Space O(n)
Number of Provinces
Count the provinces, groups of cities connected directly or through each other, in an adjacency matrix by running one DFS from every city not yet visited.
Answer: Number of Provinces: count connected groups of cities from an adjacency matrix: start a DFS from every unvisited city and count the starts.
Visual solution and codeMedium · Time O(n) · Space O(n)
Reorder Routes to Make All Paths Lead to the City Zero
The one-way roads between n cities form a tree. Count the fewest roads to reverse so every city can reach city 0: DFS from 0 and count the roads that point away from it.
Answer: Reorder Routes to Make All Paths Lead to the City Zero, step by step: store each road both ways with its direction, DFS from 0, count roads pointing away.
Visual solution and codeMedium · Time O(q · (V + E)) · Space O(V + E)
Evaluate Division
Given equations like a / b = 2, answer queries like a / c. Build a graph with an edge a → b weighted a / b, and answer each query by DFS, multiplying the weights along the path.
Answer: Evaluate Division, step by step: each equation is a weighted edge both ways, and each query is a DFS that multiplies the weights on its path.
Visual solution and codeMedium · Time O(V + E) · Space O(V)
Is Graph Bipartite?
Decide whether an undirected graph's nodes split into two sides with every edge crossing between them, by coloring each component with BFS.
Answer: Check if a graph is bipartite in O(V + E): BFS-color each component with two sides and fail on a same-side edge. Visual dry run and code in 6 languages.
Visual solution and codeMedium · Time O(n + E · α(n)) · Space O(n)
Number of Operations to Make Network Connected
Find the fewest cable moves that connect every computer in a network: check there are at least n - 1 cables, then count connected components with union-find.
Answer: Number of Operations to Make Network Connected: -1 with fewer than n - 1 cables, else components - 1, counted with union-find. Visual dry run.
Visual solution and codeMedium · Time O(R·C log(R·C)) · Space O(R·C)
Path With Minimum Effort
Find the route from the top-left to the bottom-right cell whose largest height difference between neighbors is as small as possible, with Dijkstra's algorithm.
Answer: Path With Minimum Effort: minimize the largest height step on a grid path with Dijkstra, using max instead of + to combine costs.
Visual solution and codeHard · Time O(E log E) · Space O(E)
Reconstruct Itinerary
Use every flight ticket exactly once, starting from JFK, and return the alphabetically smallest itinerary: an Eulerian path found with Hierholzer's algorithm.
Answer: Solve Reconstruct Itinerary with Hierholzer's algorithm: fly the smallest ticket, pop stuck airports onto the route, then reverse. Visual dry run, 6 languages.
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)
N-th Tribonacci Number
Compute the n-th Tribonacci number, the sum of the three before it, bottom-up with three rolling variables instead of recursion or a full table.
Answer: N-th Tribonacci Number: compute T(n) = T(n-1) + T(n-2) + T(n-3) bottom-up, keeping only the last three values: O(n) time, O(1) space.
Visual solution and codeMedium · Time O(n) · Space O(n)
Domino and Tromino Tiling
Count the ways to tile a 2 × n board with dominoes and L-shaped trominoes. dp[n] = 2 · dp[n − 1] + dp[n − 3], starting from dp[0] = 1, dp[1] = 1 and dp[2] = 2, modulo 10⁹ + 7.
Answer: Domino and Tromino Tiling, step by step: where dp[n] = 2·dp[n−1] + dp[n−3] comes from, and how to fill the table modulo 10⁹ + 7.
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: Counting Bits: 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: Solve Coin Change (LeetCode 322) with an interactive DP visualizer: learn why greedy fails, step through dp[amount] table filling, and trace back coins.
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: Step-by-step visual solution for Maximum Product Subarray (LeetCode 152) in O(n) time. Track curMax and curMin to handle negative values.
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 · S) · Space O(S)
Last Stone Weight II
Find the smallest possible weight of the last stone by turning the smashing game into splitting the stones into two piles as evenly as possible, solved as subset sum.
Answer: Last Stone Weight II: why smashing stones is really splitting them into two piles, and how a 0/1 knapsack finds the pile closest to half the total.
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: Decode Ways: 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: Maximal Square: 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: Unique Paths: 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
Triangle (LeetCode 120): 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 (LeetCode 120) with a DP visualizer: find the minimum path sum bottom-up in O(n^2) time and O(n) space with step-by-step table updates.
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(n²) · Space O(n²)
Longest Palindromic Subsequence
Find the longest subsequence of a string that reads the same both ways with interval DP over s[i..j]: matching ends wrap the best inside.
Answer: Solve Longest Palindromic Subsequence with interval DP: matching ends add 2 to the best inside, else drop one end. Step-by-step table, 6 languages.
Visual solution and codeHard · Time O(n²) · Space O(n²)
Palindrome Partitioning II
Find the minimum number of cuts that split a string into palindromes, with a dynamic program over prefixes and a palindrome table filled along the way.
Answer: Palindrome Partitioning II: fewest cuts to split a string into palindromes: for each prefix try every palindromic last piece, cuts[i] = min(cuts[j - 1] + 1).
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: Best Time to Buy and Sell Stock with Cooldown (LeetCode 309): three states, hold, sold and rest, with a dry run and O(1)-space code in 6 languages.
Visual solution and codeMedium · Time O(n) · Space O(1)
Best Time to Buy and Sell Stock with Transaction Fee
Maximize profit from unlimited trades when every sale costs a fee, with a two-state dynamic program over days: holding a share or holding cash.
Answer: LeetCode 714: max profit with a fee per sale in O(n): track the best profit holding a share and not holding one each day.
Visual solution and codeHard · Time O(n) · Space O(1)
Best Time to Buy and Sell Stock III
Find the maximum profit from at most two buy-and-sell transactions in one pass, keeping the best profit after the first buy, first sell, second buy and second sell.
Answer: Best Time to Buy and Sell Stock III: at most two transactions with four running values: buy1, sell1, buy2, sell2, updated each day in O(n) time and O(1) space.
Visual solution and codeHard · Time O(n · k) · Space O(k)
Best Time to Buy and Sell Stock IV
Find the maximum profit from at most k buy-and-sell transactions, keeping the best profit after each j-th buy and j-th sell and updating all of them every day.
Answer: Best Time to Buy and Sell Stock IV: at most k transactions with 2k running states: buy[j] and sell[j], updated each day in O(n · k).
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: Longest Increasing Subsequence: 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²) · Space O(n)
Number of Longest Increasing Subsequence
Count how many strictly increasing subsequences have the maximum length, by tracking for each index both the longest length ending there and how many ways reach it.
Answer: Number of Longest Increasing Subsequence: two DP arrays, the longest length ending at each index and how many reach it. Visual dry run, 6 languages.
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: Word Break: 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: Maximum Profit in Job Scheduling: 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)
Kids With the Greatest Number of Candies
Decide for each kid whether receiving every extra candy would give them the most candies, by finding the current maximum once and comparing each kid to it.
Answer: Kids With the Greatest Number of Candies: for each kid, check whether all the extra candies would bring them up to the current maximum.
Visual solution and codeEasy · Time O(n) · Space O(1)
Can Place Flowers
Decide whether n new flowers fit in a flowerbed where no two flowers may be adjacent, by planting greedily in each empty plot whose neighbours are empty.
Answer: Can Place Flowers: decide if n flowers fit in a flowerbed with no two adjacent: plant greedily in every empty plot whose neighbours are empty.
Visual solution and codeMedium · Time O(n) · Space O(n)
Dota2 Senate
Simulate the Dota2 senate vote with two queues of turns: whichever senator acts first bans the other and rejoins its queue for the next round.
Answer: Predict which party wins the Dota2 senate: each senator bans the next opponent due to vote. Two queues of turns, O(n) time. Code in 6 languages.
Visual solution and codeEasy · 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: Best Time to Buy and Sell Stock: track the cheapest price so far and the best sale so far in one pass: O(n) time, O(1) space.
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)
Increasing Triplet Subsequence
Decide whether an array has i < j < k with nums[i] < nums[j] < nums[k] in one pass, keeping only the smallest first and second values of a pair.
Answer: Increasing Triplet Subsequence in one pass and O(1) space: keep the smallest first and second values, and return true when a value beats both.
Visual solution and codeMedium · Time O(n) · Space O(1)
Gas Station
Find the starting gas station to complete the circuit.
Answer: Gas Station: 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: Jump Game: 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(n) · Space O(1)
Merge Triplets to Form Target Triplet
Decide whether merging triplets by element-wise max can produce a target: drop every triplet that overshoots it, merge all the rest.
Answer: Solve Merge Triplets to Form Target Triplet greedily: skip any triplet with a value above the target, merge the rest, compare. Visual dry run, 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 codeHard · Time O(n) · Space O(n)
Candy
Find the minimum number of candies to hand out so every child gets at least one and a child with a higher rating than a neighbor gets more, using two greedy passes.
Answer: Candy (LeetCode 135): give the minimum candies so higher-rated children beat their neighbors: one pass left to right, one right to left, keep the max.
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: Design Add and Search Words Data Structure with a trie: addWord inserts, search runs a DFS that tries every child at a '.' and backs up. 6 languages.
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 codeMedium · Time O(n · B) · Space O(n · B)
Maximum XOR of Two Numbers in an Array
Find the maximum XOR of any two numbers in an array by storing every number's bits in a trie and greedily walking toward the opposite bit at each level.
Answer: Maximum XOR of Two Numbers in an Array: Find the largest XOR of any two numbers in O(n) with a binary trie: insert every number's bits.
Visual solution and code
Prefix Sum interview questions
How the prefix sum pattern worksEasy · Time O(n) · Space O(1)
Find Pivot Index
Find the leftmost index whose left and right sums are equal, using the array total and one running left sum instead of a second prefix array.
Answer: Find Pivot Index: find the index where the left sum equals the right sum: total once, then a running left sum gives right = total - left - nums[i].
Visual solution and codeEasy · Time O(n) · Space O(1)
Find the Highest Altitude
Turn a list of altitude gains into the altitudes they reach with a running sum, and keep the highest one, counting the starting point at 0.
Answer: Find the Highest Altitude: add up the gains to get each altitude and keep the highest, starting from 0. A prefix sum with a running max, O(n) time, O(1) space.
Visual solution and codeMedium · 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: Count Vowels in Ranges: 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 Image: 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: Set Matrix Zeroes: zero every row and column that holds a zero, in place, using row 0 and column 0 as markers.
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: Number of 1 Bits: 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 codeMedium · Time O(32) · Space O(1)
Minimum Flips to Make a OR b Equal to c
Count the fewest single-bit flips in a and b so that a OR b equals c. Each bit position is independent: where c has 1, flip once if a and b both have 0; where c has 0, flip every 1 in a and b.
Answer: Minimum Flips to Make a OR b Equal to c, step by step: check each bit of a, b and c on its own and count the flips that bit needs.
Visual solution and codeMedium · Time O(n) · Space O(1)
Single Number II
Find the element that appears exactly once when every other element appears three times, in linear time and constant space, by counting each bit modulo 3.
Answer: Single Number II: find the one number that appears once when every other appears three times: count each bit's 1s and keep count % 3.
Visual solution and codeMedium · Time O(n) · Space O(1)
Single Number III
Find the two elements that appear exactly once when every other element appears twice, with XOR and a split on one differing bit, in linear time and constant space.
Answer: Single Number III: find the two numbers that appear once in O(n) time and O(1) space: XOR everything, split the array on the lowest set bit, XOR each group.
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: Sum of Two Integers: add two integers without +: a ^ b adds each column without the carry, (a & b) << 1 is the carry, repeat until it is 0.
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: Step-by-step visual solution for Reverse Integer (LeetCode 7). Check 32-bit overflow before multiplying by 10 without 64-bit integers.
Visual solution and code
