Master every Arrays & Strings pattern asked in Google, Meta, Amazon, Apple & Microsoft interviews. Covers prefix sum, Kadane, Dutch flag, two pointers, sliding window and 100 hand-picked problems with C, C++, Java, JavaScript & Python solutions.
March 19, 2026 Read →
Two Sum is the most asked interview problem at Google, Amazon and Meta. Learn every approach from O(n²) brute force to O(n) HashMap with C, C++, Java, JavaScript and Python solutions.
March 19, 2026 Read →
The classic stock problem asked at Amazon, Google and Microsoft. Learn the O(n) greedy "min so far" approach with complete solutions in C, C++, Java, JavaScript and Python, plus extensions to Stock II, III and IV.
March 19, 2026 Read →
Solve Contains Duplicate in O(n) time using a HashSet. Full solutions in C, C++, Java, JavaScript and Python with sorting alternative and follow-up questions asked at Amazon interviews.
March 19, 2026 Read →
Kadane's Algorithm is a must-know pattern for FAANG interviews. Solve Maximum Subarray in O(n) time with full solutions in C, C++, Java, JavaScript and Python, plus divide-and-conquer O(n log n) alternative.
March 19, 2026 Read →
Move all zeroes to end while maintaining relative order of non-zero elements. Optimal O(n) two-pointer solution with minimal writes. Full C, C++, Java, JavaScript and Python code.
March 19, 2026 Read →
Increment a large integer represented as an array by one. Learn the carry propagation pattern with O(n) solutions in C, C++, Java, JavaScript and Python.
March 19, 2026 Read →
Merge two sorted arrays in-place by filling from the end. The classic 3-pointer technique asked at Meta and Microsoft. Full solutions in C, C++, Java, JavaScript and Python.
March 19, 2026 Read →
Remove duplicates from a sorted array in-place using the write pointer pattern. O(n) time, O(1) space. Full solutions in C, C++, Java, JavaScript, Python with follow-up for allowing k duplicates.
March 19, 2026 Read →
Find the element that appears once while every other appears twice. The XOR bit trick gives O(n) time and O(1) space. Full solutions in C, C++, Java, JavaScript, Python plus Single Number II and III extensions.
March 19, 2026 Read →
Find the intersection of two integer arrays including duplicates. Each element appears as many times as it shows in both arrays.
March 19, 2026 Read →
Master cheatsheet of all 100 Arrays & Strings problems: patterns, time/space complexity, and MAANG company tags in one place.
March 19, 2026 Read →
Generate numRows rows of Pascal's triangle. Each interior element is the sum of the two elements above it.
March 19, 2026 Read →
Check if two strings are anagrams — same characters with same frequencies. Two O(n) approaches: 26-int array for lowercase, HashMap for Unicode.
March 19, 2026 Read →
Reverse a character array in-place using two pointers. O(n) time, O(1) space. The fundamental two-pointer swap pattern.
March 19, 2026 Read →
Find the index of the first non-repeating character in a string. Two-pass O(n) solution with a 26-array or HashMap.
March 19, 2026 Read →
Determine if a string is a palindrome considering only alphanumeric characters and ignoring cases. Two pointer O(n) O(1) solution with all 5 language implementations.
March 19, 2026 Read →
Find the longest common prefix string among an array of strings. Covers vertical scan O(n*m), horizontal scan, binary search, and Trie approaches with all 5 language solutions.
March 19, 2026 Read →
Count the number of prime numbers strictly less than n. Master the Sieve of Eratosthenes — one of the most elegant algorithms in CS — with full code in C, C++, Java, JavaScript and Python.
March 19, 2026 Read →
Find the missing number in [0,n]. Two elegant O(n) O(1) solutions: Gauss formula and XOR trick. Full solutions in C, C++, Java, JavaScript and Python.
March 19, 2026 Read →
Find the majority element that appears more than n/2 times. Boyer-Moore Voting Algorithm achieves O(n) time and O(1) space. Full C, C++, Java, JavaScript and Python solutions.
March 19, 2026 Read →
Find all integers in [1,n] missing from array of length n using O(n) time O(1) extra space via index negation.
March 19, 2026 Read →
Find maximum consecutive ones if you can flip at most k zeros to one. Variable sliding window O(n) solution.
March 19, 2026 Read →
Return the third distinct maximum or the max if fewer than 3 distinct values exist. Three-variable tracking O(n) O(1) solution.
March 19, 2026 Read →
Design a class to find the kth largest element in a data stream. Min-heap of size k: the top is always the answer. Full C++, Java, JavaScript and Python.
March 19, 2026 Read →
Implement Fisher-Yates shuffle for uniform random permutation. Every arrangement is equally probable. O(n) time O(1) extra space.
March 19, 2026 Read →
Compute running (prefix) sum in O(n) time O(1) extra space. The prefix sum pattern is foundational for range queries, subarray problems and 2D matrices.
March 19, 2026 Read →
Find all unique triplets summing to zero. Sort array then fix one element and use two pointers. Full O(n²) solution in C, C++, Java, JavaScript and Python.
March 19, 2026 Read →
Find two lines that together with the x-axis form a container holding the most water. Greedy two-pointer O(n) — never check a pair that can't be optimal.
March 19, 2026 Read →
Compute product of all elements except self without division. O(n) two-pass prefix/suffix approach with O(1) extra space.
March 19, 2026 Read →
Merge all overlapping intervals. Sort by start, then merge greedily in one pass. O(n log n) time.
March 19, 2026 Read →
Return all elements of an m×n matrix in spiral order. Use boundary shrinking or direction array. O(m*n) time O(1) space.
March 19, 2026 Read →
Group strings that are anagrams of each other. Use sorted string as HashMap key. O(n*k*log k) time. Full solutions in 5 languages.
March 19, 2026 Read →
Find length of longest substring without repeating characters. Optimal O(n) sliding window with HashMap tracking last seen positions.
March 19, 2026 Read →
Count subarrays summing to k. Classic prefix sum + HashMap trick: if prefix[j]-prefix[i]=k then prefix[i]=prefix[j]-k. O(n) time.
March 19, 2026 Read →
Search a target in a rotated sorted array with no duplicates. Modified binary search identifies which half is sorted, then checks the target range. O(log n) time.
March 19, 2026 Read →
Determine if you can reach the last index. Greedy: track maximum reachable index. If current position exceeds max reach, return false. O(n) O(1).
March 19, 2026 Read →
Rotate array right by k steps. Triple reverse trick: reverse whole, reverse first k, reverse rest. O(n) time O(1) space.
March 19, 2026 Read →
Find the minimum element in a rotated sorted array with no duplicates. Binary search: the minimum is in the unsorted half. O(log n) time O(1) space.
March 19, 2026 Read →
Find k most frequent elements. Approach 1: min-heap O(n log k). Approach 2: bucket sort O(n). Full 5-language solutions.
March 19, 2026 Read →
Find the maximum product of a contiguous subarray. Track both min and max at each position (negative * negative = positive). O(n) time O(1) space.
March 19, 2026 Read →
Rotate an n×n matrix 90 degrees clockwise in-place. Trick: transpose (swap i,j with j,i) then reverse each row. O(n²) time O(1) space.
March 19, 2026 Read →
Find the lexicographically next permutation in-place using a two-pass scan from the right.
March 19, 2026 Read →
Find the one duplicate in [1..n] without modifying the array using Floyd's tortoise-and-hare cycle detection.
March 19, 2026 Read →
Sort an array of 0s, 1s, and 2s in-place in one pass using Dijkstra's Dutch National Flag algorithm.
March 19, 2026 Read →
Insert a new interval into a sorted non-overlapping list and merge any overlaps in a single sweep.
March 19, 2026 Read →
Find the minimum number of intervals to remove so the rest are non-overlapping, using a greedy earliest-end-time strategy.
March 19, 2026 Read →
Find all unique combinations that sum to a target, using backtracking with candidate reuse allowed.
March 19, 2026 Read →
Generate all permutations of distinct integers using in-place swap backtracking.
March 19, 2026 Read →
Generate the power set of distinct integers using backtracking or bitmask enumeration.
March 19, 2026 Read →
Find the smallest contiguous subarray with sum >= target using the shrinkable sliding window technique.
March 19, 2026 Read →
Find all integers that appear twice using index-sign-marking trick in O(n) time and O(1) extra space.
March 19, 2026 Read →
Decode a run-length-encoded string like "3[a2[bc]]" = "abcbcabcbcabcbc" using a stack for nested brackets.
March 19, 2026 Read →
Find all unique combinations that sum to target where each number may be used once, skipping duplicates at each recursion level.
March 19, 2026 Read →
Search for a word in a 2D grid using DFS backtracking with in-place visited marking.
March 19, 2026 Read →
Determine if there exists an increasing subsequence of length 3 using two greedy variables in O(n) time O(1) space.
March 19, 2026 Read →
Find all unique quadruplets summing to target by extending the 3Sum pattern with an outer loop and duplicate skipping.
March 19, 2026 Read →
Find minimum number of jumps to reach the last index using greedy BFS-style level tracking.
March 19, 2026 Read →
Determine the unique starting gas station for a circular route using a greedy one-pass algorithm.
March 19, 2026 Read →
Find how many days until a warmer temperature for each day using a monotonic decreasing stack.
March 19, 2026 Read →
Find the longest consecutive integer sequence in O(n) using a HashSet and only extending sequences from their start.
March 19, 2026 Read →
Partition a string into the maximum number of parts where each letter appears in at most one part, using last occurrence mapping.
March 19, 2026 Read →
Calculate minimum CPU intervals for tasks with cooldown using a greedy formula based on the most frequent task count.
March 19, 2026 Read →
Find the minimum arrows needed to burst all balloons arranged as intervals using a greedy sort-by-end approach.
March 19, 2026 Read →
Maximize a number by making at most one swap, using a last-occurrence map to find the optimal swap greedily.
March 19, 2026 Read →
Find a peak element in O(log n) by binary searching on the slope direction — always move toward the higher neighbor.
March 19, 2026 Read →
Find the missing number in [0..n] using the Gauss sum formula or XOR in O(n) time O(1) space.
March 19, 2026 Read →
Find all elements appearing more than n/3 times using Extended Boyer-Moore Voting with two candidate trackers.
March 19, 2026 Read →
Rearrange an array so nums[0] < nums[1] > nums[2] < nums[3]... using virtual index mapping and nth_element for O(n) time.
March 19, 2026 Read →
Compress a sorted unique integer array into the smallest sorted list of range coverage strings.
March 19, 2026 Read →
Distribute minimum candies so each child with higher rating than neighbors gets more, using left-to-right then right-to-left passes.
March 19, 2026 Read →
Find the minimum total moves to make all array elements equal by targeting the median value.
March 19, 2026 Read →
Find the longest nested set S(k) in a permutation array by tracing cycles with visited marking in O(n) time.
March 19, 2026 Read →
Rearrange nums to maximize advantage over B using a greedy strategy: assign the smallest winning card, else discard the smallest.
March 19, 2026 Read →
Generate all unique subsets from an array with duplicates by sorting and skipping repeated elements at each recursion level.
March 19, 2026 Read →
Check if string B is a rotation of A by checking if B appears in A+A using a substring search.
March 19, 2026 Read →
Find the minimum times A must repeat so that B is a substring, using a tight bound on the number of repeats needed.
March 19, 2026 Read →
Calculate trapped rain water using inward two pointers that track left-max and right-max, replacing the classic O(n) space approach.
March 19, 2026 Read →
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque.
March 19, 2026 Read →
Find the smallest missing positive integer in O(n) time O(1) space using in-place cyclic sort to place each number at its correct index.
March 19, 2026 Read →
Find the largest rectangle in a histogram in O(n) using a monotonic increasing stack that computes area when a shorter bar is encountered.
March 19, 2026 Read →
Find the minimum window in s that contains all characters of t using a shrinkable sliding window with a character frequency counter.
March 19, 2026 Read →
Count elements smaller than each element to its right using a modified merge sort that counts inversions during the merge step.
March 19, 2026 Read →
Find the median of two sorted arrays in O(log(min(m,n))) by binary searching for the correct partition point.
March 19, 2026 Read →
Find the largest rectangle of 1s in a binary matrix by treating each row as a histogram and applying the Largest Rectangle in Histogram algorithm.
March 19, 2026 Read →
Count pairs (i,j) where i<j and nums[i]>2*nums[j] using modified merge sort to count cross-half pairs before merging.
March 19, 2026 Read →
Minimize the largest sum among m subarrays by binary searching on the answer and greedy checking feasibility.
March 19, 2026 Read →
Find the shortest subarray with sum >= K using a monotonic deque on prefix sums, handling negative numbers correctly.
March 19, 2026 Read →
Count the number of range sums that lie in [lower, upper] using a merge sort approach on prefix sums.
March 19, 2026 Read →
Find three non-overlapping subarrays of length k with maximum sum using sliding window sums and left/right best index arrays.
March 19, 2026 Read →
Find the minimum refueling stops to reach target by greedily picking the largest fuel station passed so far whenever we run out.
March 19, 2026 Read →
Find the longest subarray of 1s after deleting exactly one element using a sliding window that tracks the count of zeros.
March 19, 2026 Read →
Find the maximum number of points on the same line using a slope-as-fraction HashMap for each anchor point.
March 19, 2026 Read →
Find the longest valid parentheses substring using a stack that tracks the last unmatched index as a base.
March 19, 2026 Read →
Find the shortest subarray that when sorted makes the whole array sorted, using a single linear scan tracking violated boundaries.
March 19, 2026 Read →
Count subarrays where max element is in [L,R] using a clever counting formula with two linear scans.
March 19, 2026 Read →
Count subarrays with exactly K distinct integers using the formula: atMost(K) - atMost(K-1).
March 19, 2026 Read →
Find the minimum rotations to make all tops or bottoms equal by checking if a target value (from first domino) can unify the entire row.
March 19, 2026 Read →
Reconstruct the stamp sequence in reverse by greedily finding where the stamp can overwrite current characters in the target string.
March 19, 2026 Read →
Find the longest substring that appears at least twice using binary search on length and Rabin-Karp rolling hash for O(n log n) average time.
March 19, 2026 Read →
Design a stack that pops the most frequent element (breaking ties by recency) using frequency and group-stacks mapping.
March 19, 2026 Read →
Master every binary search pattern: classic, left/right boundary, rotated array, BS on answer, and 2D matrix — with templates and full index of 45 problems.
March 19, 2026 Read →
Implement classic binary search to find a target in a sorted array in O(log n) time.
March 19, 2026 Read →
Find the first bad version using left-boundary binary search: shrink hi to mid when version is bad.
March 19, 2026 Read →
Find where a target would be inserted in a sorted array using left-boundary binary search returning lo.
March 19, 2026 Read →
Compute integer square root using right-boundary binary search to find the largest k where k*k <= x.
March 19, 2026 Read →
Find the starting and ending positions of a target in a sorted array using two separate binary searches.
March 19, 2026 Read →
Search in a rotated sorted array by identifying which half is sorted and narrowing accordingly.
March 19, 2026 Read →
Find the minimum element in a rotated sorted array by comparing mid with right boundary to locate the rotation point.
March 19, 2026 Read →
Search a row-column sorted 2D matrix in O(log(m*n)) by treating it as a virtual 1D sorted array.
March 19, 2026 Read →
Find the minimum eating speed for Koko to finish all bananas in h hours using binary search on the answer space.
March 19, 2026 Read →
Find the minimum ship capacity to ship all packages within d days using binary search on capacity.
March 19, 2026 Read →
Find any peak element in O(log n) by always moving toward the uphill neighbor, which guarantees finding a peak.
March 19, 2026 Read →
Find the k closest elements to x in a sorted array by binary searching for the optimal left window boundary.
March 19, 2026 Read →
Find the single non-duplicate element in O(log n) by observing that pairs shift the parity of indices after the singleton.
March 19, 2026 Read →
Find the length of LIS in O(n log n) using patience sorting: binary search to maintain a sorted tails array.
March 19, 2026 Read →
Minimize the largest subarray sum when splitting into k parts using binary search on the possible answer range.
March 19, 2026 Read →
Search in a rotated sorted array that may contain duplicates by skipping lo++ when mid equals both boundaries.
March 19, 2026 Read →
Find the minimum day to make m bouquets of k adjacent flowers using binary search on the day value.
March 19, 2026 Read →
Find h-index from a sorted citations array in O(log n) using left-boundary binary search.
March 19, 2026 Read →
Count spell-potion pairs with product >= success by sorting potions and binary searching for each spell's threshold.
March 19, 2026 Read →
Find the kth smallest element in a row-column sorted matrix by binary searching on the value range.
March 19, 2026 Read →
Maximize the minimum distance between m balls in baskets using binary search on the answer (minimum distance).
March 19, 2026 Read →
Find the minimum in a rotated array with duplicates by shrinking hi-- when nums[mid]==nums[hi].
March 19, 2026 Read →
Find the median of two sorted arrays in O(log(min(m,n))) by binary searching for the correct partition point.
March 19, 2026 Read →
Count smaller elements to the right of each element using merge sort with position tracking in O(n log n).
March 19, 2026 Read →
Find the maximum number of nested envelopes by sorting by width ascending then height descending, then applying LIS.
March 19, 2026 Read →
Minimize the maximum value after performing k operations (average adjacent elements) using binary search on the answer.
March 19, 2026 Read →
Find the maximum length to cut k ribbons from given ribbons using binary search on the ribbon length.
March 19, 2026 Read →
Maximize nums[index] given array length n, sum constraint maxSum, and each element >= 1 using binary search on the peak value.
March 19, 2026 Read →
Find the kth missing number in a sorted array by binary searching on the number of missing elements up to each index.
March 19, 2026 Read →
Search a row-column sorted 2D matrix in O(m+n) using the staircase technique from top-right corner.
March 19, 2026 Read →
Place c cows in stalls to maximize the minimum distance between any two cows using binary search on the answer.
March 19, 2026 Read →
Count subarrays with sum in [lower, upper] using merge sort on prefix sums for O(n log n) complexity.
March 19, 2026 Read →
Find the picked number using binary search with the guess() API that returns -1, 0, or 1.
March 19, 2026 Read →
Count negatives in a sorted matrix in O(m+n) using the staircase approach or O(m log n) with binary search per row.
March 19, 2026 Read →
Check if a number is a perfect square in O(log n) using binary search or by exploiting odd-number sum identity.
March 19, 2026 Read →
Find the smallest letter in a circular sorted list that is greater than the target using left-boundary binary search.
March 19, 2026 Read →
Answer election queries for who is leading at time t by precomputing the leader at each vote and binary searching.
March 19, 2026 Read →
Find the duplicate in array of n+1 integers in [1,n] using binary search on value with count-of-smaller logic.
March 19, 2026 Read →
Find the kth smallest prime fraction from an array using binary search on the fraction value with a counting function.
March 19, 2026 Read →
Check if any element and its double both exist in an array using a hash set or sorting with binary search.
March 19, 2026 Read →
Implement get(key, timestamp) using binary search on stored sorted timestamps for O(log n) retrieval.
March 19, 2026 Read →
Maximize events attended by greedily attending the event with the earliest end date each day using binary search.
March 19, 2026 Read →
Find the kth smallest element from two sorted arrays in O(log(m+n)) using binary elimination of k/2 elements per step.
March 19, 2026 Read →
Find the minimum train speed to arrive on time given n rides (last ride doesn't wait) using binary search on speed.
March 19, 2026 Read →
Complete cheatsheet for Binary Search: all 7 patterns, the universal template, BS on answer guide, Big O reference, and MAANG priority.
March 19, 2026 Read →
Master bit manipulation: XOR tricks, counting bits, bitmask DP, Brian Kernighan, two's complement, and 5-language operators.
March 19, 2026 Read →
Every element appears twice except one. XOR all numbers: duplicates cancel (a^a=0), single number remains.
March 19, 2026 Read →
Every element appears 3 times except one. Track bit counts mod 3: ones and twos bitmasks, or count each bit position.
March 19, 2026 Read →
Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.
March 19, 2026 Read →
Count set bits (popcount). Brian Kernighan: n & (n-1) clears the lowest set bit; count how many operations until n=0.
March 19, 2026 Read →
Count set bits for all numbers 0..n. DP: dp[i] = dp[i >> 1] + (i & 1). Remove last bit and check if it was set.
March 19, 2026 Read →
Reverse bits of a 32-bit unsigned integer. Shift result left and input right 32 times, taking last bit each time.
March 19, 2026 Read →
Find missing number in 0..n array. XOR approach: XOR all indices with all values, duplicate indices cancel. Or math: n*(n+1)/2 - sum.
March 19, 2026 Read →
Add two integers without + or - operators. Simulate: sum = a XOR b (no carry), carry = (a AND b) << 1. Repeat until carry = 0.
March 19, 2026 Read →
Generate all subsets of an array. Each subset corresponds to a bitmask of n bits where bit i = 1 means element i is included.
March 19, 2026 Read →
Can array be partitioned into k equal-sum subsets? Bitmask DP: dp[mask] = sum filled so far. O(2^n * n) instead of O(k^n) DFS.
March 19, 2026 Read →
Sum of Hamming distances between all pairs. For each bit position, count 0s and 1s: contribution = count_0 * count_1.
March 19, 2026 Read →
AND of all numbers in [left, right]. Result is the common prefix of left and right: keep shifting right until equal, then shift back.
March 19, 2026 Read →
Assign each element of nums1 to exactly one element of nums2 to minimize XOR sum. Classic assignment bitmask DP: dp[mask] = min XOR sum.
March 19, 2026 Read →
Generate n-bit Gray code sequence where adjacent codes differ by exactly 1 bit. Formula: gray(i) = i ^ (i >> 1).
March 19, 2026 Read →
Find all 10-letter DNA sequences that appear more than once. Use rolling hash (4-bit per char) or set of seen substrings.
March 19, 2026 Read →
Count words that contain puzzle[0] and only letters from puzzle. Encode words as bitmasks, for each puzzle enumerate its subsets containing puzzle[0].
March 19, 2026 Read →
Find max product of lengths of two words with no common letters. Encode each word as bitmask; two words share letters if AND != 0.
March 19, 2026 Read →
Complete bit manipulation cheatsheet: all critical tricks, bitmask DP patterns, XOR properties, complexity table, and problem index.
March 19, 2026 Read →
Master 1D DP: Fibonacci/Climbing Stairs, House Robber, LIS, Coin Change, Jump Game, and Kadane patterns with 5-language templates.
March 19, 2026 Read →
Count ways to climb n stairs taking 1 or 2 steps. Classic Fibonacci DP — dp[n] = dp[n-1] + dp[n-2] with O(1) space.
March 19, 2026 Read →
Find minimum cost to reach the top of stairs. Each stair has a cost; you can take 1 or 2 steps. DP: min cost to reach each stair.
March 19, 2026 Read →
Maximize amount robbed without robbing adjacent houses. Classic skip-one DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
March 19, 2026 Read →
Houses arranged in a circle: first and last are adjacent. Run linear House Robber twice: once excluding last house, once excluding first.
March 19, 2026 Read →
Picking value k deletes all k-1 and k+1 elements. Map to House Robber: earn[k] = k * count(k), then max non-adjacent sum.
March 19, 2026 Read →
Find the contiguous subarray with the largest sum. Kadane's algorithm: either extend previous subarray or start fresh at current element.
March 19, 2026 Read →
Find maximum product of a contiguous subarray. Track both min and max at each position because a negative * negative becomes positive.
March 19, 2026 Read →
Find minimum coins to make amount. Unbounded knapsack DP: dp[amount] = min(dp[amount-coin]+1) over all coins. Bottom-up from 0 to amount.
March 19, 2026 Read →
Count number of combinations making up amount. Process each coin denomination completely (outer loop = coin) to avoid counting permutations.
March 19, 2026 Read →
Minimum perfect squares summing to n. Isomorphic to Coin Change where coins = all perfect squares ≤ n.
March 19, 2026 Read →
Check if you can reach the last index. Greedy: track furthest reachable index. If current position > reach, stuck.
March 19, 2026 Read →
Find minimum jumps to reach the last index. Greedy: at each jump boundary, extend to the farthest reachable position.
March 19, 2026 Read →
Count ways to decode a digit string as letters (A=1,...,Z=26). DP: single digit + valid double digit transitions.
March 19, 2026 Read →
Check if string can be segmented into dictionary words. DP: dp[i]=true if some dp[j] is true and s[j:i] is in wordDict.
March 19, 2026 Read →
Find the length of the longest strictly increasing subsequence. O(n²) DP or O(n log n) patience sorting with binary search.
March 19, 2026 Read →
Maximum envelopes you can nest. Sort by width ascending and height descending, then LIS on heights. Descending heights prevents using same-width twice.
March 19, 2026 Read →
Count palindromic substrings. Expand around each center (n odd-length + n-1 even-length centers), count valid expansions.
March 19, 2026 Read →
Find longest palindromic subsequence length. 2D DP: if s[i]==s[j], dp[i][j] = dp[i+1][j-1]+2, else max of neighbors. Fill diagonally.
March 19, 2026 Read →
Can array be partitioned into two equal-sum subsets? 0/1 knapsack: can we pick some numbers summing to total/2? Bitset or DP boolean array.
March 19, 2026 Read →
Assign + or - to each number to reach target sum. DP counts ways to reach each sum. Reduces to 0/1 knapsack subset sum count.
March 19, 2026 Read →
LCS of two strings: dp[i][j] = LCS of first i chars of s1 and first j chars of s2. Full 2D DP treatment in the 2D DP section.
March 19, 2026 Read →
Complete 1D DP cheatsheet: 8 patterns, key transitions, complexity table, and problem index.
March 19, 2026 Read →
Master 2D DP: LCS, Edit Distance, grid path counting, matrix chain, interval DP, and stock patterns with 5-language templates.
March 19, 2026 Read →
Count paths from top-left to bottom-right moving only right or down. dp[i][j] = dp[i-1][j] + dp[i][j-1]. Math formula O(1) also works.
March 19, 2026 Read →
Count paths avoiding obstacle cells. Same DP but obstacles block cell (dp[i][j]=0) and obstacle at start/end returns 0.
March 19, 2026 Read →
Find minimum cost path from top-left to bottom-right moving right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
March 19, 2026 Read →
Minimum path sum from top to bottom of triangle. Bottom-up DP: dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).
March 19, 2026 Read →
Classic LCS: dp[i][j] = LCS length of s1[:i] and s2[:j]. If chars match add 1 to diagonal; else take max of skip either string.
March 19, 2026 Read →
Minimum operations (insert, delete, replace) to transform word1 to word2. Classic Wagner-Fischer 2D DP with O(n) space optimization.
March 19, 2026 Read →
Find shortest string containing both strings as subsequences. Length = len(s1)+len(s2)-LCS. Reconstruct by tracing DP table.
March 19, 2026 Read →
Maximize coins by bursting balloons. Key insight: think of last balloon burst in interval [i,j]. dp[i][j] = max coins from interval with k as last balloon.
March 19, 2026 Read →
Maximize profit from a single buy-sell. Track running minimum price; at each day profit = price - min_so_far.
March 19, 2026 Read →
Maximize profit with unlimited buy-sell transactions (but hold at most 1 share). Greedy: collect every upward slope.
March 19, 2026 Read →
Maximize profit with at most 2 transactions. Track 4 states: buy1, sell1, buy2, sell2. State machine DP.
March 19, 2026 Read →
At most k transactions. dp[t][i] = max profit using t transactions up to day i. If k >= n/2, unlimited transactions.
March 19, 2026 Read →
Unlimited transactions with 1-day cooldown after selling. 3-state DP: hold, sold (cooldown), rest.
March 19, 2026 Read →
Unlimited transactions with transaction fee per sell. 2-state DP: cash (not holding) and hold (holding stock).
March 19, 2026 Read →
Check if s3 is formed by interleaving s1 and s2. dp[i][j] = can s3[:i+j] be formed from s1[:i] and s2[:j].
March 19, 2026 Read →
Match string s against pattern p with . and *. dp[i][j] = does s[:i] match p[:j]. Handle * by matching zero or more of preceding char.
March 19, 2026 Read →
Match string with wildcard pattern: ? matches any char, * matches any sequence. Similar to regex but * matches any sequence (not zero/more of preceding).
March 19, 2026 Read →
Find minimum initial health to reach bottom-right dungeon cell. Solve backwards: dp[i][j] = min health needed at (i,j) to survive.
March 19, 2026 Read →
Find maximum strings using at most m zeros and n ones. 2D 0/1 knapsack: dp[i][j] = max strings using i zeros and j ones.
March 19, 2026 Read →
Find minimum sum falling path from top row to bottom row, moving to adjacent diagonal cells. DP row by row.
March 19, 2026 Read →
Minimum turns to print string where each turn prints a contiguous run of same char. Interval DP: dp[i][j] = min turns for s[i..j].
March 19, 2026 Read →
Complete 2D DP cheatsheet: 7 patterns, key transitions, stock state machine, interval DP template, and problem index.
March 19, 2026 Read →
Master BFS and DFS on graphs and grids: islands, flood fill, shortest paths, connected components, and multi-source BFS with 5-language implementations.
March 19, 2026 Read →
Count connected land components in a binary grid using DFS flood fill or BFS. Classic easy problem, foundation for all island variants.
March 19, 2026 Read →
Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.
March 19, 2026 Read →
Calculate the perimeter of an island in a binary grid. Each land cell contributes 4 edges minus 2 for each land neighbour.
March 19, 2026 Read →
Find the maximum area of any island in a binary grid. DFS returns the area of each island, track the maximum.
March 19, 2026 Read →
Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.
March 19, 2026 Read →
Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.
March 19, 2026 Read →
For each cell find distance to nearest 0. Multi-source BFS from all 0s simultaneously gives optimal O(m*n) solution.
March 19, 2026 Read →
Fill each empty room with distance to nearest gate. Multi-source BFS from all gates (0) simultaneously, walls (-1) are barriers.
March 19, 2026 Read →
Count land cells that cannot reach the border. Boundary DFS marks all reachable land from borders, then count remaining land cells.
March 19, 2026 Read →
Count islands in grid2 that are subsets of islands in grid1. DFS the island in grid2 and verify every cell is also land in grid1.
March 19, 2026 Read →
Find the largest island after flipping exactly one 0 to 1. Color each island with DFS, store sizes, then check each 0 cell's unique neighbour islands.
March 19, 2026 Read →
Find cells that can flow to both Pacific and Atlantic oceans. Run DFS backwards from each ocean border, find intersection.
March 19, 2026 Read →
Find shortest clear path from top-left to bottom-right in binary matrix using 8-directional BFS. Return path length or -1.
March 19, 2026 Read →
Find the water cell farthest from any land. Multi-source BFS from all land cells gives each water cell its min distance to land.
March 19, 2026 Read →
Search for a word in a grid by moving to adjacent cells without reuse. DFS with backtracking: mark visited, recurse, unmark.
March 19, 2026 Read →
Count islands with distinct shapes. Encode each island's DFS traversal path as a string to capture shape, store in a set.
March 19, 2026 Read →
Count islands fully surrounded by water (no border touch). Flood-fill border land first, then count remaining connected land components.
March 19, 2026 Read →
Find minimum flips to connect two islands. DFS to find and color first island, then BFS outward until reaching second island.
March 19, 2026 Read →
Find path from top-left to bottom-right minimizing maximum absolute difference between consecutive cells. Use Dijkstra or binary search + BFS.
March 19, 2026 Read →
Count islands after each addLand operation. Online version requires Union-Find: add each land cell and union with adjacent land cells.
March 19, 2026 Read →
Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.
March 19, 2026 Read →
Count connected components in an undirected graph given as adjacency matrix. DFS or Union-Find both work.
March 19, 2026 Read →
Determine if all rooms are reachable. Start from room 0, DFS using keys found in each room to unlock new rooms.
March 19, 2026 Read →
Check if a path exists between source and destination in an undirected graph. BFS from source or Union-Find both work in O(V+E).
March 19, 2026 Read →
BFS from entrance in a maze to find nearest exit (border empty cell). Classic BFS shortest path with exit condition.
March 19, 2026 Read →
Minimum dice rolls to reach square n^2. Convert board position to 2D coordinates (Boustrophedon order), BFS on board states.
March 19, 2026 Read →
Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.
March 19, 2026 Read →
Check if you can reach a 0 in the array by jumping arr[i] steps left or right. BFS/DFS from start index.
March 19, 2026 Read →
Determine if you can finish all courses given prerequisites. Equivalent to detecting a cycle in a directed graph using BFS (Kahn) or DFS coloring.
March 19, 2026 Read →
Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.
March 19, 2026 Read →
Check if n nodes and edges form a valid tree: must be connected and acyclic. Exactly n-1 edges, all connected via BFS/DFS or Union-Find.
March 19, 2026 Read →
Count connected components in an undirected graph. Union-Find or BFS both give O(V+E) solution.
March 19, 2026 Read →
Find the edge that creates a cycle in an undirected graph that started as a tree. Process edges with Union-Find; the first edge whose endpoints share a root is redundant.
March 19, 2026 Read →
Find all paths from node 0 to node n-1 in a DAG. DFS with backtracking: explore each path, add to results when destination reached.
March 19, 2026 Read →
Find time for signal to reach all nodes. Single-source shortest path (Dijkstra) from node k; answer is max of all shortest distances.
March 19, 2026 Read →
Find cheapest flight from src to dst with at most k stops. Bellman-Ford with k+1 iterations or BFS level-by-level.
March 19, 2026 Read →
Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.
March 19, 2026 Read →
Find ALL shortest transformation sequences. BFS builds layer map, DFS reconstructs all paths backwards from endWord to beginWord.
March 19, 2026 Read →
Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.
March 19, 2026 Read →
Check if people can be split into two groups with no dislikes within a group. Equivalent to bipartite check on dislikes graph.
March 19, 2026 Read →
Check if a graph can be 2-colored such that no adjacent nodes share a color. BFS/DFS 2-coloring on all connected components.
March 19, 2026 Read →
BFS with (position, last_jumped_back) state to find min jumps home avoiding forbidden positions. State space BFS avoids revisiting same position+direction.
March 19, 2026 Read →
Evaluate queries like A/C = A/B * B/C. Build weighted directed graph from equations, BFS/DFS to multiply edge weights along paths.
March 19, 2026 Read →
Count total reachable nodes in a subdivided graph within M moves. Dijkstra from node 0 gives max remaining moves at each node; use those to count subdivisions.
March 19, 2026 Read →
Complete cheatsheet for BFS and DFS on graphs and grids: 7 patterns, complexity table, common pitfalls, and problem index.
March 19, 2026 Read →
Master Greedy and Monotonic Stack: interval scheduling, activity selection, next greater/smaller element, largest rectangle, and trapping rain water.
March 19, 2026 Read →
Maximize children satisfied. Sort both greed and cookie sizes; greedily assign the smallest sufficient cookie to each child.
March 19, 2026 Read →
Minimum removals to make intervals non-overlapping. Sort by end time; greedily keep earliest-ending intervals, count conflicts.
March 19, 2026 Read →
Find minimum arrows to burst all balloons (intervals). Sort by end; one arrow can burst all overlapping intervals. Count arrows needed.
March 19, 2026 Read →
Find starting gas station index to complete circular route. If total gas >= total cost, a solution exists. Track running balance; reset start when negative.
March 19, 2026 Read →
Distribute minimum candies with higher-rated children getting more than neighbors. Two-pass: left-to-right for ascending, right-to-left for descending.
March 19, 2026 Read →
For each element in nums1, find next greater element in nums2. Monotonic stack + hashmap: process nums2, pop when greater found, store in map.
March 19, 2026 Read →
For each day find how many days until a warmer temperature. Monotonic decreasing stack of indices; pop when warmer temperature found.
March 19, 2026 Read →
Find the area of the largest rectangle in a histogram. Monotonic increasing stack: when a shorter bar is found, pop and compute rectangle area using popped height and current width.
March 19, 2026 Read →
Calculate water trapped between bars. Two-pointer approach: maintain max_left and max_right; water at each position = min(max_left, max_right) - height.
March 19, 2026 Read →
Remove duplicates to get smallest lexicographic subsequence with all chars. Greedy: use monotonic stack, only pop if char appears later.
March 19, 2026 Read →
Remove k digits to get smallest number. Monotonic increasing stack: pop larger digits when they appear before a smaller one. Remove remaining from end.
March 19, 2026 Read →
Sum of minimums of all subarrays. For each element, count how many subarrays have it as minimum using previous/next smaller element positions.
March 19, 2026 Read →
Find max j-i where i<j and nums[i]<=nums[j]. Build decreasing monotonic stack for left candidates, then scan from right to match.
March 19, 2026 Read →
Find i<j<k where nums[i]<nums[k]<nums[j]. Scan right-to-left with decreasing stack; track max popped element as potential 'nums[k]' candidate.
March 19, 2026 Read →
Find the largest rectangle in a binary matrix. Build histogram row by row (reset to 0 on '0'), apply Largest Rectangle in Histogram each row.
March 19, 2026 Read →
Next greater element in circular array. Iterate twice (2n) but use index mod n. Same decreasing stack pattern.
March 19, 2026 Read →
Minimum cost to connect all sticks. Always connect the two cheapest (Huffman coding variant). Min-heap greedy: cost = sum of merged sticks each round.
March 19, 2026 Read →
Partition string so each letter appears in at most one part. Track last occurrence of each char; greedily extend current partition end.
March 19, 2026 Read →
Reconstruct queue where [h,k] means person of height h has k taller/equal people in front. Sort by height desc (then k asc), insert at index k.
March 19, 2026 Read →
Maximum score to reach end where each jump is 1..k steps. Monotonic deque (sliding window maximum) of DP values for O(n) solution.
March 19, 2026 Read →
Find max chunks of array that when sorted individually give fully sorted array. A chunk boundary exists when max(chunk so far) == current index.
March 19, 2026 Read →
Complete Greedy and Monotonic Stack cheatsheet: all patterns, templates, complexity table, and problem index.
March 19, 2026 Read →
Master HashMap, HashSet, and cache design patterns with 45 problems, 5-language solutions, and MAANG company tags.
March 19, 2026 Read →
Find two indices that add to target in O(n) by storing each number in a HashMap and looking up the complement.
March 19, 2026 Read →
Check if two strings are anagrams by comparing their character frequency counts using an array or HashMap.
March 19, 2026 Read →
Check if a ransom note can be constructed from magazine letters using a character frequency map.
March 19, 2026 Read →
Check if two strings are isomorphic by maintaining bidirectional character mappings to ensure a consistent one-to-one correspondence.
March 19, 2026 Read →
Check if a string follows a given pattern using bidirectional mapping between pattern chars and words.
March 19, 2026 Read →
Determine if a number is happy by repeatedly summing digit squares and detecting cycles using a HashSet or Floyd algorithm.
March 19, 2026 Read →
Find if any two duplicate elements are within k indices of each other using a HashMap of last-seen positions.
March 19, 2026 Read →
Find characters common to all strings in a list by intersecting their frequency arrays with element-wise minimum.
March 19, 2026 Read →
Count how many stones are jewels by storing jewel types in a HashSet and checking each stone.
March 19, 2026 Read →
Find all groups of duplicate files by parsing path strings and grouping files by their content using a HashMap.
March 19, 2026 Read →
Group strings that are anagrams together by using their sorted form as a HashMap key.
March 19, 2026 Read →
Find the k most frequent elements in O(n) using bucket sort by frequency instead of a heap.
March 19, 2026 Read →
Design a Least Recently Used cache with O(1) get and put operations using a HashMap combined with a doubly linked list.
March 19, 2026 Read →
Count subarrays with sum exactly k using prefix sums stored in a HashMap to find valid starting positions in O(n).
March 19, 2026 Read →
Check if a continuous subarray of length >= 2 sums to a multiple of k using prefix sum modulo k with a HashMap.
March 19, 2026 Read →
Find the longest consecutive integer sequence in O(n) by using a HashSet and only starting sequences from their minimum element.
March 19, 2026 Read →
Design a set with O(1) insert, delete, and getRandom using a dynamic array combined with a HashMap for index tracking.
March 19, 2026 Read →
Find all starting indices of anagram substrings by using a fixed window with character frequency comparison.
March 19, 2026 Read →
Implement weighted random selection by building a prefix sum array and using binary search to find the sampled index.
March 19, 2026 Read →
Find the vertical line that crosses the fewest bricks by counting the most frequent gap position using a HashMap.
March 19, 2026 Read →
Check if all value frequencies are unique using two hash sets in O(n).
March 19, 2026 Read →
Count substrings with at most one odd-frequency letter using bitmask prefix XOR and a hash map.
March 19, 2026 Read →
Count (row, col) pairs that are equal by hashing each row tuple and each column tuple.
March 19, 2026 Read →
Find if a BST contains two nodes summing to target using a hash set during DFS traversal.
March 19, 2026 Read →
Find the longest arithmetic subsequence using dp[i][diff] = length ending at index i with given difference.
March 19, 2026 Read →
Count pairs (i,j) where j-i != nums[j]-nums[i] by counting good pairs via frequency map of nums[i]-i.
March 19, 2026 Read →
Find the smallest subarray to remove so the remaining sum is divisible by p using prefix modular arithmetic.
March 19, 2026 Read →
Count tuples (a,b,c,d) where a*b=c*d by counting pairs with each product using a frequency map.
March 19, 2026 Read →
Design a URL shortener using two hash maps for O(1) encode and decode operations.
March 19, 2026 Read →
Convert a fraction to decimal string with recurring part detected via remainder position tracking.
March 19, 2026 Read →
Find all duplicate subtrees by serializing each subtree and tracking serialization counts in a hash map.
March 19, 2026 Read →
Implement a hash map from scratch using an array of buckets with chaining for collision resolution.
March 19, 2026 Read →
Implement a hash set from scratch supporting add, remove, and contains in O(1) average time.
March 19, 2026 Read →
Pick a random index of a target value with equal probability using reservoir sampling over the array.
March 19, 2026 Read →
Find the most common word not in a banned list by normalizing input and using a frequency counter.
March 19, 2026 Read →
Determine if cards can be rearranged into consecutive groups of size groupSize using a sorted frequency map.
March 19, 2026 Read →
Count subarrays with sum divisible by k using prefix mod frequencies and the complement map pattern.
March 19, 2026 Read →
Count pairs summing to a power of 2 by checking all 22 powers-of-2 against a running frequency map.
March 19, 2026 Read →
Design a time-stamped key-value store supporting set and get(key, timestamp) using binary search on sorted timestamps.
March 19, 2026 Read →
Count 4-tuples summing to zero by splitting into two pairs and using a frequency map of pair sums.
March 19, 2026 Read →
Implement an LFU cache with O(1) get/put using three hash maps: key→val, key→freq, freq→OrderedDict.
March 19, 2026 Read →
Design a data structure supporting inc/dec and getMaxKey/getMinKey in O(1) using a doubly linked list of frequency buckets.
March 19, 2026 Read →
Design Twitter with follow/unfollow and getNewsFeed using per-user tweet lists and a min-heap merge.
March 19, 2026 Read →
Find all index pairs forming palindromes by checking prefix/suffix splits against a reverse-word map.
March 19, 2026 Read →
Complete cheatsheet for Hashing & Maps: all 7 patterns, Big O reference, template code, and MAANG priority guide.
March 19, 2026 Read →
Master heaps and priority queues: 7 core patterns including Top K, Two Heaps, Merge K, and scheduling problems.
March 19, 2026 Read →
Maintain a min-heap of size K to track the Kth largest element as numbers are added to a stream.
March 19, 2026 Read →
Simulate stone smashing by repeatedly extracting the two heaviest stones using a max-heap.
March 19, 2026 Read →
Assign gold/silver/bronze or rank numbers to athletes based on their scores using sorted ordering.
March 19, 2026 Read →
Find K closest elements to x in a sorted array using binary search to find the optimal left boundary.
March 19, 2026 Read →
Find the Kth largest element using quickselect O(n) average or a min-heap of size K in O(n log k).
March 19, 2026 Read →
Return the K most frequent elements using a frequency map plus min-heap, or bucket sort for O(n) solution.
March 19, 2026 Read →
Sort characters in a string by decreasing frequency using a frequency counter and max-heap or bucket sort.
March 19, 2026 Read →
Find K points closest to the origin using a max-heap of size K or quickselect for O(n) average.
March 19, 2026 Read →
Find minimum CPU intervals to schedule tasks with cooldown using a greedy max-heap simulation.
March 19, 2026 Read →
Rearrange a string so no two adjacent characters are the same using a greedy max-heap approach.
March 19, 2026 Read →
Maintain a dynamic median using two heaps: a max-heap for the lower half and a min-heap for the upper half.
March 19, 2026 Read →
Compute medians of all sliding windows using two heaps with lazy deletion for element removal.
March 19, 2026 Read →
Merge K sorted linked lists into one sorted list using a min-heap to always extract the globally smallest node.
March 19, 2026 Read →
Find the Kth smallest element in an n×n row-and-column sorted matrix using binary search on value range or heap.
March 19, 2026 Read →
Find K pairs (u, v) with smallest sums from two sorted arrays using a min-heap initialized with first row candidates.
March 19, 2026 Read →
Find the nth ugly number (only prime factors 2, 3, 5) using three pointers for the 2x, 3x, 5x merge streams.
March 19, 2026 Read →
Maximize courses taken within deadlines by greedily scheduling and swapping out the longest past course.
March 19, 2026 Read →
Find minimum conference rooms required by tracking room end times with a min-heap of ongoing meeting endings.
March 19, 2026 Read →
Find minimum cost to connect all sticks by greedily always merging the two shortest sticks first.
March 19, 2026 Read →
Maximize capital after k IPO investments by greedily picking the highest profit project among affordable ones.
March 19, 2026 Read →
Check if a car can pick up all passengers by processing start/end events with a sorted timeline or heap.
March 19, 2026 Read →
Greedily use ladders for the largest climbs and bricks for smaller gaps, managed with a min-heap of ladder sizes.
March 19, 2026 Read →
Assign tasks to available servers using two heaps: one for free servers and one for busy servers sorted by free time.
March 19, 2026 Read →
Calculate trapped water in a 3D height map using BFS with a min-heap to process cells from shortest boundary inward.
March 19, 2026 Read →
Find minimum time to swim from top-left to bottom-right in a grid where time = max elevation on the path.
March 19, 2026 Read →
Find the smallest range that contains at least one element from each of K sorted lists using a sliding K-way merge.
March 19, 2026 Read →
Find the nth super ugly number with prime factors only from a given list using K-pointer dynamic programming.
March 19, 2026 Read →
Find minimum fuel stops to reach the target by greedily selecting the largest available fuel stations when running low.
March 19, 2026 Read →
Design a simplified Twitter with follow/unfollow and a news feed showing the 10 most recent tweets from followed users.
March 19, 2026 Read →
Find the nth number divisible by a, b, or c using binary search with inclusion-exclusion counting formula.
March 19, 2026 Read →
Maximize team performance (sum of speeds * min efficiency) by sorting by efficiency and using a min-heap on speeds.
March 19, 2026 Read →
Build the longest string with at most 2 consecutive identical characters by always using the most frequent available character.
March 19, 2026 Read →
Design a stack that pops the most frequent element, breaking ties by most recently pushed, using frequency-bucket stacks.
March 19, 2026 Read →
Minimize max-min of an array by doubling odd numbers and repeatedly halving the max using a max-heap.
March 19, 2026 Read →
Extended practice: compute median for each window in a stream using two-heap with lazy deletion pattern.
March 19, 2026 Read →
For each query point, find the smallest interval containing it by sorting both intervals and queries, using a min-heap.
March 19, 2026 Read →
For each interval find the interval with the smallest start point >= the end point using sorted starts and binary search.
March 19, 2026 Read →
Sort array elements by frequency ascending, breaking ties by value descending.
March 19, 2026 Read →
Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.
March 19, 2026 Read →
Minimize total hiring cost by always choosing the cheapest candidate from the first or last p candidates using two min-heaps.
March 19, 2026 Read →
Design a seat manager that reserves the lowest numbered available seat and unreserves seats using a min-heap.
March 19, 2026 Read →
Track stock prices with corrections by maintaining a sorted multiset and a timestamp-to-price map.
March 19, 2026 Read →
Find the minimum number of elements to remove to reduce array size by half by greedily removing most frequent elements.
March 19, 2026 Read →
Find the subsequence of length k with the largest sum by selecting top k values while preserving original order.
March 19, 2026 Read →
Complete Heaps section recap with 7 patterns, complexity guide, and full problem index for interview prep.
March 19, 2026 Read →
Master every linked list pattern: reverse, two pointers, cycle detection, merge, clone, and design problems — with templates and full index of 45 problems.
March 19, 2026 Read →
Reverse a singly linked list iteratively with three-pointer technique and recursively with call stack.
March 19, 2026 Read →
Find the middle node of a linked list in one pass using the slow/fast pointer technique.
March 19, 2026 Read →
Detect a cycle in a linked list in O(1) space using Floyd's two-pointer tortoise and hare algorithm.
March 19, 2026 Read →
Merge two sorted linked lists into one sorted list using a dummy head node to simplify pointer management.
March 19, 2026 Read →
Check if a linked list is a palindrome by finding the middle, reversing the second half, then comparing.
March 19, 2026 Read →
Remove duplicate nodes from a sorted linked list in O(n) with a single pointer walk.
March 19, 2026 Read →
Delete a node given only access to that node by copying the next node value and skipping the next node.
March 19, 2026 Read →
Find the intersection node of two linked lists in O(n) O(1) by switching pointers at the end of each list.
March 19, 2026 Read →
Convert a linked list representing a binary number to its integer value using left-shift accumulation.
March 19, 2026 Read →
Remove all nodes with a given value from a linked list using a dummy head to handle edge cases cleanly.
March 19, 2026 Read →
Remove the nth node from the end in one pass using two pointers offset by n steps and a dummy head.
March 19, 2026 Read →
Swap every two adjacent nodes in a linked list without modifying node values using pointer rewiring.
March 19, 2026 Read →
Group all odd-indexed nodes before even-indexed nodes in O(n) time and O(1) space using two pointer chains.
March 19, 2026 Read →
Rotate a linked list to the right by k places by finding length, computing effective rotation, and rewiring.
March 19, 2026 Read →
Reorder a linked list into L0→Ln→L1→Ln-1 pattern by splitting at middle, reversing second half, then merging.
March 19, 2026 Read →
Add two numbers represented as reversed linked lists by simulating digit addition with carry propagation.
March 19, 2026 Read →
Add two numbers given in forward order by pushing digits to stacks, then building the result list in reverse.
March 19, 2026 Read →
Partition a linked list around value x into less-than and greater-than-or-equal chains, then join them.
March 19, 2026 Read →
Sort a linked list in O(n log n) time and O(log n) space using top-down merge sort with fast/slow split.
March 19, 2026 Read →
Remove all nodes that have duplicate numbers from a sorted linked list using a dummy head and skip logic.
March 19, 2026 Read →
Deep copy a linked list with random pointers using either a hash map or the O(1) space interleave technique.
March 19, 2026 Read →
Flatten a multilevel doubly linked list by inserting child sub-lists inline using DFS or an explicit stack.
March 19, 2026 Read →
Find the node where a cycle begins using Floyd's algorithm: detect meeting point, then reset one pointer to head.
March 19, 2026 Read →
Find the duplicate in an array of n+1 integers in O(1) space by treating indices as a linked list with Floyd's cycle detection.
March 19, 2026 Read →
Find the next greater value for each node in a linked list using a monotonic decreasing stack of indices.
March 19, 2026 Read →
Implement a doubly linked list with sentinel head and tail nodes for clean O(1) insertions and deletions.
March 19, 2026 Read →
Swap the kth node from the front with the kth node from the end by finding both with two pointers.
March 19, 2026 Read →
Remove consecutive nodes that sum to zero by tracking prefix sums in a map and relinking past zero-sum runs.
March 19, 2026 Read →
Split a linked list into k consecutive parts as evenly as possible, front parts get the extra nodes.
March 19, 2026 Read →
Reverse the portion of a linked list between positions left and right in one pass using careful pointer manipulation.
March 19, 2026 Read →
Find the maximum sum of twin nodes (node i + node n-1-i) by reversing the second half and comparing pairs.
March 19, 2026 Read →
Merge all nodes between 0s into a single node with their sum, modifying the list in-place.
March 19, 2026 Read →
Delete the middle node of a linked list using a prev-pointer variant of the fast/slow technique.
March 19, 2026 Read →
Reverse nodes in each even-length group of a linked list by counting group sizes and selectively reversing.
March 19, 2026 Read →
Insert a value into a sorted circular linked list by finding the correct position with careful edge case handling.
March 19, 2026 Read →
Count the number of connected components of a linked list that consist of nodes in a given set.
March 19, 2026 Read →
Flatten a binary tree in-place into a linked list following pre-order using the Morris traversal approach.
March 19, 2026 Read →
Convert a sorted linked list to a height-balanced BST by repeatedly finding the middle node as root.
March 19, 2026 Read →
Reverse every k nodes of a linked list recursively: check k nodes exist, reverse them, recurse on the rest.
March 19, 2026 Read →
Merge k sorted linked lists into one sorted list using a min-heap for O(n log k) time complexity.
March 19, 2026 Read →
Sort a linked list in O(n log n) time and O(1) space using bottom-up merge sort with doubling sublist sizes.
March 19, 2026 Read →
Build a balanced BST from a sorted list in O(n) by counting nodes, building in-order, and consuming list nodes.
March 19, 2026 Read →
Implement LRU Cache from scratch using a doubly linked list with sentinel nodes and a hash map for O(1) operations.
March 19, 2026 Read →
Design a browser history with visit, back, and forward operations using a doubly linked list for O(1) navigation.
March 19, 2026 Read →
Complete cheatsheet for Linked Lists: all 7 patterns, template code, Big O reference, and MAANG interview priority guide.
March 19, 2026 Read →
Master Segment Trees and Binary Indexed Trees: range sum/min/max queries, point updates, lazy propagation, and 5-language implementations.
March 19, 2026 Read →
Support point updates and range sum queries. BIT (Fenwick Tree) gives O(log n) both operations with elegant implementation.
March 19, 2026 Read →
Count smaller elements to the right of each element. Process from right to left; BIT tracks seen elements. Coordinate compress values to BIT indices.
March 19, 2026 Read →
Count pairs (i,j) where i<j and nums[i] > 2*nums[j]. Modified merge sort: during merge, count pairs across left/right halves.
March 19, 2026 Read →
Book events without double-booking. Use sorted dictionary to find previous and next events; check overlap with both.
March 19, 2026 Read →
Track coverage of half-open intervals. addRange, removeRange, queryRange. Sorted dictionary of disjoint intervals with merge/split logic.
March 19, 2026 Read →
Simulate falling squares, track tallest stack height. Coordinate compress x-coordinates, use segment tree with lazy propagation for range max.
March 19, 2026 Read →
Count subarray sums within [lower, upper]. Use prefix sums and merge sort: during merge count pairs of prefix sums with difference in range.
March 19, 2026 Read →
Count all LIS of maximum length. DP: track length and count. Segment tree on values enables O(n log n) solution.
March 19, 2026 Read →
Apply range shift operations to letters. Difference array: mark +1 at start and -1 at end+1, prefix sum gives net shift at each position.
March 19, 2026 Read →
Sum of rectangle region. Precompute 2D prefix sums: prefix[i][j] = sum of all cells from (0,0) to (i-1,j-1). Inclusion-exclusion for query.
March 19, 2026 Read →
Track maximum booking overlaps at any time. Difference array: +1 at start, -1 at end; running max of prefix sum. Lazy segment tree for dynamic range.
March 19, 2026 Read →
Find max rectangle sum <= k in 2D matrix. Fix row boundaries, compress to 1D array, use prefix sums + BIT/sorted set to find best subarray sum <= k.
March 19, 2026 Read →
Find longest subarray with sum <= k. Build prefix sums, use monotonic deque for decreasing prefix sums to efficiently find left boundaries.
March 19, 2026 Read →
For each element compute product of all other elements. Two-pass: left prefix products then multiply with right suffix products.
March 19, 2026 Read →
Complete Segment Tree and BIT cheatsheet: templates for BIT, segment tree, lazy propagation, 2D BIT, and problem index.
March 19, 2026 Read →
Master every stack and queue pattern: monotonic stack, BFS, two-stack tricks, deque, and design — with templates and full index of 50 problems.
March 19, 2026 Read →
Check if a string of brackets is valid by pushing open brackets and matching close brackets against the stack.
March 19, 2026 Read →
Implement a stack using one queue by rotating all elements after each push to bring the new element to the front.
March 19, 2026 Read →
Implement a queue using two stacks with amortized O(1) operations by lazily transferring from inbox to outbox.
March 19, 2026 Read →
Design a stack with O(1) getMin by maintaining a parallel min-tracking stack alongside the main stack.
March 19, 2026 Read →
Simulate a baseball scoring game using a stack to track valid scores and handle +, D, and C operations.
March 19, 2026 Read →
Compare two strings after applying backspace characters in O(1) space by scanning from right with skip counters.
March 19, 2026 Read →
Track the minimum number of operations to return to the main folder by simulating directory navigation with a depth counter.
March 19, 2026 Read →
Count ping requests within the last 3000ms using a queue that slides expired entries off the front.
March 19, 2026 Read →
Remove adjacent pairs of same letters with different cases using a stack to build the result character by character.
March 19, 2026 Read →
Find how many days until a warmer temperature using a monotonic decreasing stack of unresolved day indices.
March 19, 2026 Read →
Find the next greater element for each query in O(n+m) using a monotonic stack on nums2 and a lookup map.
March 19, 2026 Read →
Find the next greater element in a circular array by iterating twice (0 to 2n) and using a monotonic stack.
March 19, 2026 Read →
Calculate the stock price span (consecutive days <= today) using a monotonic stack that accumulates spans.
March 19, 2026 Read →
Remove k digits to form the smallest number by maintaining a monotonic increasing stack and greedy removal.
March 19, 2026 Read →
Decode a string with nested encodings like 3[a2[bc]] using two stacks: one for counts and one for partial strings.
March 19, 2026 Read →
Evaluate an RPN expression by pushing numbers and applying operators to the top two stack elements.
March 19, 2026 Read →
Find the maximum in each sliding window of size k using a monotonic decreasing deque storing indices.
March 19, 2026 Read →
Simulate asteroid collisions using a stack where right-moving asteroids wait and left-moving ones destroy smaller ones.
March 19, 2026 Read →
Sum the minimums of all subarrays by computing each element's contribution as the minimum using previous and next smaller element spans.
March 19, 2026 Read →
Calculate the score of balanced parentheses where () = 1 and AB = A+B and (A) = 2*A using a stack depth trick.
March 19, 2026 Read →
Find the minimum intervals to execute all tasks with cooldown n by greedily scheduling the most frequent task first.
March 19, 2026 Read →
Find minutes until all oranges rot using multi-source BFS starting from all initially rotten oranges simultaneously.
March 19, 2026 Read →
Count islands in a 2D grid using BFS or DFS to flood-fill connected land cells, marking them visited.
March 19, 2026 Read →
Detect if all courses can be finished (no cycle) using Kahn's algorithm: BFS on in-degree zero nodes.
March 19, 2026 Read →
Return a valid course order using Kahn's BFS topological sort, or empty array if a cycle exists.
March 19, 2026 Read →
Find the shortest word transformation sequence using BFS where each step changes exactly one character.
March 19, 2026 Read →
Evaluate a string expression with +, -, *, / using a stack that handles operator precedence without parentheses.
March 19, 2026 Read →
Detect a 132 pattern (i < j < k, nums[i] < nums[k] < nums[j]) using a monotonic stack scanning right to left.
March 19, 2026 Read →
Count visible people in a queue for each person using a monotonic decreasing stack scanning right to left.
March 19, 2026 Read →
Implement a circular queue using a fixed-size array with head and tail pointers and a size counter.
March 19, 2026 Read →
Find cells that can flow to both oceans by doing reverse BFS from each ocean's borders and finding the intersection.
March 19, 2026 Read →
Maximize score jumping through an array with window k by combining DP with a monotonic decreasing deque.
March 19, 2026 Read →
Find the shortest subarray with sum >= k using a monotonic deque on prefix sums for O(n) time.
March 19, 2026 Read →
Fill each empty room with its distance to nearest gate using simultaneous multi-source BFS from all gates.
March 19, 2026 Read →
Implement an iterator for a nested list using a stack that lazily expands nested lists as elements are consumed.
March 19, 2026 Read →
Remove k adjacent identical characters repeatedly using a stack that tracks (character, count) pairs.
March 19, 2026 Read →
Design a hit counter that returns hits in the past 5 minutes using a queue to expire old timestamps.
March 19, 2026 Read →
Find the largest rectangle in a histogram by computing left and right boundaries using a monotonic increasing stack.
March 19, 2026 Read →
Find the maximal rectangle in a binary matrix by building histogram heights row by row and applying largest rectangle.
March 19, 2026 Read →
Evaluate a basic expression with +, -, and parentheses using a stack to save and restore sign context.
March 19, 2026 Read →
Design a frequency stack with O(1) push and pop-max-frequency using a map of frequency to stack of elements.
March 19, 2026 Read →
Find the median dynamically as numbers are added using two heaps: a max-heap for the lower half and min-heap for upper.
March 19, 2026 Read →
Serialize a binary tree to a string using BFS level-order and deserialize back using a queue for reconstruction.
March 19, 2026 Read →
Calculate trapped rainwater volume using a monotonic stack that computes water in horizontal layers as bars are processed.
March 19, 2026 Read →
Complete cheatsheet for Stacks & Queues: all 7 patterns, template code, Big O reference, and MAANG interview priority guide.
March 19, 2026 Read →
Master every tree pattern: DFS traversals, BFS level-order, BST operations, LCA, path sum, and serialization — with templates and full index of 75 problems.
March 19, 2026 Read →
Find the maximum depth of a binary tree using recursive DFS (one line) or iterative BFS level counting.
March 19, 2026 Read →
Invert a binary tree by recursively swapping left and right children at every node.
March 19, 2026 Read →
Check if a binary tree is symmetric by comparing mirror subtrees with a two-pointer recursive approach.
March 19, 2026 Read →
Determine if a root-to-leaf path exists with a given sum using DFS that subtracts each node value from the target.
March 19, 2026 Read →
Check if two binary trees are identical by recursively comparing structure and node values.
March 19, 2026 Read →
Check if a binary tree is height-balanced by computing subtree heights and returning -1 early on imbalance.
March 19, 2026 Read →
Merge two binary trees by adding overlapping node values recursively, using existing nodes where possible.
March 19, 2026 Read →
Sum all BST values in [low, high] using BST property to prune entire subtrees outside the range.
March 19, 2026 Read →
Find a node with given value in a BST by navigating left or right based on the BST property.
March 19, 2026 Read →
Return values grouped by level using BFS with a queue, processing each level in a batch loop.
March 19, 2026 Read →
Traverse a binary tree in zigzag level order by toggling insertion direction at each level.
March 19, 2026 Read →
Find the rightmost node at each level using BFS and taking the last element seen at each depth.
March 19, 2026 Read →
Collect all root-to-leaf paths with a given sum using DFS backtracking, appending and removing the current node.
March 19, 2026 Read →
Find the diameter (longest path between any two nodes) using a depth function that tracks the maximum path through each node.
March 19, 2026 Read →
Validate a BST by passing down min and max bounds through DFS, ensuring every node falls strictly within its valid range.
March 19, 2026 Read →
Find the kth smallest element in a BST using inorder traversal (left-root-right) which visits nodes in sorted order.
March 19, 2026 Read →
Find the LCA of two nodes using post-order DFS: return root when found, propagate upward and split at the ancestor.
March 19, 2026 Read →
Find the LCA in a BST in O(h) by navigating left or right based on whether both nodes are in the same subtree.
March 19, 2026 Read →
Build a binary tree from preorder and inorder traversals by using the preorder root and inorder index to split left/right subtrees.
March 19, 2026 Read →
Count paths in a binary tree summing to target (not necessarily root-to-leaf) using a prefix sum frequency map.
March 19, 2026 Read →
Find and delete a node from a BST while maintaining BST properties using in-order successor.
March 19, 2026 Read →
Flatten a binary tree to a linked list in-place using pre-order traversal order.
March 19, 2026 Read →
Connect each node to its next right node using BFS level order or O(1) space pointer manipulation.
March 19, 2026 Read →
Find all nodes at distance K from a target node by building parent pointers then doing BFS.
March 19, 2026 Read →
Compute the total sum of all root-to-leaf numbers formed by concatenating digits along each path.
March 19, 2026 Read →
Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.
March 19, 2026 Read →
Count nodes where no node on the root-to-node path has a value greater than the node itself.
March 19, 2026 Read →
Replace each node value with the sum of all values greater than or equal to it using reverse in-order traversal.
March 19, 2026 Read →
Find all duplicate subtrees by serializing each subtree and using a hash map to detect duplicates.
March 19, 2026 Read →
Generate all structurally unique BSTs with values 1 to n using divide and conquer with memoization.
March 19, 2026 Read →
Trim a BST so all values lie within [low, high] by recursively pruning out-of-range subtrees.
March 19, 2026 Read →
Serialize a BST to a compact preorder string and reconstruct it using the min-max BST property.
March 19, 2026 Read →
Group tree nodes by vertical column then row, sorting by value within same position using BFS with coordinates.
March 19, 2026 Read →
Find path directions between two tree nodes by finding LCA then building paths from LCA to each target.
March 19, 2026 Read →
Verify a binary tree is complete using BFS: once a null child is seen, no more non-null nodes should follow.
March 19, 2026 Read →
Find and swap the two misplaced nodes in a BST using in-order traversal to detect the violations.
March 19, 2026 Read →
Maximize robbery from a tree-structured neighborhood where adjacent (parent-child) nodes cannot both be robbed.
March 19, 2026 Read →
Find minimum cameras to monitor all nodes using greedy bottom-up: prefer placing cameras at parents of uncovered leaves.
March 19, 2026 Read →
Count minimum moves to distribute coins evenly by tracking excess/deficit coins flowing through each edge.
March 19, 2026 Read →
Find the Kth ancestor of any tree node in O(log k) per query using binary lifting (sparse table DP).
March 19, 2026 Read →
Find the maximum path sum in a binary tree where the path can start and end at any node.
March 19, 2026 Read →
Serialize a binary tree to string and back using BFS level-order or DFS preorder with null markers.
March 19, 2026 Read →
Find the maximum sum of any BST subtree within a binary tree using post-order DFS returning subtree metadata.
March 19, 2026 Read →
Reconstruct a BST from its preorder traversal in O(n) using min-max bounds to place each node.
March 19, 2026 Read →
Collect leaves by height (distance from leaf) repeatedly, returning all leaves at each height level.
March 19, 2026 Read →
Count nodes in a complete binary tree in O(log^2 n) by comparing left and right heights to identify full subtrees.
March 19, 2026 Read →
Find minimum seconds to collect all apples in a tree by DFS: include a subtree path only if it contains apples.
March 19, 2026 Read →
Find the maximum |a - b| for any ancestor-descendant pair by tracking min and max values along each root-to-leaf path.
March 19, 2026 Read →
Find the longest zigzag path in a binary tree where you alternate left-right directions at each step.
March 19, 2026 Read →
Compute sum of distances from every node to all others in O(n) using two DFS passes with rerooting technique.
March 19, 2026 Read →
Count the number of structurally unique BSTs with n nodes using Catalan numbers and DP.
March 19, 2026 Read →
Perform level-order traversal of an N-ary tree using BFS, collecting all children at each level.
March 19, 2026 Read →
Remove all subtrees that do not contain a 1 by recursively returning null for subtrees with only zeros.
March 19, 2026 Read →
Find the level with the maximum sum using BFS level-order traversal to compute each level's total.
March 19, 2026 Read →
Find lexicographically smallest string from any leaf to root by collecting and comparing reversed paths.
March 19, 2026 Read →
Find time for infection to spread through entire tree from a start node by converting to graph then doing BFS.
March 19, 2026 Read →
Find minimum swaps to sort each level of a binary tree using BFS and cycle-detection in permutation sorting.
March 19, 2026 Read →
Implement an in-order BST iterator with O(h) space using a stack to simulate recursive in-order traversal.
March 19, 2026 Read →
Sum all root-to-leaf path sums in a tree encoded as 3-digit integers using a hashmap to decode tree structure.
March 19, 2026 Read →
Find k values closest to target in a BST using two in-order iterators (forward and reverse) with a two-pointer merge.
March 19, 2026 Read →
Transform a binary tree so every right child becomes a sibling and left child becomes parent using iterative rotation.
March 19, 2026 Read →
Find the inorder successor of a node in a BST when you have access to parent pointers.
March 19, 2026 Read →
Find second minimum value in a special binary tree where root is min and each node equals min of its children.
March 19, 2026 Read →
Build a preorder string representation of a binary tree using parentheses to show tree structure.
March 19, 2026 Read →
Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.
March 19, 2026 Read →
Sum all nodes at the deepest level of a binary tree using BFS to process level by level.
March 19, 2026 Read →
Determine if two nodes are cousins (same depth, different parents) using BFS to track depth and parent.
March 19, 2026 Read →
Count nodes in complete binary tree in O(log^2 n) by comparing left vs right subtree heights recursively.
March 19, 2026 Read →
Insert a value into a BST by traversing left/right based on comparisons until reaching a null position.
March 19, 2026 Read →
Traverse an N-ary tree in preorder and postorder using DFS with a stack or recursion.
March 19, 2026 Read →
Build a quad tree from a 2D grid by recursively checking if a region is uniform and splitting into four quadrants.
March 19, 2026 Read →
Rearrange a BST into a right-skewed tree with no left children using in-order traversal.
March 19, 2026 Read →
Count nodes where node value equals the average of all values in its subtree using post-order DFS returning sum and count.
March 19, 2026 Read →
Complete Trees section recap covering 9 core patterns, complexity guide, and interview problem index.
March 19, 2026 Read →
Master Tries: insert/search/prefix, word search II, autocomplete, XOR trie for max XOR, and bitwise trie patterns with 5-language implementations.
March 19, 2026 Read →
Implement a Trie with insert, search, and startsWith operations. Core data structure for all prefix-based problems.
March 19, 2026 Read →
Trie that supports wildcard '.' matching any character. DFS through trie when '.' encountered, trying all children.
March 19, 2026 Read →
Find all words from a list in a grid. Build trie from words, DFS on grid while traversing trie simultaneously to prune early.
March 19, 2026 Read →
Replace each word in sentence with its shortest root from dictionary. Insert roots into trie; for each sentence word find shortest matching prefix.
March 19, 2026 Read →
Find maximum XOR of any two numbers in array. Binary trie (bit by bit from MSB): for each number greedily choose opposite bit to maximize XOR.
March 19, 2026 Read →
After each character typed, return up to 3 lexicographically smallest matching products. Sort products, insert into trie, store sorted lists at each node.
March 19, 2026 Read →
Find longest word where all prefixes exist in dictionary. Trie: only follow nodes where is_end=True, track max depth.
March 19, 2026 Read →
Find pairs (i,j) where words[i]+words[j] is a palindrome. Insert reversed words into trie, for each word check palindromic suffix/prefix conditions.
March 19, 2026 Read →
Query if any word ends at the current stream position. Insert reversed words into trie; maintain suffix deque to match from current position backwards.
March 19, 2026 Read →
Find word with given prefix AND suffix. Insert 'suffix#word' for each suffix of each word into trie; query combines prefix+suffix search.
March 19, 2026 Read →
For each word, sum up how many other words share each of its prefixes. Trie with prefix count at each node; query each word's prefix sum.
March 19, 2026 Read →
Find all words that can be formed by concatenating two or more words from the same list. Build trie, then run word break DP on each word.
March 19, 2026 Read →
Encode word list as shortest string where each word is a suffix. Words that are suffixes of others need not be separately encoded. Use trie of reversed words.
March 19, 2026 Read →
Implement insert(key, val) and sum(prefix) returning sum of values for all keys with given prefix. Trie with value at end node.
March 19, 2026 Read →
Count words with given prefix. Simple trie with count at each node; reach prefix end and return count.
March 19, 2026 Read →
For each query (xi, mi), find max xi XOR with element ≤ mi. Offline: sort queries and elements by value, add elements up to mi, query trie.
March 19, 2026 Read →
Find the longest common prefix length between any number in arr1 and any number in arr2. Build trie from arr1 digits, query with arr2.
March 19, 2026 Read →
Overview of trie application variants: binary trie for XOR, reverse trie for suffix matching, counted trie for scoring, and offline trie processing.
March 19, 2026 Read →
Count distinct substrings. Naive: insert all suffixes into trie and count nodes. Optimal: suffix automaton or rolling hash.
March 19, 2026 Read →
Complete Tries cheatsheet: core operations, 5 patterns, binary trie for XOR, complexity table, and decision guide.
March 19, 2026 Read →
Master Two Pointers and Sliding Window patterns with 60 problems, 5-language solutions, and MAANG company tags.
March 19, 2026 Read →
Check if a string is a palindrome after removing non-alphanumeric characters using inward two pointers.
March 19, 2026 Read →
Reverse an array of characters in-place using the classic two-pointer swap technique.
March 19, 2026 Read →
Return squares of a sorted array in sorted order using two pointers that compare absolute values from both ends.
March 19, 2026 Read →
Remove all occurrences of val in-place using a write pointer pattern, returning the new length.
March 19, 2026 Read →
Remove duplicates in-place from a sorted array using a write pointer that only advances on unique elements.
March 19, 2026 Read →
Merge two sorted arrays in-place from the end to avoid overwriting elements using three pointers.
March 19, 2026 Read →
Check if string s is a subsequence of t using a greedy two-pointer scan that matches characters in order.
March 19, 2026 Read →
Find the maximum number of consecutive 1s achievable by flipping at most k zeros, using a variable sliding window.
March 19, 2026 Read →
Count days with fixed-size window sums above upper and below lower thresholds using a sliding fixed window.
March 19, 2026 Read →
Compute the running sum of a 1D array where each element is the sum of itself and all previous elements.
March 19, 2026 Read →
Find the longest substring without duplicate characters using a HashSet-backed shrinkable sliding window.
March 19, 2026 Read →
Find the longest substring with at most k character replacements by tracking the maximum frequency char in the window.
March 19, 2026 Read →
Check if any permutation of s1 is a substring of s2 using a fixed-size sliding window with character frequency comparison.
March 19, 2026 Read →
Find the maximum fruits you can collect starting from any tree with two baskets (at most 2 distinct fruit types) using a sliding window.
March 19, 2026 Read →
Find the maximum sum of a subarray with all unique elements using a sliding window backed by a HashSet.
March 19, 2026 Read →
Find the smallest subarray with sum >= target using a variable sliding window that shrinks from the left when the condition is met.
March 19, 2026 Read →
Count tuples (i,j,k,l) where nums1[i]+nums2[j]+nums3[k]+nums4[l]=0 by hashing all pairs from first two arrays.
March 19, 2026 Read →
Maximize water trapped between two vertical lines using inward two pointers that always move the shorter line inward.
March 19, 2026 Read →
Find minimum boats to save everyone where each boat carries at most 2 people with total weight <= limit, using sort + greedy two pointers.
March 19, 2026 Read →
Find all unique triplets summing to zero by sorting and using two pointers for each fixed element with careful duplicate skipping.
March 19, 2026 Read →
Find two numbers summing to target in a 1-indexed sorted array using inward two pointers in O(n) time O(1) space.
March 19, 2026 Read →
Count contiguous subarrays with product < k using a sliding window that divides from the left when product exceeds the limit.
March 19, 2026 Read →
Maximize card points taken from both ends of an array by finding the minimum-sum subarray of size n-k in the middle.
March 19, 2026 Read →
Count subarrays with exactly k odd numbers using the at-most(k) minus at-most(k-1) sliding window formula.
March 19, 2026 Read →
Count binary subarrays with exactly the given sum using prefix sum with HashMap or the atMost(k)-atMost(k-1) trick.
March 19, 2026 Read →
Find the maximum frequency of any element after at most k increments by sorting and using a sliding window with a running sum.
March 19, 2026 Read →
Find minimum operations to reduce X to zero from either end by finding the longest middle subarray with sum = total-X.
March 19, 2026 Read →
Find the longest mountain subarray (strictly increasing then decreasing) using two separate forward scans for up and down slopes.
March 19, 2026 Read →
Find the longest turbulent subarray where comparisons alternate between > and < using two-pointer direction tracking.
March 19, 2026 Read →
Count subarrays with exactly K distinct integers using the mathematical trick: exactly(K) = atMost(K) - atMost(K-1).
March 19, 2026 Read →
Find the minimum length substring to replace so that a string of QWER has equal frequencies, using a shrinkable two-pointer approach.
March 19, 2026 Read →
Find minimum character flips to make a binary string alternating by applying a fixed circular sliding window of size n.
March 19, 2026 Read →
Find the maximum number of vowels in any substring of length k using a fixed sliding window with vowel count.
March 19, 2026 Read →
Find minimum swaps to group all 1s together in a circular binary array using a fixed-size sliding window equal to the count of 1s.
March 19, 2026 Read →
Find minimum minutes to collect at least k of each character from ends by finding the longest middle window that can be excluded.
March 19, 2026 Read →
Maximize customer satisfaction by finding the best k-minute window for the bookstore owner to stay non-grumpy.
March 19, 2026 Read →
Find the minimum difference between the max and min of any k scores by sorting and using a fixed window of size k.
March 19, 2026 Read →
Find the maximum length substring you can transform from s to t within a given cost budget using a sliding window on character change costs.
March 19, 2026 Read →
Count substrings containing at least one a, b, and c using the last-seen indices shortcut for O(n) time.
March 19, 2026 Read →
Count subarrays with sum divisible by k using prefix sum modulo k and a frequency map of remainders.
March 19, 2026 Read →
Find k closest integers to x in a sorted array using binary search to locate the optimal left boundary of the window.
March 19, 2026 Read →
Count subarrays where min=minK and max=maxK using a single pass tracking the last invalid position and last positions of minK and maxK.
March 19, 2026 Read →
Find the maximum consecutive ones in a binary array when you can flip at most k zeros, identical to the Max Consecutive Ones III pattern.
March 19, 2026 Read →
Sort only the vowels in a string while keeping consonants in place by extracting vowels, sorting, then reinserting.
March 19, 2026 Read →
Find the minimum window in s that contains t as a subsequence by using a forward pass to find a valid window then backward pass to minimize it.
March 19, 2026 Read →
Count subarrays where the median is exactly k by converting the problem to counting balanced prefix sequences around k.
March 19, 2026 Read →
Find the median of each sliding window of size k using two heaps (max-heap for lower half, min-heap for upper half) with lazy deletion.
March 19, 2026 Read →
Find all starting indices of substrings that are concatenations of all given words using a sliding window for each possible word-aligned start.
March 19, 2026 Read →
Find the minimum number of consecutive cards that contain a matching pair using a HashMap tracking last seen positions.
March 19, 2026 Read →
Count subarrays where score = sum × length is less than k using a shrinkable sliding window with running sum.
March 19, 2026 Read →
Find the smallest window in s containing all characters of t using a have/need counter to track when the window is valid.
March 19, 2026 Read →
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque of indices.
March 19, 2026 Read →
Find the shortest subarray with sum >= k, handling negative numbers correctly using a monotonic deque on prefix sums.
March 19, 2026 Read →
Find the longest substring containing at most 2 distinct characters using a variable sliding window with a character count map.
March 19, 2026 Read →
Find the longest contiguous subarray of 1s after deleting exactly one element using a sliding window allowing at most one zero.
March 19, 2026 Read →
Sort an array of 0s, 1s, and 2s in one pass using the Dutch National Flag 3-pointer algorithm.
March 19, 2026 Read →
Check if a string can become a palindrome by deleting at most one character using recursive two-pointer palindrome checking.
March 19, 2026 Read →
Check if an array can be split into three consecutive parts with equal sum using a greedy counting approach.
March 19, 2026 Read →
Calculate trapped rainwater using optimal two-pointer approach that tracks left and right maximums without extra space.
March 19, 2026 Read →
Complete cheatsheet of Two Pointers and Sliding Window patterns with template code, problem index, and MAANG priority list.
March 19, 2026 Read →
Complete backtracking reference: universal template, 7 pattern recognition cues, complexity guide, and top 30 interview problems.
May 29, 2025 Read →
Color a graph with m colors (no adjacent same color) and find Hamiltonian paths using backtracking with neighbor constraint checking.
May 28, 2025 Read →
Remove minimum invalid parentheses to produce all valid results. BFS approach for minimum removals, DFS for complete enumeration.
May 27, 2025 Read →
Solve Beautiful Arrangement and similar constraint-based permutation problems with backtracking and precomputed valid positions.
May 26, 2025 Read →
Compare backtracking and DP approaches for subset sum: when to use each, conversion to knapsack, and bitset optimization.
May 25, 2025 Read →
Solve tiling (domino, triomino) and optimal string splitting problems combining backtracking insight with DP optimization.
May 24, 2025 Read →
Solve the Knight's Tour problem and maze path finding using backtracking with Warnsdorff heuristic for dramatic speedup.
May 23, 2025 Read →
Solve partition backtracking problems: equal sum subset (NP-hard, backtrack with pruning) and k equal sum subsets.
May 22, 2025 Read →
Generate valid IP addresses from digit strings and all sentence segmentations with word break backtracking.
May 21, 2025 Read →
Generate all expressions by inserting +, -, * between digits to reach target. Track running value and last operand for multiplication.
May 20, 2025 Read →
Partition a string into all-palindrome substrings using backtracking with O(n^2) precomputed palindrome DP table for O(1) checks.
May 19, 2025 Read →
Generate all letter combinations from phone number digits using backtracking. Classic tree exploration with fixed branching factor.
May 18, 2025 Read →
Search for words in a character grid using DFS backtracking. Word Search II uses a Trie for simultaneous multi-word search.
May 17, 2025 Read →
Generate all valid parentheses combinations of length 2n using open/close count tracking. Classic backtracking interview problem.
May 16, 2025 Read →
Solve a 9x9 Sudoku board with backtracking enhanced by constraint propagation (arc consistency) for dramatic pruning.
May 15, 2025 Read →
Solve the N-Queens problem with backtracking using column/diagonal conflict tracking. O(n!) with early pruning.
May 14, 2025 Read →
Generate all k-combinations and find combinations summing to target. Master the start-index pattern to avoid duplicates.
May 13, 2025 Read →
Generate all n! permutations using backtracking with used[] array or in-place swap. Handles duplicates by sorting + skipping.
May 12, 2025 Read →
Generate all 2^n subsets of a set using backtracking (include/exclude) and bit masking. Handles duplicates with sorting + skip.
May 11, 2025 Read →
Master recursion and backtracking for DSA interviews: 7 core patterns, time complexity analysis, pruning strategies, and top 30 problems.
May 10, 2025 Read →
Complete reference for math and number theory DSA patterns: algorithm selection guide, complexity table, and top 25 interview problems.
April 29, 2025 Read →
Apply the inclusion-exclusion principle to count elements satisfying union of conditions. Solves divisibility, coverage, and derangement problems.
April 28, 2025 Read →
Master randomized DSA algorithms: reservoir sampling for streams, quickselect for O(n) kth element, and random shuffling.
April 27, 2025 Read →
Master combinatorial game theory: Nim XOR strategy, Grundy (nimber) values, and Sprague-Grundy theorem for composite games.
April 26, 2025 Read →
Tackle geometry problems in coding interviews: cross product, point-in-polygon, line intersection, and Graham scan convex hull.
April 25, 2025 Read →
Apply probability theory and expected value DP to competitive programming: dice problems, random walks, and geometric distribution.
April 24, 2025 Read →
Prevent integer overflow in competitive programming: safe multiplication, __int128, binary search on answers, and floating-point gotchas.
April 23, 2025 Read →
Build range query structures in O(sqrt n) per query with block decomposition. Simpler alternative to segment trees.
April 22, 2025 Read →
Solve systems of modular congruences with the Chinese Remainder Theorem. Fundamental for cryptography and competitive math.
April 21, 2025 Read →
Explore classic number sequences: Fibonacci, Lucas, Pell, tribonacci, with DP and matrix approaches.
April 20, 2025 Read →
Master bitwise operations for DSA: XOR tricks, Brian Kernighan bit counting, subset enumeration, and bitmask DP.
April 19, 2025 Read →
Solve linear recurrences like Fibonacci in O(log n) using matrix exponentiation. Essential for DP optimization on large n.
April 18, 2025 Read →
Explore digit manipulation, perfect/abundant numbers, Armstrong numbers, and common math interview patterns.
April 17, 2025 Read →
Compute combinations nCr efficiently with precomputed factorials, Pascal's triangle for small n, and Catalan numbers for tree/parenthesis counting.
April 16, 2025 Read →
Compute Euler's totient phi(n) for cryptography and modular inverse applications. Sieve variant for all values up to n.
April 15, 2025 Read →
Factor integers efficiently with trial division O(sqrt n), SPF sieve O(log n), and understand when each approach is optimal.
April 14, 2025 Read →
Master modular arithmetic for competitive programming: binary exponentiation O(log n), modular inverse, and Chinese Remainder Theorem.
April 13, 2025 Read →
Master GCD/LCM with Euclidean algorithm O(log n) and the Extended Euclidean for modular inverse computation.
April 12, 2025 Read →
Generate all primes up to n in O(n log log n) with the Sieve of Eratosthenes. Includes segmented sieve and prime factorization variants.
April 11, 2025 Read →
Master mathematical algorithms for DSA: primes, GCD, modular arithmetic, combinatorics, and fast exponentiation with 5-language implementations.
April 10, 2025 Read →
Master advanced graph algorithms: Kruskal and Prim MST, Tarjan SCC, articulation points, bridges, Floyd-Warshall all-pairs shortest path, and A* search.
March 1, 2025 Read →
Find the minimum spanning tree of a weighted graph using Kruskal's algorithm. Sort edges by weight, use Union-Find to avoid cycles. O(E log E) time.
March 1, 2025 Read →
Build the minimum spanning tree using Prim's algorithm: start from any vertex, greedily expand by always adding the minimum-weight crossing edge using a min-heap.
March 1, 2025 Read →
Find all strongly connected components in a directed graph using Tarjan's single-pass DFS algorithm with discovery time, low-link values, and a stack.
March 1, 2025 Read →
Find all bridge edges and articulation point vertices in an undirected graph using a single DFS pass with discovery time and low-link tracking.
March 1, 2025 Read →
Compute shortest paths between all pairs of vertices using Floyd-Warshall's O(V³) DP. Handles negative weights and detects negative cycles.
March 1, 2025 Read →
Compute single-source shortest paths in graphs with negative weight edges using Bellman-Ford. V-1 relaxation passes detect negative cycles on the Vth pass.
March 1, 2025 Read →
A* combines Dijkstra's correctness with a heuristic to guide search toward the goal. Uses f(n)=g(n)+h(n) priority. Optimal when heuristic is admissible.
March 1, 2025 Read →
Advanced topological sort: DFS-based with 3-color marking for cycle detection, Kahn's BFS approach, and applications in course scheduling, build systems, and task ordering.
March 1, 2025 Read →
Advanced Dijkstra patterns: state-space Dijkstra for problems with extra constraints like K stops, fuel limit, or restricted nodes. The key is augmenting the state beyond just the node.
March 1, 2025 Read →
Check if a graph is bipartite using BFS 2-coloring. A graph is bipartite if and only if it contains no odd-length cycles — equivalent to being 2-colorable.
March 1, 2025 Read →
Connect all n points with minimum total Manhattan distance cost. Models the problem as a complete graph MST and applies optimised Prim's without building all O(n²) edges explicitly.
March 1, 2025 Read →
Find the path from source to destination minimising the maximum edge weight. Binary search on the answer + BFS/DFS connectivity check. O(E log W) total.
March 1, 2025 Read →
Count the number of shortest paths from source to destination using modified Dijkstra that tracks both minimum distance and path count simultaneously.
March 1, 2025 Read →
LeetCode 1192: Find all critical edges (bridges) in a network. A connection is critical if removing it disconnects the network. Uses Tarjan's bridge algorithm.
March 1, 2025 Read →
Find the itinerary using all flight tickets exactly once (Eulerian path). Uses Hierholzer's algorithm: DFS with post-order insertion into result — the only graph algorithm that uses post-order for path construction.
March 1, 2025 Read →
Find the minimum time to swim from (0,0) to (n-1,n-1) where you can only move to a cell when time >= cell value. Two approaches: Dijkstra O(n² log n) and binary search + BFS O(n² log n).
March 1, 2025 Read →
Find the longest path in a directed acyclic graph using DFS with memoisation. Since cycles are absent, DFS never revisits nodes, making top-down DP straightforward.
March 1, 2025 Read →
Introduction to network flow: max flow problem, Ford-Fulkerson algorithm with BFS (Edmonds-Karp), max-flow min-cut theorem, and applications in matching and connectivity.
March 1, 2025 Read →
Complete recap of all 20 advanced graph problems with algorithm selection guide, complexity comparison, and pattern recognition cues.
March 1, 2025 Read →
Master advanced string algorithms: KMP failure function for O(n) pattern matching, Z-algorithm for all prefix matches, Rabin-Karp rolling hash, and suffix arrays for substring queries.
March 1, 2025 Read →
Implement KMP string search: build the failure function (LPS array) in O(m) then search in O(n). Never re-examines matched characters unlike naive search.
March 1, 2025 Read →
The Z-algorithm computes Z[i] = length of the longest substring starting at i that matches a prefix of the string. O(n) time, elegant and powerful for pattern search.
March 1, 2025 Read →
Rabin-Karp uses a rolling polynomial hash to match patterns in O(n+m) expected time. The key is updating the hash in O(1) as the window slides.
March 1, 2025 Read →
Find the longest palindromic substring in O(n) using Manacher's algorithm. Expands palindromes using a mirror trick to avoid redundant work.
March 1, 2025 Read →
Precompute polynomial prefix hashes to compare any two substrings in O(1). Enables O(n log n) LCP computation and O(n) duplicate detection.
March 1, 2025 Read →
Build a suffix array in O(n log²n) using doubling sort. Enables O(m log n) substring search, longest common substring, and number of distinct substrings.
March 1, 2025 Read →
Find the longest common substring between two strings. DP approach O(nm), binary search + rolling hash O((n+m) log(n+m)).
March 1, 2025 Read →
Core string DP patterns: edit distance (Wagner-Fischer), longest common subsequence, interleaving strings, and regular expression matching.
March 1, 2025 Read →
Group anagrams, find anagram indices, and count anagram occurrences. Three approaches: sort key O(nk log k), frequency tuple O(nk), and sliding window O(n+k).
March 1, 2025 Read →
Comprehensive palindrome problem coverage: valid palindrome check, longest palindromic substring (three methods), count palindromic substrings, and palindrome partitioning.
March 1, 2025 Read →
Word Search I and II solved with DFS backtracking. Word Search II uses a Trie to prune the search space from O(N·4^L) per word to O(N·4^L) total for all words.
March 1, 2025 Read →
Design an encode/decode scheme for a list of strings. Length-prefix encoding (4-byte header per string) is collision-proof unlike delimiter-based approaches.
March 1, 2025 Read →
Add minimum characters to the front of a string to make it a palindrome. KMP trick: concatenate s + '#' + rev(s), find the LPS value at the last position.
March 1, 2025 Read →
Count the number of distinct substrings using the suffix array and LCP array. Total substrings minus sum of LCP values gives distinct count in O(n log n).
March 1, 2025 Read →
Implement run-length encoding, string compression in-place, and decode compressed strings. Tests two-pointer technique and string manipulation.
March 1, 2025 Read →
Advanced trie applications beyond basic insert/search: binary trie for XOR maximization, palindrome pairs detection, and stream search using Aho-Corasick automaton concept.
March 1, 2025 Read →
High-frequency string problems from Meta and Google interviews: valid parentheses, longest substring without repeating characters, zigzag conversion, and string to integer.
March 1, 2025 Read →
Aho-Corasick automaton matches all patterns simultaneously in O(n+m+z) where z is the number of matches. Builds failure links on a trie for efficient multi-pattern search.
March 1, 2025 Read →
Complete recap of all 20 string algorithm problems: pattern recognition guide, algorithm selection, and complexity reference.
March 1, 2025 Read →
Master the mock interview process: how to structure 2-hour sessions, simulate real conditions, analyse performance, and track improvement week over week.
February 20, 2025 Read →
Week 1 mock session: two carefully chosen easy/medium problems designed to build communication habits. Full problem walkthrough with example think-aloud scripts.
February 20, 2025 Read →
Week 2 mock: solve medium problems then optimize. Practice the full interview loop of brute force → optimal → follow-up questions. Includes common interviewer follow-up prompts.
February 20, 2025 Read →
Week 3 mock focuses on hard problems. Strategy: get a working solution in 35 minutes, optimize in remaining 15. Includes triage framework for when you're stuck on a hard problem.
February 20, 2025 Read →
Full company-specific mock sessions. Each simulation replicates the actual interview format, problem difficulty distribution, and evaluation criteria of Google, Meta, and Amazon.
February 20, 2025 Read →
Week 5 combines system design with coding. Design a system at high level, then implement a core component in code. Mirrors senior-level interview formats at all major companies.
February 20, 2025 Read →
How to extract maximum learning from each mock session. Covers error categorisation, pattern analysis, and a weekly improvement cycle that compounds over 5 weeks.
February 20, 2025 Read →
Exact time allocation for a 45-minute coding interview. How to avoid common time traps, recover from getting stuck, and always have something to show at the end.
February 20, 2025 Read →
Master the STAR method for behavioral interviews. Includes 10 must-prepare stories, how to tie them to DSA/technical decisions, and company-specific LP alignment.
February 20, 2025 Read →
Map Amazon's 16 Leadership Principles to coding interview behaviors. Know which LP each behavioral question targets, and how to weave LP language naturally into technical answers.
February 20, 2025 Read →
Google's interview process: Googleyness criteria, coding expectations, and how to prepare for the unique 'How would you improve Google Maps?' style questions.
February 20, 2025 Read →
Meta's interview process: core values evaluation, coding speed expectations, and preparation strategies for Meta's unique product-focused behavioral questions.
February 20, 2025 Read →
A repeatable 45-minute framework for system design interviews. Covers requirements gathering, capacity estimation, high-level design, deep dive, and trade-off discussion.
February 20, 2025 Read →
The 15 most common coding interview mistakes that cost candidates the offer. Each mistake includes the root cause, what it signals to the interviewer, and the exact fix.
February 20, 2025 Read →
The complete 7-day plan for the week before your interview. Daily focus areas, what to review, what to skip, and how to peak on interview day.
February 20, 2025 Read →
The complete interview readiness cheatsheet: pattern recognition guide, complexity reference, STAR story index, system design vocabulary, and company-specific tips all in one place.
February 20, 2025 Read →
Strategic guide to company-specific DSA preparation: Google's focus on graphs and DP, Meta's emphasis on arrays and trees, Amazon's leadership principles alignment with system design and BFS.
February 15, 2025 Read →
Search for a target in a matrix where each row and column is sorted. O(m+n) solution using top-right corner elimination — a classic Google interview problem.
February 15, 2025 Read →
Derive character ordering from a sorted alien dictionary using topological sort. Build a directed graph from adjacent word comparisons and apply Kahn's BFS algorithm.
February 15, 2025 Read →
Find the maximum in every sliding window of size k using a monotonic decreasing deque. O(n) solution that Google uses to test understanding of amortised data structures.
February 15, 2025 Read →
Find the smallest substring of s containing all characters of t using an expanding/contracting two-pointer window with frequency counting. O(n) time.
February 15, 2025 Read →
Implement an iterator for a nested list that flattens it lazily. Meta favors this for testing iterator design, stack usage, and lazy evaluation.
February 15, 2025 Read →
Serialize a binary tree to a string and deserialize it back. Meta loves this problem for testing tree traversal and string parsing. Both BFS and preorder DFS approaches shown.
February 15, 2025 Read →
Implement a read() function using a read4() primitive. Two variants: read once and read multiple times. Tests buffer management and pointer arithmetic.
February 15, 2025 Read →
Count islands after each addLand operation using incremental Union-Find. Each new land cell potentially merges with up to 4 neighbors — classic Amazon system-at-scale problem.
February 15, 2025 Read →
Design a stream that always returns the kth largest element after each add. Uses a min-heap of size k — the top is always the kth largest.
February 15, 2025 Read →
Find the minimum intervals to complete all tasks given cooldown n. Greedy with max-heap: always execute most frequent available task, idle only when forced.
February 15, 2025 Read →
Find the longest substring with at most k distinct characters using a sliding window with a character frequency map. O(n) time.
February 15, 2025 Read →
Generate all combinations of well-formed parentheses of given n pairs using backtracking. Track open and close counts to prune invalid branches early.
February 15, 2025 Read →
Merge k sorted linked lists into one sorted list using a min-heap. O(n log k) time by always extracting the current minimum across all list heads.
February 15, 2025 Read →
Count the number of inversions in an array (pairs where i < j but arr[i] > arr[j]) using modified merge sort in O(n log n). Google uses this to test deep algorithm understanding.
February 15, 2025 Read →
Count subarrays with sum equal to k using prefix sums and a hashmap. O(n) time by tracking how many times each prefix sum has occurred.
February 15, 2025 Read →
Find the k most frequent elements using a max-heap or bucket sort. O(n) bucket sort approach using frequency as bucket index — faster than O(n log n) heap.
February 15, 2025 Read →
Return the values visible from the right side of a binary tree — the last node of each BFS level. O(n) BFS with level tracking.
February 15, 2025 Read →
Comprehensive coverage of Two Sum, Two Sum II (sorted), 3Sum, and 4Sum. Amazon frequently tests these variants to gauge understanding of hashmap vs two-pointer trade-offs.
February 15, 2025 Read →
Return all ways to segment a string into dictionary words. Combines DP validity check with DFS+memo backtracking to avoid TLE on valid inputs.
February 15, 2025 Read →
Merge accounts sharing common email addresses using Union-Find. Group emails by owner, merge accounts with shared emails, sort each merged group.
February 15, 2025 Read →
Calculate how much water can be trapped in a 3D height matrix. Uses a min-heap BFS starting from the boundary, always processing the lowest border cell to determine water trapped inside.
February 15, 2025 Read →
Find the median of two sorted arrays in O(log(min(m,n))) time using binary search on partition points. A classic hard problem testing deep binary search understanding.
February 15, 2025 Read →
Create a deep copy of an undirected graph using DFS with a HashMap to track visited/cloned nodes. Meta tests this to evaluate graph traversal and pointer manipulation.
February 15, 2025 Read →
Complete recap of all 24 company-tagged problems with pattern classification, company attribution, and key insights. Use as a final review checklist before company-specific interviews.
February 15, 2025 Read →
Master system design problems that test data structure knowledge: LRU/LFU caches, Twitter feed, file systems, and 15+ design problems with full implementations.
February 10, 2025 Read →
Implement an LRU (Least Recently Used) cache with O(1) get and put using a doubly linked list and hashmap. Full 5-language solutions.
February 10, 2025 Read →
Implement an LFU cache with O(1) get and put. Uses two hashmaps and per-frequency doubly linked lists to track access frequency and recency simultaneously.
February 10, 2025 Read →
Design a simplified Twitter where users post tweets and follow each other, with getNewsFeed returning the 10 most recent tweets from followed users using a min-heap merge.
February 10, 2025 Read →
Implement a file system that creates paths and associates values with them. Uses a Trie or HashMap to map full paths to values with O(L) operations.
February 10, 2025 Read →
Design a hit counter that counts hits in the last 5 minutes using a deque-based sliding window or circular buffer with O(1) amortised operations.
February 10, 2025 Read →
Design a key-value store that returns values at or before a given timestamp. Uses a hashmap of sorted (timestamp, value) lists with binary search for O(log n) get.
February 10, 2025 Read →
Design a search autocomplete system that returns top 3 historical queries matching the current prefix, sorted by frequency then lexicographically. Uses a Trie with per-node frequency maps.
February 10, 2025 Read →
Design a browser with visit, back, and forward navigation. Uses two stacks (or a doubly-ended array with pointer) for O(1) visit and O(steps) navigation.
February 10, 2025 Read →
Design a leaderboard that tracks player scores, supports score additions, top K sum queries, and player resets using a hashmap with sorted aggregation.
February 10, 2025 Read →
Simulate a snake game on a grid where the snake eats food to grow and dies if it hits walls or itself. Uses a deque for O(1) head/tail and a set for O(1) body collision checks.
February 10, 2025 Read →
Implement a skip list from scratch supporting search, add, and erase in O(log n) expected time. Uses layered linked lists with probabilistic level assignment.
February 10, 2025 Read →
Design a log storage system that retrieves log IDs within a timestamp range at a specified granularity (Year, Month, Day, Hour, Minute, Second).
February 10, 2025 Read →
Design a phone directory managing available and allocated numbers with O(1) get, check, and release using a queue of free numbers and a boolean availability array.
February 10, 2025 Read →
Design an in-memory key-value database that supports set, get, delete, and rank operations. Demonstrates combining hashmaps with sorted structures for efficient multi-key queries.
February 10, 2025 Read →
Implement a stack that supports push, pop, top, and retrieving the minimum element in O(1) time using an auxiliary min-stack that tracks minimums at each level.
February 10, 2025 Read →
Maintain a running median from a data stream using two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalancing after each insertion.
February 10, 2025 Read →
Implement a circular queue (ring buffer) with fixed capacity supporting enQueue, deQueue, Front, Rear, isEmpty, and isFull in O(1) time using head and tail pointers.
February 10, 2025 Read →
Design a URL shortener like TinyURL that encodes long URLs to short codes and decodes them back. Uses base-62 encoding with a counter or random string generation.
February 10, 2025 Read →
Design a parking system with big, medium, and small spaces. O(1) addCar checks if space is available and decrements the counter, returning whether the car was parked.
February 10, 2025 Read →
Complete recap of all 20 system design DSA problems: pattern classification, time complexities, key data structures, and decision framework for choosing the right design approach.
February 10, 2025 Read →