Learn how to find the next greater node in a linked list using a monotonic stack in O(n) time. A popular interview question at Amazon and Adobe that tests your stack intuition and linked list traversal skills.
A deep-dive into implementing a linked list from scratch — a classic data structures interview question at Amazon, Google, and Microsoft that tests your true understanding of pointers, node management, and edge case handling.
Master swapping the kth node from start and end in a linked list using the two-pointer technique. A clean O(n) interview question asked at Amazon and Bloomberg that tests linked list traversal confidence and pointer discipline.
Learn how to remove consecutive nodes that sum to zero from a linked list using a prefix sum hashmap in two passes. A tricky interview problem asked at Google and Amazon that combines linked list manipulation with the classic prefix sum technique.
Learn how to split a linked list into k roughly equal parts in O(n) time using integer division and remainder math. A clean medium interview problem asked at Amazon and Facebook that tests linked list traversal and arithmetic reasoning.
Master reversing a subrange of a linked list in-place in a single pass. A classic interview problem at Facebook, Microsoft, and Amazon that tests your pointer manipulation skills and ability to handle complex multi-pointer state.
Find the maximum twin sum of a linked list in O(n) time and O(1) space by reversing the second half and comparing node pairs. A modern LeetCode 75 problem asked at Amazon and Google that combines fast-slow pointers with in-place list reversal.
Learn how to merge all nodes between consecutive zeros in a linked list into a single sum node in O(n) time and O(1) space. A clean simulation problem from LeetCode 2181 that tests in-place pointer manipulation and linked list traversal confidence.
Learn how to delete the middle node of a linked list in one pass using a clever modification of the fast/slow pointer technique. A LeetCode 75 problem asked at Amazon and Google that tests your understanding of the tortoise-and-hare algorithm.
Learn how to reverse nodes in each even-length group of a linked list by carefully counting group sizes and applying in-place reversal. A moderately tricky interview problem at Amazon and Google that tests group traversal and selective reversal skills.
Master the three cases needed to insert a value into a sorted circular linked list correctly. A classic interview problem at Google, Facebook, and Amazon that tests your ability to handle circular structure edge cases and write bug-free pointer manipulation code.
Count the number of connected components in a linked list defined by a given set of values using a single traversal and O(1) HashSet lookups. A clean O(n) interview problem at Google, Amazon, and Bloomberg that tests your ability to convert a graph concept into a simple linear scan.
Learn three ways to flatten a binary tree to a pre-order linked list in-place, including the O(1) space Morris-style approach. A classic interview problem at Microsoft, Amazon, and Google that bridges tree and linked list manipulation.
Convert a sorted linked list to a height-balanced binary search tree using fast/slow pointers to find the midpoint recursively. A classic divide-and-conquer interview problem at Amazon, Google, and Microsoft that bridges linked list and BST skills.
Implement a browser history data structure with visit, back, and forward operations using a doubly linked list for O(1) navigation. A practical design interview problem at Amazon, Microsoft, and Google that tests your ability to model real-world state with linked list pointers.
A complete tour of the seven advanced graph patterns FAANG interviewers test most: Kruskal and Prim MST, Tarjan SCC, bridges and articulation points, Floyd-Warshall all-pairs shortest path, Bellman-Ford with negative cycles, and A-star heuristic search. One pattern recognition guide that turns every advanced graph problem into a routine implementation.
LC 1584 Minimum Cost to Connect All Points and LC 1135 Connecting Cities are MST problems straight from the FAANG playbook. Master Kruskal: sort edges by weight, accept the cheapest edge that does not form a cycle using Union-Find, and prove correctness via the cut property in one sentence.
Master Prim's algorithm for Minimum Spanning Tree: grow a single tree from any starting vertex by repeatedly attaching the cheapest crossing edge using a min-heap. The dense-graph counterpart to Kruskal, asked at Google, Amazon, and Microsoft.
Master the Floyd-Warshall algorithm: a triple-nested DP that computes shortest paths between every pair of vertices in O(V^3), supports negative edges, and detects negative cycles. The interview workhorse for dense graphs and small V, asked at Google, Amazon, and Microsoft.
Master Bellman-Ford: relax every edge V-1 times to compute single-source shortest paths even with negative edges, and detect negative cycles in one extra pass. The algorithm behind LeetCode 787 Cheapest Flights Within K Stops, asked at Google, Amazon, and Meta.
Master A* search: a heuristic-guided best-first search that finds optimal shortest paths far faster than Dijkstra by combining actual distance g(n) with an admissible estimate h(n). The interview pattern behind LeetCode 1091 Shortest Path in Binary Matrix and the algorithm powering Google Maps, game AI, and robotics navigation.
Master bipartite checking and graph coloring: a single BFS or DFS pass that 2-colors a graph and proves it is bipartite, or finds an odd cycle. The pattern behind LeetCode 785 Is Graph Bipartite and LeetCode 886 Possible Bipartition, asked at Google, Meta, and Amazon.
Master LeetCode 1584 Min Cost to Connect All Points: model the n^2 implicit edges as a complete graph, then run Prim's MST in O(n^2) without ever materialising the edge list. A FAANG-favourite interview question at Amazon, Google, and Meta that tests whether you can spot a Minimum Spanning Tree behind a geometry prompt.
Solve the bottleneck shortest path problem: find a route from source to destination that minimises the maximum edge weight on the path. Combines binary search on the answer with BFS connectivity checks in O((V+E) log W) — a FAANG interview pattern asked at Google and Amazon, and the foundation behind LeetCode 1102 Path With Maximum Minimum Value.
Master LeetCode 1976 Number of Ways to Arrive at Destination: extend Dijkstra to count the number of distinct shortest paths simultaneously, returning the count modulo 10^9+7. A FAANG-favourite shortest-path counting interview question asked at Google, Amazon, and Meta.
Master longest path in a directed acyclic graph (DAG): a polynomial-time graph-DP that combines topological sort with memoised DFS. The same template solves LeetCode 329 Longest Increasing Path, course planning with prerequisites, and critical-path scheduling — a FAANG interview pattern at Google, Amazon, and Meta.
Eighteen advanced graph problems collapsed into one decision tree. Match the problem cue to the algorithm in seconds: MST, SCC, bridges, Floyd-Warshall, Bellman-Ford, A-star, topological sort, Eulerian paths, and max flow with complexity bounds you can quote on demand.
LeetCode 53 — find the contiguous subarray with the largest sum in O(n). Kadane is the dynamic programming gateway problem at Amazon, Google, and Meta.
Given a binary array and an integer k, find the longest run of 1s you can create by flipping at most k zeros. Master the variable sliding window pattern that solves this in O(n) time and O(1) space — and learn the follow-up questions Google and Meta actually ask after you get it right.
Learn why 3Sum is a FAANG interview staple — how sorting enables two pointers, why deduplication trips up even strong candidates, a full visual dry run, and every common bug explained with Python and JavaScript solutions.
LeetCode 11 explained from scratch: why this is a greedy problem, the formal proof that you must always move the shorter pointer, a full step-by-step dry run, common traps, and clean Python + JavaScript solutions. Master the pointer-elimination pattern that appears throughout FAANG interviews.
LeetCode 238 is one of the most frequently asked medium problems at Google and Meta. Learn why the no-division constraint is intentional, how the prefix × suffix insight unlocks the O(n) solution, and how a single running variable eliminates the extra O(n) space entirely.
Master the classic Merge Intervals problem (LeetCode 56) asked at Google, Meta, Amazon, and Microsoft. Learn why sorting by start time is the key insight, the exact overlap condition (c ≤ b), a step-by-step visual dry run, 4 common mistakes, Python and JavaScript solutions, and follow-up problems including Insert Interval, Non-overlapping Intervals, and Meeting Rooms II.
Traverse an m×n matrix in spiral order. Master the boundary-shrinking technique — maintain top, bottom, left, right walls and peel layer by layer. Covers edge cases, visual dry run, common bugs, Python & JavaScript solutions, and follow-ups like Spiral Matrix II.
Group strings that are anagrams of each other using two canonical approaches: sorted string key O(n·k·log k) and character frequency tuple key O(n·k). Understand when the difference matters, trace through a dry run, dodge the common traps, and leave any interview with both solutions ready to go.
Master LeetCode 3 — the canonical sliding window problem. Understand the "shrink from left" insight, the critical stale-index bug with max(), and both set-based and hashmap-optimized solutions in Python and JavaScript. Includes a full step-by-step dry run and follow-up problems LC 340 and LC 159.
LeetCode 560 is one of the most-asked FAANG problems because it teaches the prefix sum + hashmap pattern — a technique that handles negative numbers, generalizes to a dozen follow-ups, and cannot be replaced by sliding window. Learn the insight, the dry run, the common mistakes, and the O(n) solution in Python and JavaScript.
LeetCode 33 is a rite of passage in FAANG interviews. Learn the one invariant that makes O(log n) possible on a rotated array, trace through a dry run, avoid the 4 most common bugs, and master the full family of follow-up problems (LC 81, LC 153, LC 154).
LeetCode 55 is a classic FAANG greedy problem that tests whether you can compress O(n²) DP thinking into a single O(n) pass. Learn the "max reachable index" insight, why greedy beats DP here, a full visual dry run, common traps, and every follow-up question interviewers ask next.
LeetCode 189 looks trivial — until the interviewer asks for O(1) space. Learn why three distinct approaches exist, the mathematical reason triple-reverse works, every common pitfall (wrong k, direction confusion, off-by-one), a full visual dry run, and how this trick unlocks Rotate String, Rotate Image, and beyond.
LeetCode 153 is one of the cleanest illustrations of binary search on a non-standard search space. Learn the rotation insight that unlocks O(log n), trace through a full visual dry run, avoid the three mistakes that most often break this one, and walk away ready for the duplicates variant (LC 154) and the full search-in-rotated problem (LC 33).
LeetCode 347 asks for k most frequent elements with a constraint: beat O(n log n). Learn why naive sort fails, how a min-heap of size k achieves O(n log k), and the elegant bucket sort insight that delivers true O(n) — with full visual dry run, common mistakes, and Python/JavaScript solutions for all three approaches.
LeetCode 152 looks like a simple extension of Maximum Sum Subarray — until you hit negative numbers. A negative times a negative is positive, which means the current minimum can instantly become the new maximum. Learn why tracking BOTH cur_max and cur_min is the essential insight, how zeros act as hard resets, the four bugs every candidate makes, and step-by-step dry runs on key examples. Python and JavaScript solutions from O(n²) brute force to the elegant O(n) DP approach.
Learn how to rotate an n×n matrix 90° clockwise in-place using the elegant transpose-then-reverse trick. Understand the math behind it, see the 4-cell direct rotation alternative, dry-run through a worked example, avoid the four most common mistakes, and get clean Python + JavaScript solutions.
Next Permutation is not just an array problem — it is a test of systematic algorithmic thinking under pressure. Learn why you scan from the right, why you swap with the smallest larger element, and why the suffix is reversed rather than sorted. Includes full visual dry runs, the 4 most common bugs, and Python + JavaScript solutions.
LeetCode 287 eliminates every naive approach through three hard constraints: no array modification, O(1) space, O(n) time. The solution — treating the array as an implicit linked list and running Floyd's tortoise-and-hare cycle detection — is one of the most elegant algorithm mappings in all of DSA. Full proof, visual dry run, Python and JavaScript solutions.
Master Dijkstra's Dutch National Flag algorithm to sort 0s, 1s, and 2s in a single pass with O(1) space. Understand the three-pointer invariants, the critical bug most candidates make, and how this pattern unlocks a family of partition problems.
Master LeetCode 57 with the three-phase sweep algorithm. Learn exactly how to insert and merge intervals in O(n) time — a pattern that appears repeatedly at Google, Amazon, and Meta.
Master LeetCode 435 with the greedy earliest-end-time strategy. Learn why sorting by end time is the key insight, walk through a visual dry run, and ace every FAANG follow-up on interval scheduling.
Master LeetCode 39 — Combination Sum by understanding the backtracking decision tree, why unlimited reuse is handled by staying at the same index, and how sorting enables early pruning. Includes Python and JavaScript solutions with line-by-line comments, a full visual dry run, common mistakes, and follow-up questions on LC 40, LC 216, and LC 377.
LC 46 — Permutations is the canonical backtracking problem every interviewer uses to test recursive thinking. Learn two clean approaches — the visited-array method and the in-place swap method — with a full decision-tree dry run for [1,2,3], the three most common interview mistakes, and real follow-up questions on LC 47 and LC 60.
LC 78 is the gateway to every combination and permutation problem in FAANG interviews. Master all three approaches — backtracking, bitmask enumeration, and iterative cascading — with deep visual dry runs, real interview follow-ups, and line-by-line Python and JavaScript solutions.
Master LeetCode 209 from first principles: understand why a variable-size shrinkable sliding window is the insight that cracks this problem in O(n), trace through every pointer movement on a real example, learn the three common interview mistakes, and be ready for the O(n log n) binary search follow-up that Amazon and Microsoft love to ask.
LeetCode 442 is a FAANG favorite that tests whether you can squeeze O(1) space out of a hash-set problem. We use index negation to mark visited values in place.
LeetCode 394 is a classic FAANG string problem testing nested-bracket parsing. We use two stacks to decode any depth of k[encoded] expressions in linear time.
LeetCode 40 is a FAANG backtracking favorite that tests duplicate handling. Sort the candidates and skip same-level repeats to enumerate unique sum combinations.
LeetCode 134 — asked at Amazon, Google, and Microsoft. Find the unique valid starting station in a circular gas route using a two-insight greedy: global feasibility check plus a local reset that eliminates O(n) candidates at once, giving O(n) time and O(1) space.
LeetCode 739 — asked at Amazon, Google, and Meta. Find the number of days until a warmer temperature using a monotonic decreasing stack. Store indices not temperatures, pop when current day is warmer, and solve six related problems with the same O(n) pattern.
LeetCode 128 — asked at Google, Amazon, and Meta. Find the longest consecutive integer sequence in O(n) using a HashSet. Only start counting from numbers where num-1 is absent — each element is visited at most twice total, making an apparent O(n²) nested loop amortized O(n).
LeetCode 763 — asked at Amazon, Google, and Meta. Partition a string into the maximum number of pieces so each letter appears in exactly one piece. Map each character to its last occurrence, then greedily extend the current partition boundary — O(n) time, O(1) space.
LeetCode 621 — asked at Google, Meta, and Amazon. Schedule tasks with a cooldown n to minimize total time. Use the greedy formula max(len(tasks), (max_count - 1) * (n + 1) + count_of_max) or simulate with a max-heap and queue — both O(tasks) time.
LeetCode 452 — asked at Amazon, Google, and Microsoft. Find the minimum number of arrows to burst all balloons by sorting by end coordinate and greedily shooting through overlapping intervals. O(n log n) time, O(1) space — the classic greedy interval scheduling pattern.
LeetCode 670 — asked at Meta and Amazon. Given a non-negative integer, swap at most one pair of digits to get the maximum value. Track the last occurrence of each digit, then greedily find the leftmost position where a larger digit appears later — O(n) time, O(1) space.
LeetCode 162 — asked at Google, Meta, and Amazon. Find any peak element in O(log n) using binary search on slope direction. If nums[mid] < nums[mid+1], a peak must exist in the right half — guaranteed by virtual negative infinity at both boundaries.
LeetCode 229 — asked at Amazon, Google, and Microsoft. Find all elements appearing more than n/3 times using the Extended Boyer-Moore Voting Algorithm with two candidates. At most two such elements can exist — verify both candidates with a second pass. O(n) time, O(1) space.
LeetCode 324 — asked at Google and Amazon. Rearrange an array so nums[0] < nums[1] > nums[2] < nums[3]... The key insight: find the median, then use a virtual index mapping to interleave smaller and larger halves without adjacent equal elements. O(n) time with nth_element.
LeetCode 462 — asked at Amazon, Meta, and Google. Find the minimum number of moves to equalize all array elements where each move increments or decrements one element by 1. The optimal target is the median — provable by absolute deviation minimization. O(n log n) time.
LeetCode 565 — asked at Amazon and Google. Find the longest cycle in a functional graph where each index maps to nums[index]. Mark visited nodes in-place (set to n) to avoid revisiting. O(n) time, O(1) extra space — classic cycle detection pattern.
LeetCode 870 — asked at Google and Amazon. Rearrange array A to maximize the count of positions where A[i] > B[i]. Apply Sun Tzu greedy: against each of B's strongest, send your weakest if you cannot win; otherwise send your smallest winning element. O(n log n) time.
LeetCode 90 — asked at Amazon, Apple, and Google. Generate all unique subsets from an array with duplicates. Sort first, then in backtracking skip duplicate elements at the same recursion depth. O(2^n) time — the cleanest duplicate-handling pattern in all backtracking problems.
LeetCode 686 — asked at Google and Amazon. Find the minimum number of times to repeat string a so that b is a substring. The ceiling trick: repeat a at least ceil(len(b)/len(a)) times, then check that and one more. O(n*m) time, O(n+m) space.
Master LeetCode 1493 with an intuition-first sliding window approach. Learn why you subtract 1 from the window size, trace through a real dry run, and ace every follow-up question an interviewer throws at you.
Most candidates jump straight to sorting. Learn the O(n) one-pass trick that finds the minimum and maximum of the violated region, expands the boundary correctly, and handles all edge cases — plus every FAANG follow-up interviewers actually ask.
Master LeetCode 795 using the elegant count(max <= R) - count(max <= L-1) subtraction trick — a powerful O(n) pattern that unlocks a whole family of subarray counting problems asked at Amazon, Google, and Meta.
LeetCode 1007 seems deceptively simple but hides a key insight that trips up most candidates: only the value on the very first domino can ever unify an entire row. Learn why this candidate-reduction observation collapses six potential targets into at most two, how to count rotations efficiently in a single pass, and what FAANG interviewers ask as follow-ups — including generalization to N faces and streaming domino inputs.
LC 34 asks for the start and end index of a target in a sorted array. Solve it in O(log n) by running two separate binary searches — one for the left boundary and one for the right boundary. A top FAANG pattern.
Search a rotated sorted array in O(log n) by identifying which half is always sorted at each step and checking whether the target falls inside it. A top FAANG interview problem.
Find the minimum element in a rotated sorted array in O(log n) by comparing mid to hi to decide which side of the rotation pivot you are on. A classic FAANG pivot-search pattern.
LC 74 asks you to search a globally sorted 2D matrix in O(log(m*n)). The key insight: treat the entire matrix as a 1D sorted array using flat-index mapping (row = mid // n, col = mid % n) and run standard binary search.
Find the minimum eating speed that lets Koko finish all bananas in h hours by binary searching over the answer space and using a feasibility check. The canonical binary-search-on-answer problem.
LC 1011 asks for the minimum ship capacity to deliver all packages within D days. Binary search on the capacity range [max(weights), sum(weights)] and greedily simulate loading to check feasibility. A classic binary-search-on-answer pattern.
Find any peak element in O(log n) by always moving toward the uphill neighbor. Understand the slope-chasing invariant that guarantees a peak exists in every search window.
Find the k closest elements to x in a sorted array in O(log(n-k) + k) by binary searching for the optimal left boundary of the result window rather than searching for x itself.
Find the one non-duplicate element in O(log n) time by observing how pair indices shift after the singleton — a parity-based binary search that requires no XOR or extra space.
Find the length of the longest strictly increasing subsequence in O(n log n) using patience sorting — a binary search on a maintained tails array that is simpler and faster than classic DP.
Search a rotated sorted array that may contain duplicates in O(log n) average time by handling the ambiguous duplicate case with a safe lo++ shrink. Deep FAANG interview breakdown with visual dry runs and all edge cases.
Find the minimum number of days to make m bouquets of k adjacent flowers by binary searching on the day value and checking feasibility greedily. Full FAANG-level breakdown with visual dry run and all edge cases.
Find the h-index from a sorted citations array in O(log n) time using left-boundary binary search. Full FAANG interview breakdown with visual dry run, all edge cases, and intuition behind the search condition.
Count spell-potion pairs where spell * potion >= success by sorting potions and binary searching for each spell threshold. Full FAANG-level breakdown with visual dry run, all edge cases, and ceiling division intuition.
LC 378 asks for the kth smallest element in an n x n matrix sorted row-by-row and column-by-column. Binary search on the value range [min, max] and count elements <= mid using a staircase walk. O(n log(max-min)) total.
LC 1552 asks you to place m balls in sorted basket positions to maximize the minimum distance between any two balls. Binary search on the minimum distance and greedily place balls to check feasibility. A classic maximize-minimum binary search pattern.
LeetCode 2439 minimizes the array maximum by transferring values right-to-left. Solve it with binary search on the answer or, more elegantly, with the prefix-average closed form.
LeetCode 1802 maximizes the value at a given index given a sum cap and adjacent-difference constraint. A textbook O(log maxSum) binary-search-on-answer with arithmetic series math.
LC 1060 asks for the kth missing number in a sorted array. Binary search on the missing-count function: at index i, exactly nums[i] - nums[0] - i numbers are missing. Find the first index where this count >= k, then recover the answer. O(log n).
Search a row-and-column sorted 2D matrix in O(m+n) using the staircase technique from the top-right corner. Understand why binary search alone fails and why the corner is the unique elimination point.
LC 911 requires answering repeated queries "who is leading at time t?" in O(log n) per query. Precompute the leader at each vote event, then use right-boundary binary search on the times array to answer each query. Classic precompute-and-query design.
LC 287 has n+1 integers in [1,n] with exactly one duplicate. The binary search approach counts elements <= mid: if count > mid, the duplicate is in [1,mid]. O(n log n) time, O(1) space. Also understand the O(n) Floyd cycle detection approach.
LC 981 implements a key-value store where each key can have values at different timestamps. set() in O(1), get(key, timestamp) in O(log n) using right-boundary binary search on the sorted timestamp list. A classic design + binary search interview problem.
LC 1353 asks for the maximum number of events you can attend given start and end days. Greedy approach: each day, attend the event with the earliest end date using a min-heap. Sort events by start day and use a pointer to add available events. O(n log n).
LC 1870 asks for the minimum integer train speed to complete all rides within a given time limit. Binary search on speed [1, 10^7]: all rides except the last use ceiling division (must wait for the next hour), the last uses exact division. Classic binary-search-on-answer pattern.
LC 137 Single Number II extends XOR cancellation to triplets. Learn the ones/twos state machine and the mod-3 bit count, two approaches every FAANG interviewer expects you to derive from scratch.
LeetCode 260 Single Number III: every element appears twice except two unique elements. Master the XOR partition trick used by FAANG interviewers to test deep bitwise reasoning.
LeetCode 371 Sum of Two Integers: add integers using only XOR and AND. Master the half-adder, carry propagation, and two's complement trick that reveals how CPUs actually compute sums.
LeetCode 78 Subsets: enumerate the power set with bitmask iteration. Master the elegant 2^n bit-loop FAANG interviewers prefer over recursion for its clarity and speed.
LeetCode 698 Partition to K Equal Sum Subsets: decide if an array can be split into k equal-sum buckets. Master the bitmask DP that converts an exponential DFS into a clean O(2^n * n) solution loved by FAANG interviewers.
LeetCode 477 Total Hamming Distance: sum bit-differences across every pair in linear time. Master the per-bit contribution trick that turns O(n^2) brute force into O(n) — a FAANG favorite.
LeetCode 201 Bitwise AND of Numbers Range: AND every integer in [left, right] in O(log n). Master the common-prefix observation FAANG interviewers expect — far smarter than the obvious O(range) loop.
LeetCode 89 Gray Code — generate an n-bit sequence where consecutive numbers differ by exactly one bit. The one-line XOR formula gray(i) = i XOR (i shifted right by 1) cracks it. FAANG-favorite bit manipulation interview problem.
LeetCode 187 Repeated DNA Sequences — find every 10-letter substring that appears twice or more. Encode each nucleotide in 2 bits, slide a 20-bit window with shift and AND. Linear-time bit manipulation interview classic.
LeetCode 318 Maximum Product of Word Lengths — find two words sharing no letters with maximum length product. Encode each word as a 26-bit set, then check disjointness with one bitwise AND. The textbook FAANG bitmask interview problem.
LeetCode 240 Search a 2D Matrix II is a Google favourite that tests staircase elimination. We solve it in O(m + n) by walking from the top-right corner — beating the naive O(m * n) scan and the O(m * log n) per-row binary search.
Implement a lazy iterator over a nested integer list using a stack. Meta frequently tests this to evaluate iterator design, lazy evaluation, and stack-based tree traversal.
Find the minimum CPU intervals to finish all tasks with a cooldown constraint. Amazon tests this greedy heap problem to evaluate CPU scheduling knowledge and frequency-based optimization.
Find the longest substring containing at most k distinct characters using a sliding window with a frequency map. Google asks this to test sliding window mastery and hashmap-based window shrinking.
Generate all valid combinations of n pairs of parentheses using backtracking with open and close counters. Meta asks this to test recursive thinking, pruning, and combinatorial generation under time pressure.
Count contiguous subarrays whose elements sum to k using prefix sums and a frequency hashmap. Meta asks this to test prefix sum mastery and O(N) optimization over brute-force O(N^2) solutions.
Find the k most frequent elements in an array using a min-heap or bucket sort. Amazon asks this to test frequency counting, heap manipulation, and O(N) bucket sort optimization for bounded frequency ranges.
Return the rightmost visible node at each level of a binary tree using BFS level order traversal. Meta uses this to test BFS confidence, level tracking, and tree traversal variants applied to visual rendering problems.
Merge accounts that share any email address using Union-Find on email nodes. Meta uses this to test graph connectivity thinking and identity resolution — directly applicable to Facebook account deduplication systems.
Deep copy an undirected graph using DFS or BFS with a HashMap to track already-cloned nodes. Meta tests this to evaluate graph traversal, deep copy semantics, and cycle detection in recursive graph structures.
The complete 1D Dynamic Programming roadmap for FAANG interviews — Fibonacci, House Robber, Kadane, Coin Change, LIS, Jump Game, Decode Ways, and Palindrome patterns with Python and JavaScript templates.
LC 198 House Robber asks you to maximize stolen money without robbing adjacent houses. The recurrence dp[i] = max(dp[i-1], dp[i-2] + nums[i]) is the canonical skip-one DP pattern asked at Amazon, Google, and Microsoft. Master the derivation, the three-phase DP evolution, and the O(1) space solution.
LC 213 House Robber II extends House Robber to a circular arrangement where the first and last houses are adjacent. The elegant solution runs the linear House Robber DP twice — once excluding the first house, once excluding the last — and returns the maximum. A top FAANG interview problem that tests systematic problem decomposition.
LC 740 Delete and Earn looks like a game problem but reduces to House Robber DP after a preprocessing step. Choosing value v earns v * count(v) points and forces deletion of v-1 and v+1, exactly the skip-adjacent constraint. Asked at Amazon and Meta to test whether candidates see through surface-level descriptions to the underlying DP pattern.
LC 152 Maximum Product Subarray extends Kadane's Algorithm by tracking both the running maximum and minimum products simultaneously. A negative number flips today's minimum into tomorrow's maximum. This dual-tracking insight is tested at Amazon, Google, and LinkedIn as a harder follow-up to Maximum Subarray.
LC 322 Coin Change finds the minimum number of coins to make a target amount using unlimited coin supply. The recurrence dp[i] = min(dp[i - coin] + 1) over all coins is the canonical unbounded knapsack minimization problem, asked at Amazon, Google, and Microsoft as a core DP interview question.
LC 518 Coin Change II counts the number of combinations (not permutations) of coins that sum to a target amount. The key insight is the loop order: coins outer, amounts inner. This unbounded knapsack counting pattern is tested at Amazon and Google to distinguish candidates who understand loop-order reasoning from those who memorize templates.
LC 279 Perfect Squares finds the minimum number of perfect square integers that sum to n. It is isomorphic to Coin Change (LC 322) where the "coins" are all perfect squares up to n. The DP recurrence dp[i] = min(dp[i - j*j] + 1) runs in O(n * sqrt(n)) time and is asked at Google and Amazon.
LC 55 Jump Game asks if you can reach the last index given maximum jump lengths. The DP approach is O(n^2) but the greedy insight — tracking the farthest reachable index — reduces it to O(n) O(1). Asked at Amazon and Google as a test of recognizing when greedy is provably optimal over DP.
LC 45 Jump Game II finds the minimum number of jumps to reach the last index. The DP solution is O(n^2), but the greedy window technique — extending the current reachable window whenever a boundary is crossed — achieves O(n) O(1). Asked at Amazon and Google as a harder follow-up to Jump Game.
LC 91 Decode Ways counts the number of ways to decode a digit string as letters A-Z. The recurrence combines one-digit and two-digit transitions — a conditional Fibonacci DP. Heavily tested at Amazon, Google, and Meta because it combines string parsing, edge case handling, and DP reasoning in a single problem.
LC 139 Word Break checks if a string can be segmented into dictionary words. The reachability DP dp[i] = true if some dp[j] is true and s[j:i] is in the dictionary. Asked heavily at Amazon, Google, and Microsoft as a test of string DP with set-based lookups.
LC 300 Longest Increasing Subsequence finds the length of the longest strictly increasing subsequence. The O(n²) DP is the expected starting point; the O(n log n) patience sorting binary search optimization is what FAANG interviewers look for. This problem is asked at Amazon, Google, and Microsoft and is the foundation for Russian Doll Envelopes.
LeetCode 647 Palindromic Substrings is the canonical center-expansion problem. We derive the 2D DP recurrence, simplify it to expand-around-center for O(1) memory, and walk through a full DP table dry run with FAANG interview tips on why this beats Manacher in real interviews.
LeetCode 516 Longest Palindromic Subsequence is the cleanest interval DP recurrence in interview prep. We derive the dp[i][j] formulation, fill the table along diagonals, and reduce memory from O(n^2) to O(n) — exactly the depth Amazon and Google look for.
LeetCode 416 Partition Equal Subset Sum is the cleanest 0/1 knapsack disguise on the platform. We reduce it to subset-sum-equals-half, derive the boolean DP recurrence, walk through the reverse-iteration trick, and finish with a one-liner bitset version that crushes interviews.
LeetCode 494 Target Sum looks like sign-assignment but reduces to subset-sum count via a beautiful algebra trick. We derive the reduction, build the 1D DP, dry-run a tabulation, and discuss why this O(n * sum) solution beats 2^n brute force at FAANG.
LeetCode 1143 Longest Common Subsequence is the foundational two-string DP every FAANG interviewer expects you to nail. We derive the dp[i][j] recurrence, walk a full table, optimize space from O(m*n) to O(min(m,n)), and trace why this template powers Edit Distance, Shortest Common Supersequence, and diff tooling.
The full 1D Dynamic Programming cheatsheet for FAANG interviews — eight pattern transitions, knapsack loop directions, LIS patience sort, and the complete problem index in one place.
LC 62 Unique Paths is the foundational 2D grid DP problem at Amazon, Google, and Meta. Learn the recurrence, space-optimize to 1D, and master the combinatorics shortcut interviewers love to ask about.
LC 63 Unique Paths II extends the classic grid DP with obstacle cells. Master the obstacle-zeroing pattern, handle blocked start/end edge cases, and space-optimize to O(n) — the exact follow-up interviewers throw immediately after Unique Paths.
LC 64 Minimum Path Sum is the essential cost-minimization variant of grid DP, asked heavily at Amazon and Google. Learn the 2D recurrence, space-optimize to O(n), and understand why bottom-up tabulation handles borders without special-casing.
LC 120 Triangle asks for the minimum-sum path from apex to base. The bottom-up DP approach eliminates border initialization complexity and achieves O(n) space — a classic 2D DP problem that tests your ability to work on non-rectangular structures.
LC 1143 Longest Common Subsequence is the foundational sequence DP problem at every FAANG company. Master the 2D recurrence, space-optimize to O(n), and learn how to reconstruct the actual LCS — skills that transfer directly to Edit Distance, Shortest Common Supersequence, and Diff algorithms.
LC 122 Best Time to Buy and Sell Stock II allows unlimited buy-sell transactions (hold at most 1 share at a time). Solvable with a greedy slope-collection approach, but the state machine DP extension reveals how unlimited transactions differ structurally from single-transaction stock problems.
LC 309 Best Time to Buy and Sell Stock with Cooldown adds a 1-day cooldown after selling. The state machine expands to 3 states — holding, sold (cooldown), and resting — and the buy transition reads from 2 days ago instead of 1 day ago. This structural change is the cleanest example of how constraints reshape state machine DP.
LC 714 Best Time to Buy and Sell Stock with Transaction Fee extends unlimited transactions by subtracting a fee on each sell. The state machine is identical to Stock II with one modification: the sell transition subtracts the fee. This is the final stock series variant and the cleanest demonstration that state machine DP is a modular framework.
LC 97 Interleaving String asks whether s3 can be formed by interleaving s1 and s2 while preserving character order. The 2D DP table dp[i][j] checks whether s3[:i+j] can be formed from s1[:i] and s2[:j] — a classic Boolean 2D DP problem asked at Google and Amazon.
LeetCode 474 Ones and Zeroes is the cleanest two-capacity 0/1 knapsack on the platform. We derive the dp[i][j] recurrence, walk a full 2D table, and ship a 1D-collapsed solution that handles the dual-resource constraint while staying interview-friendly.
LeetCode 931 Minimum Falling Path Sum is the cleanest grid DP with diagonal moves. We derive the dp[i][j] recurrence with three predecessors, walk a full table, and ship an O(1) extra-space in-place tabulation that interviewers love.
Master BFS and DFS on graphs and grids with the seven core patterns that show up in 90 percent of FAANG graph interviews. Learn flood fill, multi-source BFS, shortest path on unweighted graphs, and connected components with Python and JavaScript code.
Solve LeetCode 200 Number of Islands with DFS flood fill in O(m*n) time. The most asked grid traversal problem at Amazon, Google, and Meta — covers DFS, BFS, and Union-Find approaches with Python and JavaScript.
Find the maximum area of any island in a binary grid using DFS that returns the size of each connected component. The canonical "DFS with return value" pattern asked at Google, Meta, and Amazon.
Capture every region of Os surrounded by Xs by inverting the problem — flood from the boundary instead of the interior. The classic boundary-DFS pattern interviewers love.
Compute the minimum minutes for rot to spread across a grid using multi-source BFS. The canonical "all sources start at the same time" pattern that solves dozens of grid-spreading problems.
For each cell, return the distance to the nearest 0. Multi-source BFS from every 0 simultaneously gives the answer in linear time — the gold-standard pattern asked at every FAANG company.
Find every cell from which water can flow to both oceans by reversing the flow and running DFS inward from each ocean. The reverse-flow trick that turns an O(N^4) brute force into O(N^2).
Find the shortest clear path from top-left to bottom-right in a binary grid with 8-directional movement. Pure BFS on an unweighted graph — the classic shortest-path-in-a-grid interview problem.
Find the water cell whose distance to the nearest land is maximized. Multi-source BFS from all land cells gives the answer in linear time — a top FAANG distance-spread problem.
Determine whether a word can be spelled by traversing adjacent cells without reusing any cell. The canonical DFS-with-backtracking template every grid-search interview problem builds on.
Count islands with unique shapes by encoding each DFS traversal path as a string and storing shapes in a set. A classic interview problem testing DFS + hashing.
Count land islands fully surrounded by water (no border touch). Flood-fill border land first to eliminate open islands, then count remaining closed components.
Find the path from top-left to bottom-right that minimizes the maximum absolute difference between consecutive cells. Dijkstra treats effort as edge weight; binary search + BFS checks feasibility for each candidate effort.
Master Clone Graph (LeetCode 133): a FAANG favorite that tests BFS, DFS, graph traversal, hash map state, and cycle handling. We trace it step by step, derive the optimal pattern, and fortify you against the classic mistakes interviewers love to spot.
LeetCode 547 Number of Provinces is the canonical connected-components question. Learn the DFS, BFS, and Union Find solutions, master the adjacency-matrix walk, and rehearse the FAANG interview script.
Classic graph reachability problem disguised as a puzzle. Treat each room as a node and each key as a directed edge, then run BFS or DFS from room 0 to check if every room can be visited.
BFS from the entrance to find the nearest border empty cell that is not the entrance. Classic BFS shortest-path on a grid with a carefully defined exit condition.
Minimum dice rolls to reach square n² from square 1. The hard part is converting square numbers to board coordinates in Boustrophedon (snake) order. BFS on the state space of squares gives the optimal answer.
Find the minimum number of turns to go from "0000" to the target combination on a 4-wheel lock, avoiding deadend states. Classic BFS on a finite state space — the lock combination is the node, each wheel turn is an edge.
An array problem masquerading as a jump puzzle. Each index is a node with two outgoing edges (i + arr[i] and i - arr[i]), and the question reduces to a textbook BFS or DFS reachability check.
A directed graph cycle-detection problem solved by Kahn topological sort (BFS) or three-color DFS. The bedrock template behind dependency resolution at Maven, npm, Bazel, Make, and every modern build system.
The natural sequel to LC 207. Instead of asking whether you can finish all courses, this problem asks for a valid course ordering. Kahn algorithm gives the answer almost for free.
A graph is a valid tree iff it is connected and has no cycles, equivalently exactly n - 1 edges and one connected component. Solve with BFS, DFS, or Union Find — Union Find is shortest.
Count connected components by Union Find (decrement count on each successful union) or by BFS / DFS (increment count for each unvisited node). Both run in near-linear time.
Find the edge that closes a cycle when added to an n-node, n-edge graph. The first edge whose two endpoints share a Union Find root is the answer — a five-line solve.
LC 743 Network Delay Time asks for the time a signal takes to reach all n nodes from source k. Single-source shortest path via Dijkstra gives every distance in O(E log V); the answer is the maximum among them.
LC 787 Cheapest Flights Within K Stops asks for the cheapest route from src to dst using at most k intermediate stops. Bellman-Ford with exactly k+1 relaxation rounds handles the stop constraint cleanly without Dijkstra getting confused by the layered state.
LeetCode 886 Possible Bipartition reduces a real-world group split to a bipartite check. Master the BFS 2-coloring, DFS coloring, and Union Find variants that recruiters expect at FAANG.
LeetCode 785 Is Graph Bipartite asks whether you can 2-color a graph. Master the BFS and DFS coloring patterns, the disconnected-component handling, and the FAANG interview script that proves you understand bipartite theory.
LeetCode 1654 Minimum Jumps to Reach Home looks like a number line puzzle, but it is a graph traversal in disguise. Master the state space BFS where direction is part of the node identity, plus the upper-bound trick that beats the time limit.
LeetCode 399 Evaluate Division turns equations like A/B equals 2 into a weighted graph. Master the BFS, DFS, and Union Find solutions plus the FAANG-grade interview script.
LeetCode 435 Non-Overlapping Intervals is a Meta and Amazon staple that tests interval scheduling. Sort by end time and greedily keep the earliest-ending interval to remove the minimum number in O(n log n).
LeetCode 452 Minimum Number of Arrows to Burst Balloons is a Meta and Google interval-clustering classic. Sort by end and shoot one arrow per cluster of overlapping intervals in O(n log n).
LeetCode 134 Gas Station is an Amazon, Uber, and Google favorite. Solve the circular-tour problem in a single linear pass using the running-tank greedy and a clean existence argument.
LC 739 Daily Temperatures is the most important medium-level monotonic stack problem. Unlike Next Greater Element, the stack stores indices so you can compute waiting distances. Every FAANG company uses this to gauge stack fluency.
LC 316 Remove Duplicate Letters combines greedy with a monotonic stack to find the lexicographically smallest subsequence containing every character exactly once. The "pop only if the character appears again later" check using last_occurrence is the key insight.
LC 402 Remove K Digits uses a monotonic increasing stack to greedily eliminate digits that make the number larger. The three-part answer construction — pop k times, trim trailing removals, strip leading zeros — is the exact pattern that trips candidates in interviews.
LC 907 Sum of Subarray Minimums introduces the contribution technique: instead of finding the minimum of each subarray, count how many subarrays each element is the minimum of. Two monotonic stacks compute left and right boundaries in O(n).
LC 962 Maximum Width Ramp finds the largest j-i with nums[i] <= nums[j]. The two-pass approach — build a decreasing stack of candidates, then scan right-to-left to match — is a pattern that appears in several max-width-satisfying-condition problems.
LC 456 132 Pattern requires finding i < j < k where nums[i] < nums[k] < nums[j]. The right-to-left decreasing stack maintains the "2" candidate — the key insight that makes an O(n) solution possible where left-to-right fails.
LC 503 Next Greater Element II extends the NGE pattern to circular arrays. Use a monotonic decreasing stack with a double-pass (iterate 2n) and modular indexing to handle wrap-around — a critical adaptation tested as a follow-up at every FAANG company.
LC 1167 Minimum Cost to Connect Sticks applies Huffman coding greedy with a min-heap. Always merge the two cheapest sticks first — a classic greedy pattern with a provable exchange argument that Amazon uses to test priority queue fluency.
LC 763 Partition Labels partitions a string into maximum parts where each letter appears in at most one part. Track the last occurrence of each character and greedily extend the current partition boundary — an elegant O(n) greedy interval merge.
Reconstruct a queue from height-position pairs [h, k] where k is the count of taller or equal people in front. Sort tallest first, then insert each person at their specified position k.
Maximise score jumping through an array where each jump covers 1 to k steps. Combine DP with a monotonic deque to find the sliding window maximum of recent DP values in O(n) time.
Find the maximum number of chunks that can be individually sorted to produce the full sorted array. A chunk boundary exists when the running maximum equals the current index — a clean O(n) greedy.
Complete Greedy and Monotonic Stack cheatsheet covering all patterns, templates, complexity table, decision tree, and problem index. The single page to revise before any FAANG interview.
Find Duplicate File in System teaches content-based grouping — the foundation of file deduplication, plagiarism detection, and distributed caching. Learn to parse structured strings, extract keys, and group by those keys using a HashMap.
Group Anagrams is a medium-difficulty milestone that teaches the canonical-key grouping pattern — one of the most broadly applicable hash map techniques. Amazon, Google, and Meta use it as a filter for candidates who can design O(n k) grouping algorithms over O(n^2 k) brute-force comparisons.
Top K Frequent Elements is a classic interview problem that tests whether you know the O(n) bucket sort approach over the standard O(n log k) heap. Amazon, Google, Meta, and Microsoft all ask this problem because it reveals whether you can identify when domain constraints enable a better algorithm.
LRU Cache is one of the most important design problems in tech interviews — it combines a HashMap for O(1) lookup with a doubly linked list for O(1) eviction order. Amazon, Google, Meta, and Microsoft use it to assess system design thinking at the data structure level.
Subarray Sum Equals K is the definitive prefix-sum hash map problem. It teaches the pattern of converting a range-sum query into a complement lookup — reducing O(n^2) to O(n). Amazon, Google, and Meta ask this in nearly every data-focused interview loop.
Continuous Subarray Sum applies the modular prefix sum trick — one of the most elegant applications of number theory to hash map design. Google uses this problem to test whether candidates can combine modular arithmetic with hash-map complement lookup.
Longest Consecutive Sequence is a deceptively hard problem that Google and Meta use to test whether candidates can achieve O(n) without sorting. The key insight — only start counting from sequence beginnings — turns an O(n^2) brute force into an O(n) HashSet solution.
Insert Delete GetRandom O(1) is a classic design interview problem that Google, Amazon, and Meta use to assess compound data structure thinking. The trick — swapping the target with the last element before deletion — enables O(1) removal from a dynamic array.
Find All Anagrams in a String combines the frequency-count pattern with a fixed sliding window — a compound technique that Google and Amazon use to filter candidates who understand both string hashing and window management. The "match counter" optimization is the key to an elegant O(n) solution.
Random Pick with Weight teaches weighted random sampling — a foundational technique in machine learning, A/B testing, and traffic routing. Google and Meta use this problem to assess whether candidates understand prefix sums and binary search well enough to implement probability distributions from scratch.
Brick Wall teaches the insight of counting the complement — instead of minimizing bricks crossed, maximize gaps hit. Google uses this problem to test whether candidates can reframe a minimization problem as a maximization problem and solve it in O(n) with a frequency map.
Count Wonderful Substrings combines bitmask XOR with prefix parity tracking to count substrings where at most one character has an odd frequency. This advanced hashing problem teaches the bit-manipulation pattern that Google and Meta use to filter candidates for senior-level roles.
LeetCode 2352 (Medium) is a Google and Amazon favorite that tests whether you can convert rows and columns into hashable tuples. The optimal solution counts row tuples in a hashmap, then probes columns to count matches in O(n^2) time.
LeetCode 1027 (Medium) is a Google, Amazon, and Microsoft favorite that fuses DP with hashing. Each index keeps a hashmap from common difference to longest subsequence length, giving an elegant O(n^2) solution.
LeetCode 2364 (Medium) is a Google, Amazon, and Meta favorite. Count good pairs through a frequency map of nums[i]-i and subtract from total — a textbook complement-counting hashmap interview pattern.
LeetCode 1590 (Medium) shows up at Google, Amazon, and Microsoft. Find the shortest subarray whose sum mod P equals the total mod P, using a prefix-sum hashmap — a classic hash table FAANG pattern.
LeetCode 1726 (Medium) is a Google, Amazon, and Meta hashmap interview favorite. Build a frequency map of all pair products, then apply choose-2 combinatorics and a factor of 8 to count ordered tuples.
LeetCode 535 (Medium) is the on-ramp to system design interviews at Google, Amazon, and Microsoft. Build O(1) encode and decode using two hashmaps and a counter — the core data structure behind every URL shortener.
LeetCode 166 (Medium) shows up in Google, Amazon, and Microsoft interviews. Convert a fraction to its decimal string by simulating long division and tracking remainders in a hashmap to detect the repeating cycle.
LeetCode 652 (Medium) is a Google, Amazon, and Microsoft staple. Serialize each subtree during post-order DFS, store the serialization in a hashmap, and report nodes whose serialization first hits a count of two.
Pick a uniformly random index of a target value without pre-processing, using reservoir sampling — an elegant streaming algorithm that appears in Google and Facebook interviews on probability and distributed systems.
LC 846 Hand of Straights asks whether cards can be rearranged into groups of consecutive values using a greedy frequency map — a FAANG-tested pattern that also appears in interval scheduling and task scheduling problems.
LC 974 Subarray Sum Divisible by K counts subarrays whose sum is divisible by K using prefix remainders and a frequency hash map — the canonical prefix mod pattern tested at Google, Amazon, and Facebook.
LC 1711 Count Good Meals extends Two Sum to 22 power-of-two targets, counting pairs whose combined deliciousness is a power of 2 using a frequency map and complement lookup — tested at Amazon, Google, and Meta.
LC 981 Time Based Key-Value Store pairs a hash map with binary search to retrieve the value associated with the largest timestamp not exceeding a query — a foundational design problem tested at Google, Amazon, and Facebook.
LC 454 4Sum II counts 4-tuples from four arrays summing to zero by splitting into two pairs and using a frequency map — the meet-in-the-middle strategy that reduces O(n^4) to O(n^2), tested at Google, Amazon, and Microsoft.
Design a simplified Twitter with follow/unfollow and a news feed that returns the 10 most recent tweets across followed users — combining hash maps, social graph storage, and k-way heap merging.
Solve LeetCode 658 Find K Closest Elements using a max-heap of size K or O(log n) binary search on the window boundary, a classic Google and Amazon question.
Solve LeetCode 215 Kth Largest Element using a heap (O(n log k)) or Quickselect (average O(n)). One of the most-asked Meta and Amazon interview problems.
Solve LeetCode 347 Top K Frequent Elements using a min-heap (O(n log k)) or bucket sort (O(n)). One of the most common Meta and Amazon onsite questions.
Solve LeetCode 973 K Closest Points to Origin using a max-heap (O(n log k)) or Quickselect (O(n) average). One of the most-asked Meta and Amazon problems.
Solve LeetCode 767 Reorganize String with a max-heap by always picking the two most frequent characters. A staple Amazon, Meta, and Google interview problem.
LeetCode 378 (Medium) — a Google and Amazon staple. Solve k-th smallest in a row-and-column-sorted matrix with a min-heap k-way merge or binary search on the value range.
LeetCode 373 (Medium) — find the k smallest pair sums from two sorted arrays in O(k log k) by treating the implicit pair-sum matrix as a sorted matrix and running a min-heap k-way merge.
Find the minimum number of conference rooms required for all meetings by tracking room availability with a min-heap of end times — a classic interval scheduling problem asked at every major tech company and fundamental to resource allocation.
Find the minimum cost to connect all sticks by always merging the two shortest first — a direct application of the Huffman coding greedy principle, asked at Amazon and Facebook as a clean demonstration of optimal merge order.
Check if a car can complete all trips without exceeding capacity by using a difference array or event-sweep — a clean interval problem with an O(1) space solution that appears at Amazon, Facebook, and Google for testing interval manipulation skills.
Reach the furthest building by greedily assigning ladders to the largest climbs and bricks to the rest — a nuanced greedy problem with a min-heap that appears at Amazon, Facebook, and Google and teaches optimal resource allocation under uncertainty.
LeetCode 1882 Process Tasks Using Servers is a Google and Amazon two-heap scheduling interview classic. Master the priority queue approach that simulates task assignment in O((m+n) log n).
LeetCode 313 Super Ugly Number is a generalization of Ugly Number II asked in Amazon and Google interviews. Generate the nth number whose only prime factors are in a given list using min-heap or K-pointer DP.
LeetCode 355 Design Twitter is a Meta and Twitter system design interview classic. Build post, follow, unfollow, and getNewsFeed using a per-user tweet list and a K-way merge max-heap.
LeetCode 1201 Ugly Number III is a Google and Amazon medium that breaks the heap pattern. Solve it with binary search plus inclusion-exclusion in O(log(n*max)) — far faster than naive heap enumeration.
LeetCode 1405 Longest Happy String is a Google and Amazon medium interview classic. Greedily build a string with no three consecutive identical chars using a max-heap of remaining counts in O(N log 1).
For each interval, find the one with the smallest start point greater than or equal to its end — a clean binary search problem that teaches index-preserving sort patterns.
Find the kth largest level sum in a binary tree by computing all level sums with BFS and selecting the kth largest using a min-heap — a clean combination of BFS and heap selection.
Minimize the total cost to hire k workers by always choosing the cheapest candidate from the first or last p candidates using two min-heaps expanding inward from both ends.
Design a seat manager that always reserves the lowest available seat number and supports unreservation using a min-heap — the canonical example of heap-based resource management.
Track stock prices with out-of-order timestamp updates and corrections, supporting O(log n) current, maximum, and minimum queries using a timestamp map and sorted multiset.
Find the minimum number of distinct values to remove to halve the array size by greedily eliminating the most frequent elements first — a clean greedy problem with a frequency max-heap.
LC 19 Remove Nth Node From End of List is a classic one-pass interview problem at Amazon, Google, and Facebook that combines the dummy head sentinel with a two-pointer n-gap technique. Learn the optimal O(n) single-pass solution with Python and JavaScript, step-by-step dry run, and common interview traps.
LC 24 Swap Nodes in Pairs is a medium linked list interview problem at Microsoft and Bloomberg that tests precise multi-step pointer manipulation. Learn the iterative dummy-head approach and the recursive solution with Python and JavaScript, detailed visual dry run, and interview tips.
LC 328 Odd Even Linked List is a medium interview problem at Facebook, Amazon, and LinkedIn that tests your ability to maintain two separate pointer chains simultaneously. Learn the O(1) space two-chain pattern with Python and JavaScript, a visual dry run, and interview tips.
LC 61 Rotate List is a medium interview problem at Amazon and Microsoft that tests your ability to use circular linked list manipulation and modular arithmetic to rotate by k positions efficiently. Learn the optimal O(n) solution with Python and JavaScript, detailed dry run, and the critical k mod n insight.
LC 143 Reorder List is a composite interview problem at Facebook, Amazon, and Google that combines three core patterns: fast/slow midpoint finding, in-place second-half reversal, and interleaved merging. Master the O(1) space solution with Python and JavaScript, step-by-step visual trace, and interview approach.
LC 2 Add Two Numbers is one of the most iconic interview problems at Amazon, Google, and Microsoft where you simulate grade-school addition on two reversed linked lists digit by digit. Master the carry propagation technique with Python and JavaScript solutions, visual dry run, and common pitfalls.
LC 445 Add Two Numbers II is a medium interview problem at Amazon and Google where numbers are stored most-significant-digit first, requiring stacks or list reversal to process from LSB. Learn the optimal stack-based solution with Python and JavaScript, dry run, and the key difference from LC 2.
LC 86 Partition List is a medium interview problem at Bloomberg and Amazon that extends the dummy-head two-chain pattern to partition by value comparison. Learn the stable O(n) solution with Python and JavaScript, visual dry run, and critical edge cases including the tail-cycle trap.
LC 148 Sort List is a classic O(n log n) interview problem at Amazon, Google, and Facebook that applies merge sort to a linked list using fast/slow pointer splitting and recursive merging. Learn top-down merge sort with Python and JavaScript, a complete dry run, and the bottom-up O(1) space follow-up.
LC 82 Remove Duplicates from Sorted List II is a medium interview problem at Google, Amazon, and Bloomberg where you remove ALL nodes that appear more than once from a sorted list. Learn the dummy-head predecessor skip pattern with Python and JavaScript, step-by-step dry run, and the critical difference from LC 83.
LC 138 Copy List with Random Pointer is a medium interview problem at Amazon, Microsoft, and Facebook that requires deep-copying a linked list where each node has a random pointer. Learn the O(n) space hash map approach and the clever O(1) space interleave technique with Python and JavaScript solutions and detailed dry run.
LC 430 Flatten a Multilevel Doubly Linked List is a medium interview problem at Microsoft and Amazon that uses DFS or an explicit stack to inline child sub-lists into the main list. Learn the iterative stack approach and the recursive approach with Python and JavaScript, step-by-step dry run, and interview tips.
LC 142 Linked List Cycle II is a medium interview problem at Amazon, Microsoft, and Google where you find the exact node where a cycle begins using Floyd's algorithm and a mathematical proof. Learn the two-phase approach with Python and JavaScript, the math proof, visual dry run, and common interview questions.
LC 287 Find the Duplicate Number is a brilliant medium interview problem at Amazon, Google, and Facebook where you find a duplicate in an n+1 integer array in O(1) space by treating the array as an implicit linked list and applying Floyd's cycle detection algorithm. Master the connection between arrays and linked lists with Python and JavaScript solutions and detailed proof.
Modular arithmetic powers nearly every competitive programming problem and is foundational at Google, Stripe, and any system that handles big numbers. Master binary exponentiation in O(log n), modular inverse via Fermat little theorem, and the modulo identities that prevent overflow on the hot path.
Prime factorization is the workhorse of number-theoretic interview problems at Amazon and Microsoft. Master trial division in O(sqrt n), the smallest-prime-factor sieve for batched factorization in O(log n) per query, and the divisor-counting tricks they unlock.
Eulers totient function phi(n) counts integers up to n coprime to n and underpins RSA, modular inverse for composite moduli, and Eulers theorem. Master the prime-factorization formula, the sieve variant in O(N log log N), and the multiplicative-function tricks that make phi indispensable for competitive programming.
Computing C(n, r) modulo a prime appears in nearly every counting problem at Google and Meta. Master Pascal triangle for small n, precomputed factorials with modular inverse for n up to 10^6, and Lucas theorem for n up to 10^18.
Bit manipulation is the cheat code of competitive programming and tier-1 interviews. Master the XOR identities, n & (n-1) tricks, subset enumeration over a bitmask, and bitmask DP techniques that turn O(2^n) brute force into elegant constant-factor wins.
Recognising classical number sequences — Fibonacci, Catalan, triangular, Pascal-derived — is the difference between a 30-minute brute force and a 5-minute closed form. Master the recurrences, generating functions, and combinatorial interpretations every interviewer expects you to know.
Learn the Chinese Remainder Theorem from scratch. Understand the math, build CRT from extended GCD, handle non-coprime moduli, and ace cryptography and competitive programming interview questions.
Master square root decomposition for range sum, range minimum, and Mo's algorithm. The simplest range-query data structure that beats brute force for competitive programming and interviews.
Avoid silent overflow bugs and floating-point traps. Learn safe multiplication, modular arithmetic, BigInt, integer square root, and binary search on the answer for competitive programming and interviews.
Solve probability DP problems used by quantitative interviews. Master expected value recurrences, geometric distribution, knight probability, and the soup servings memoization trick.
Master the computational geometry primitives every interviewer expects: cross product orientation, segment intersection, Graham scan convex hull, polygon area via shoelace, and point in polygon.
Master combinatorial game theory: Nim XOR strategy, Grundy numbers, Sprague-Grundy theorem, mex, and minimax DP for stone games and impartial games in competitive programming and interviews.
Master randomized algorithms in interviews: reservoir sampling for streams, quickselect for O(n) kth element, Fisher-Yates shuffle, and Bloom filters with probability proofs.
Apply the inclusion-exclusion principle to divisibility counting, derangements, Euler totient, and surjection problems. The single most useful tool for combinatorial counting in interviews and competitive programming.
A practical, interview-ready guide to recursion and backtracking covering 7 core patterns, the choose-explore-unchoose template, pruning strategies, and complexity analysis. Build the mental model that unlocks subsets, permutations, combinations, partitioning, N-Queens, and Sudoku.
LeetCode 78 Subsets and 90 Subsets II are the foundation of every backtracking interview. Master the include-exclude decision tree, the duplicate-skip rule, and the bitmask alternative that interviewers use to test depth.
LeetCode 46 Permutations and 47 Permutations II are essential backtracking problems at top-tier companies. Master the used-array pattern, in-place swap variant, and the tricky `not used[i-1]` duplicate-skip condition that separates strong candidates from average ones.
LC 77 Combinations, LC 39 Combination Sum, and LC 40 Combination Sum II form a trilogy that every FAANG interviewer loves. Master the start-index pattern to enumerate selections without duplicates and the i+1 vs i reuse trick.
LC 22 Generate Parentheses is the backtracking warm-up every FAANG interviewer reaches for. Master the open and close counter invariant, the Catalan number trail, and why a string-builder beats array joins for clean recursion.
LC 79 Word Search and LC 212 Word Search II ship in nearly every FAANG onsite. Master DFS with in-place visited marking, four-directional exploration, and the trie trick that turns multi-word search into a single traversal.
LC 17 Letter Combinations of a Phone Number is the cleanest cartesian-product backtracking template ever written. Master the digit-to-letter mapping, the per-position branching, and why the iterative BFS variant is asked at Amazon.
Master LeetCode 131 Palindrome Partitioning using backtracking with a precomputed palindrome DP table. Learn the decision tree, pruning, and FAANG interview tips.
Master Partition Equal Subset Sum (LC 416) and Partition to K Equal Sum Subsets (LC 698) with bucket backtracking, sorting tricks, and FAANG-grade pruning.
LeetCode 526 Beautiful Arrangement with backtracking and bitmask DP. Learn how to generate divisibility-constrained permutations with FAANG interview tips.
M-coloring, bipartite check, and Hamiltonian path/cycle: backtracking on graphs with constraint propagation, ordering heuristics, and FAANG interview prep.
LC 307 Range Sum Query Mutable is the canonical benchmark for range query data structures. BIT solves it in O(log n) per operation; Segment Tree generalizes to any associative query. Master both before your next FAANG interview.
Design a calendar that rejects double bookings. The classic interval-overlap interview problem solved with sorted maps in O(log n) per booking — the foundation for every range scheduling system.
Count all longest increasing subsequences with DP in O(n^2) or with a segment tree on values for O(n log n). The classic crossover problem between DP and range-query data structures.
Apply many range shift operations to a string in O(n + q) using a difference array. The textbook example of when a diff array beats a segment tree, and the canonical interview signal for offline range updates.
Master LeetCode 304 Range Sum Query 2D Immutable with 2D prefix sums, inclusion-exclusion, and the natural extension to 2D Fenwick tree (BIT) for the mutable variant.
Find the longest contiguous subarray whose sum is at most K in linear time using prefix sums plus a decreasing monotonic stack, then learn the segment tree and BIT alternatives for streaming variants.
Solve LeetCode 238 Product of Array Except Self in O(n) time and O(1) extra space using two passes of prefix and suffix products, with the segment tree and Fenwick tree extensions for the mutable variant.
Find how many days until a warmer temperature using a monotonic decreasing stack of unresolved day indices. The canonical monotonic stack problem asked at every FAANG company — master the pattern here and unlock 20+ harder problems.
Find the next greater element in a circular array by processing 2n indices with modulo indexing and a monotonic stack. The circular variant of the classic monotonic stack pattern — an elegant trick that extends NGE I to handle wrap-around in O(n) time.
Calculate the stock price span using a monotonic decreasing stack that stores (price, span) pairs and accumulates spans in O(1) amortized time. A classic streaming design problem that tests span accumulation and the monotonic stack pattern.
Remove k digits from a number string to form the smallest possible number using a monotonic increasing stack with greedy removal. A key FAANG problem testing greedy thinking, stack manipulation, and edge case handling with leading zeros.
Decode a run-length encoded string with nested brackets like 3[a2[bc]] using two stacks for counts and partial strings. A key FAANG problem testing nested structure parsing with stacks — the same pattern used in expression evaluators and compilers.
Evaluate a Reverse Polish Notation expression by pushing operands and applying operators to the top two stack elements in O(n) time. The canonical stack-based expression evaluation problem asked at Amazon, LinkedIn, and Microsoft.
Simulate asteroid collisions where right-moving asteroids accumulate on the stack and left-moving ones destroy smaller ones on collision. A clean application of the collision-simulation stack pattern asked at Amazon and Bloomberg.
Sum the minimum of all subarrays using a monotonic stack to find each element's contribution as the minimum element across all subarrays it dominates. A critical FAANG problem teaching the contribution-counting pattern with monotonic stacks.
Calculate the score of a balanced parentheses string where () = 1 and (A) = 2*A using a stack and an elegant O(1) space depth-doubling trick. A FAANG medium problem that rewards deep thinking with a beautiful bit-shift optimization.
Find the minimum CPU intervals to execute all tasks with cooldown n using a greedy formula based on maximum frequency. A key FAANG problem testing greedy reasoning, frequency counting, and optionally heap-based simulation asked at Amazon, Google, and Facebook.
Solve LeetCode 994 Rotting Oranges step by step using multi-source BFS with a queue. A FAANG interview favorite at Amazon, Google, and Microsoft that teaches level-order traversal, simultaneous infection spread, and grid traversal patterns.
Solve LeetCode 200 Number of Islands using BFS with a queue or DFS with a stack. The most asked grid interview question at Amazon, Google, Meta, and Microsoft, teaching connected components and flood fill.
Solve LeetCode 207 Course Schedule using Kahn algorithm BFS topological sort with a queue and indegree array. A FAANG interview classic at Amazon, Google, and Meta that tests cycle detection in a directed graph.
Solve LeetCode 210 Course Schedule II by returning an actual topological order using Kahn algorithm BFS or DFS with three colors. A FAANG interview classic at Amazon, Google, Meta, and Microsoft.
Solve LeetCode 227 Basic Calculator II using a stack to handle operator precedence for plus, minus, multiplication, and division. A FAANG interview classic at Google, Amazon, Meta, and Uber.
Solve LeetCode 456 132 Pattern in O(n) using a monotonic stack scanned from right to left while tracking the best second-largest. A FAANG interview favorite at Bloomberg, Amazon, and Google.
Solve LeetCode 622 Design Circular Queue with a fixed-size array and two pointers to achieve O(1) enQueue, deQueue, Front, and Rear. A FAANG interview classic at Amazon, Google, and Meta.
Solve LeetCode 417 Pacific Atlantic Water Flow with reverse BFS from both ocean borders using a deque queue. A FAANG grid traversal classic asked at Amazon, Google, and Meta.
Solve LeetCode 1696 Jump Game VI with a monotonic deque to track the sliding window maximum of DP states in O(n). A high-signal FAANG interview problem.
Solve LeetCode 341 Flatten Nested List Iterator with a lazy stack-based approach in O(1) amortized hasNext and next. A FAANG design favorite at Google, Meta, and Amazon.
Solve LeetCode 1209 Remove All Adjacent Duplicates II in O(n) using a counter stack of (char, count) pairs. A FAANG-favorite stack twist asked at Google and Amazon.
Solve LeetCode 362 Design Hit Counter using a queue or fixed-size circular buffer for O(1) amortized hits and constant-time getHits. A FAANG system design favorite.
The Z algorithm computes Z[i] equals the length of the longest substring starting at index i that matches a prefix of the string in linear O(n) time. Cleaner than KMP for many problems and the foundation of competitive programming string toolkits.
Rabin Karp uses a polynomial rolling hash to fingerprint each window of the text and matches against the pattern hash in expected O(n + m) time. Master this and you unlock substring search, plagiarism detection, and the entire family of hash-based string problems.
Precompute polynomial prefix hashes once in O(n) and answer substring equality queries in O(1) for the lifetime of the string. The Swiss army knife behind longest duplicate substring, longest common substring binary search, and dozens of competitive programming techniques.
Find the longest contiguous substring shared by two strings. The DP solution is O(n*m), binary search plus rolling hash gives O((n+m) log min(n,m)) expected, and suffix array plus LCP achieves O((n+m) log(n+m)).
The four canonical string DP problems — edit distance, longest common subsequence, interleaving strings, and regular expression matching — share a common 2D state structure. Master the family and you cover 80 percent of FAANG string DP questions.
Group anagrams, find anagram occurrences, and detect anagrams under constraints. Master the three classical encodings — sorted key, 26-bucket frequency vector, and prime-product hash — with rolling-window extensions used at Meta and Google.
Longest Palindromic Substring, Palindrome Partitioning, and Palindromic Substrings form a tight family of FAANG questions. Master expand-around-center, 2D DP, and the link to Manacher and you can adapt to any variant on the spot.
Encode and Decode Strings (LC 271) is a deceptively simple FAANG question that mirrors how real protocols frame variable-length payloads. Master length-prefix encoding and you have the foundation for HTTP chunked transfer, Protobuf, and most binary wire formats.
String Compression (LC 443) is a deceptively careful two-pointer problem with strict in-place memory requirements. Master the read-write pointer pattern and you have the blueprint for in-place array transformations across many FAANG questions.
LeetCode 146 LRU Cache is the most-asked design problem at FAANG. Build O(1) get and put using a doubly linked list and hashmap with full Python and JavaScript code.
Implement a file system that creates paths and associates integer values with them. Uses a HashMap mapping full path strings to values with O(L) operations—a pattern used in virtual file systems and etcd.
Design a hit counter that counts requests in the last 5 minutes using a circular buffer with 300 buckets. This O(1) fixed-memory design is used in rate limiters and analytics pipelines at AWS and Cloudflare.
Design a time-stamped key-value store that retrieves the latest value at or before a given time using binary search on sorted timestamp lists. Google and Amazon test this to evaluate versioned data design and binary search mastery.
Implement browser back/forward navigation using an array with a current index pointer. This O(1) design models the two-stack navigation pattern used in browser engines and undo/redo systems.
Design a real-time leaderboard that tracks player scores, supports score additions, top-K sum queries, and resets. A pattern used in gaming platforms, competitive coding sites, and live event dashboards at Amazon and Riot Games.
Simulate a snake game where the snake eats food to grow and dies if it hits walls or itself. Uses a deque for O(1) head insertion and tail removal, plus a HashSet for O(1) self-collision detection.
Design a log storage system that retrieves log IDs within a timestamp range at a specified granularity. Uses prefix-based string comparison to truncate timestamps—a pattern used in log aggregation systems like Elasticsearch and CloudWatch.
Design a phone directory that manages available and allocated numbers with O(1) get, check, and release. Uses a queue of free numbers and a boolean availability array—the same pattern used in IP address allocation and database connection pools.
Implement a stack that retrieves the minimum element in O(1) using a parallel auxiliary stack. A foundational design pattern asked at Amazon, Google, and Meta—and used in undo systems and expression evaluators.
Implement a circular queue (ring buffer) with O(1) enqueue, dequeue, and peek using head/tail pointer arithmetic. Used in embedded systems, producer-consumer pipelines, and network packet buffers at Amazon and Qualcomm.
Design a URL shortener like TinyURL using base-62 encoding with an incrementing counter or random key generation. A classic system design coding problem asked at Amazon, Google, and Bitly to test encoding, collision handling, and hashmap design.
LeetCode 102 — Binary Tree Level Order Traversal, asked at Amazon, Meta, Google and Microsoft. The canonical BFS template that powers Right Side View, Zigzag, Largest in Each Row and 30+ other problems.
LeetCode 103 Binary Tree Zigzag Level Order Traversal — frequently asked at Amazon, Meta, Microsoft, and Bloomberg. Learn the BFS toggle pattern with deque appendleft for O(n) time.
LeetCode 199 Binary Tree Right Side View — high-frequency at Amazon, Meta, Google, and Apple. Two clean approaches: BFS taking last node per level and DFS visiting right-first.
LeetCode 113 Path Sum II — Medium tree backtracking favorite at Amazon, Meta, Microsoft. Collect every root-to-leaf path summing to target with DFS plus path append-and-pop.
LeetCode 98 Validate Binary Search Tree — high-frequency at Amazon, Meta, Google, Apple. Pass min and max bounds down through DFS so every node is strictly within its valid range.
LeetCode 236 Lowest Common Ancestor of a Binary Tree — Amazon, Meta, Google, Apple favorite. Single post-order DFS that returns root when either target is found, then propagates the split point upward.
LeetCode 235 Lowest Common Ancestor of a Binary Search Tree — top BST problem at Amazon, Meta, Microsoft. Iterative O(h) navigation with O(1) space using BST ordering.
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal — Amazon, Google, Microsoft favorite. Divide-and-conquer with a HashMap for O(1) inorder lookup giving O(n) total time.
LC 437 Path Sum III counts all paths in a binary tree summing to a target. The optimal O(n) solution mirrors the subarray sum equals k trick — use a prefix sum frequency map with DFS backtracking, a pattern tested at Amazon and Google.
LC 450 Delete Node in a BST is a top FAANG interview problem testing all three deletion cases. Master the in-order successor strategy to pass BST questions at Amazon, Google, and Microsoft.
LC 114 Flatten Binary Tree to Linked List rearranges a binary tree into a right-skewed linked list in pre-order. The optimal O(1) space solution uses a Morris-like pointer manipulation trick tested at Amazon and Microsoft.
LC 116 Populate Next Right Pointers asks you to connect each node to its next right sibling. The O(1) space solution leverages already-connected next pointers on the current level to wire up the next level — a pattern tested at Amazon and Microsoft.
LC 863 All Nodes Distance K in Binary Tree finds all nodes exactly K edges from a target. The key insight is converting the tree to an undirected graph by recording parent pointers, then running BFS from the target — a pattern tested at Amazon and Google.
Solve LeetCode 129 Sum Root to Leaf Numbers with the carry-and-accumulate DFS pattern asked at Meta, Amazon, Google, and Microsoft. Includes Python and JavaScript code, dry run, and follow-ups.
Solve LeetCode 662 Maximum Width of Binary Tree with the heap-style index trick used in Amazon, Meta, and Microsoft interviews. Includes overflow-safe BFS code in Python and JavaScript.
Solve LeetCode 1448 Count Good Nodes in Binary Tree with the DFS carry-max pattern asked at Microsoft, Meta, and Amazon. Includes Python and JavaScript code, complexity analysis, and FAANG-style follow-ups.
Solve LeetCode 538 Convert BST to Greater Tree using reverse in-order traversal asked at Google, Microsoft, and Amazon. Single O(n) pass with O(h) space.
Solve LeetCode 652 Find Duplicate Subtrees with postorder serialization and hashing — a Google and Amazon favorite. Includes Python and JavaScript solutions with O(n^2) and O(n) approaches.
Generate all structurally unique BSTs storing values 1 to n using recursion plus memoization. LeetCode 95 is asked at Google, Amazon, and Meta to test divide-and-conquer reasoning on Catalan-number-sized search spaces.
Trim a BST so all values lie within [low, high] using recursive subtree pruning. LeetCode 669 is a Medium FAANG question asked at Amazon, Google, and Apple.
Encode a BST compactly using preorder traversal without null markers and rebuild it with min-max bounds. LeetCode 449 is a Medium FAANG question asked at Amazon, Google, and Meta.
Solve LeetCode 2096 by finding LCA, building path strings, and replacing the start path with U moves. Asked at Amazon, Meta, and Google for FAANG-style tree pathing.
Verify a binary tree is complete with one BFS pass. Once a null child is encountered, every subsequent dequeued node must be null. LeetCode 958 is a Medium FAANG question asked at Amazon, Meta, and Microsoft.
Recover a BST where two nodes are swapped using in-order traversal to find the inversion pair. LeetCode 99 is asked at Amazon, Google, and Meta. Includes O(1) space Morris traversal solution.
LC 337 House Robber III extends the classic House Robber DP to a binary tree where adjacent nodes cannot both be robbed. The optimal O(n) solution uses post-order DFS returning a (rob, skip) pair — a fundamental tree DP pattern tested at Amazon and Microsoft.
LC 979 Distribute Coins in Binary Tree asks for minimum moves to give each node exactly one coin. The O(n) solution tracks coin excess flowing through each edge via post-order DFS — a pattern tested at Amazon and Google that elegantly converts a counting problem into a flow problem.
LC 1483 Kth Ancestor of a Tree Node answers each query in O(log k) after O(n log n) preprocessing using binary lifting — a sparse table DP technique that also powers LCA algorithms and is commonly tested at Amazon.
LC 1008 Construct BST from Preorder Traversal reconstructs a binary search tree in O(n) using min-max bounds to decide left vs right placement — a clean recursion problem tested at Amazon and Google that showcases BST property exploitation.
LC 366 Find Leaves of Binary Tree groups nodes by their height (distance from the nearest leaf) using a post-order DFS — a problem asked at Amazon and LinkedIn that reveals an elegant alternative to iterative leaf removal.
Count nodes in a complete binary tree in O(log^2 n) by comparing left and right spine heights to detect perfect subtrees and skip counting them entirely.
Find the minimum seconds to collect all apples in an undirected tree using post-order DFS — include a subtree path only when it contains at least one apple.
Find the longest zigzag path in a binary tree by DFS — track the current direction and length, reset when the direction breaks, and update a global maximum.
LeetCode 96 Unique Binary Search Trees asks for the count of structurally unique BSTs storing 1..n. Solve it in O(n^2) using Catalan number DP — a favorite Amazon and Google interview question.
LeetCode 429 N-ary Tree Level Order Traversal is a level-by-level BFS over a tree where each node has any number of children. Common at Amazon and Meta as a BFS warmup.
LeetCode 814 Binary Tree Pruning removes every subtree that contains no 1. Solve it in O(n) using post-order recursion — a classic Amazon and Google interview question.
LeetCode 1161 Maximum Level Sum returns the smallest level whose node-sum is largest. Solve in O(n) with BFS level-size snapshots — a common Amazon and Meta phone-screen question.
LeetCode 988 Smallest String Starting From Leaf returns the lexicographically smallest leaf-to-root string. Solve in O(n * h) using DFS with path strings — popular at Amazon and Google.
LeetCode 2385 Amount of Time for Binary Tree to Be Infected models tree-to-graph BFS spread. Solve in O(n) by converting to an undirected graph and running BFS from the start node — common at Amazon, Google, and Meta.
LeetCode 2471 Minimum Number of Operations to Sort a Binary Tree by Level uses BFS plus minimum-swaps-to-sort-an-array. Solve in O(n log n) — a popular Google and Meta interview question.
LeetCode 173 BST Iterator implements a controlled inorder traversal with O(h) memory and amortized O(1) next. Asked at Amazon, Google, Meta, and Apple as a class-design tree question.
LeetCode 666 Path Sum IV reconstructs a tree from depth-position-value encoded integers and returns the sum of all root-to-leaf paths. Solve with hashmap DFS in O(n) — frequent at Amazon and Alibaba.
LeetCode 156 (Medium) classically asked at Google and LinkedIn. Re-root a binary tree by flipping each left child into the new parent and the original parent into the new right child, in O(n) time and O(1) extra space iteratively.
LeetCode 510 (Medium) frequently asked at Microsoft and Facebook. Find the inorder successor of a BST node when each node has a parent pointer, in O(h) time and O(1) extra space without access to the root.
LeetCode 623 (Medium) asked at Amazon and Microsoft. Insert a new row of value v at a given depth, pushing existing children down as left/right subtrees of new nodes, using BFS or DFS in O(n) time.
LeetCode 1302 (Medium) asked at Amazon and Oracle. Sum all node values at the deepest level of a binary tree using BFS level-order traversal in O(n) time and O(w) space.
LC 222 Count Complete Tree Nodes has an O(log^2 n) solution that exploits perfect subtree detection — a FAANG interview problem where the naive O(n) answer is wrong. Learn the left/right spine height comparison trick tested at Amazon and Google.
LC 701 Insert into a BST traverses left or right based on value comparisons until finding a null position. The O(h) recursive solution is a BST fundamentals question tested at Amazon and Microsoft — always insert at a leaf.
LC 427 Construct Quad Tree builds a spatial partitioning tree from a 2D binary grid by recursively splitting non-uniform regions into four quadrants. This divide-and-conquer problem is tested at Amazon and Google and models real-world image compression and spatial indexing.
LeetCode 2265 (Medium). Count every node whose value equals the floor average of its own subtree using a single postorder DFS that returns sum and count to the parent.
Design a Trie with insert, search, and startsWith operations. This is the foundational data structure behind autocomplete, spell checkers, and IP routing tables.
LeetCode 211 walkthrough — implement WordDictionary supporting add and search where the search query can contain a "." wildcard. The optimal solution combines a trie with DFS branching at every wildcard, a textbook FAANG interview pattern.
LeetCode 648 — replace each word in a sentence with the shortest dictionary root that prefixes it. The trie walks one character at a time, returning the first isEnd we hit. A clean autocomplete-style problem.
LeetCode 421 — find the maximum XOR pair in an array of integers in O(N times 32) using a binary trie. The classic introduction to bit-trie pattern that powers competitive programming and database query optimisers.
LeetCode 1268 — return up to three lexicographically smallest products for every prefix of a search query. The trie autocomplete pattern that backs Google search, Amazon product search, and command palettes everywhere.
LeetCode 720 — find the longest word in a dictionary that can be built one character at a time, with each prefix also in the dictionary. Trie + BFS gives lex-smallest tie-breaking for free.
LeetCode 820 — encode a list of words into the shortest reference string where each word appears as a suffix terminated by #. Build a trie of reversed words; only words at trie leaves contribute their length plus one to the answer.
LeetCode 677 — design a structure supporting insert(key, value) and sum(prefix) returning the total of values for all keys with that prefix. The key trick is propagating delta sums along the trie path so prefix queries become a single O(L) walk.
LeetCode 3043 — find the longest common prefix length between any number in arr1 and any number in arr2 (compared as digit strings). A digit trie of arr1 makes each arr2 lookup O(D) where D is the number of digits.
Count the number of distinct substrings of a string. The elegant trick: every substring is a prefix of some suffix, so a suffix trie has exactly one node per distinct non-empty substring. Count nodes during insertion in O(N^2).
LeetCode 1004 Max Consecutive Ones III is a Google and Amazon variable sliding window problem. Track the count of zeros inside the window and shrink from the left whenever it exceeds k to find the longest contiguous run of ones after k flips.
LeetCode 3 Longest Substring Without Repeating Characters is one of the top five most asked questions at Meta and Amazon. Master the variable sliding window with a hash map to solve it in O(n) time and O(min n,m) space.
LeetCode 424 — a classic FAANG sliding window problem (Google, Microsoft, Amazon). Master the max-frequency invariant that powers the optimal O(n) solution.
LeetCode 567 — detect if any permutation of s1 appears as a substring of s2 using a fixed-size sliding window. Frequently asked at Google, Amazon, and Microsoft.
LeetCode 904 — find the longest contiguous subarray with at most two distinct values. A reskinned classic that appears in Google, Amazon, and Microsoft interviews.
LeetCode 1695 — find the maximum sum of a subarray with all unique values using a HashSet sliding window. A favorite at Google and Amazon for testing window invariants.
LC 881 asks for the minimum boats to rescue everyone given a weight limit and at-most-2-per-boat rule. Sort then greedily pair the heaviest with the lightest using two pointers — O(n log n) time, O(1) space.
LC 15 asks for all unique triplets summing to zero. Sort the array, fix each element as the anchor, and use two pointers to scan for pairs — with careful three-level deduplication. A must-know FAANG pattern.
LeetCode 167 Two Sum II is asked at Amazon, Microsoft, Google, and Bloomberg. Solve it in O(n) time and O(1) space with the inward two-pointer technique on a sorted array.
LeetCode 713 Subarray Product Less Than K is asked at Google, Amazon, and Stripe. Count contiguous subarrays in O(n) using a multiplicative sliding window.
LeetCode 1423 Maximum Points You Can Obtain from Cards is asked at Google, Amazon, and Meta. Convert pick-from-ends into a fixed-size minimum-window problem in O(n).
LeetCode 1248 Count Number of Nice Subarrays is asked at Google and Amazon. Convert "exactly k odds" into atMost(k) minus atMost(k-1) for an O(n) solution.
LeetCode 930 Binary Subarrays With Sum is asked at Google, Amazon, and Meta. Count subarrays with exact sum in O(n) using atMost(goal) minus atMost(goal-1).
LeetCode 1838 Frequency of the Most Frequent Element is asked at Google and Amazon. Sort, then slide a window where total cost to lift everything to the rightmost value is at most k.
LeetCode 1658 Minimum Operations to Reduce X to Zero is asked at Amazon, Google, and Meta. Reframe to longest subarray summing to total minus x for an O(n) solution.
LeetCode 845 Longest Mountain in Array is asked at Google, Amazon, and Bloomberg. Find the longest strictly increasing-then-decreasing subarray in O(n) time, O(1) space.
LeetCode 1234 Replace the Substring for Balanced String is asked at Google and Amazon. Find the minimum window to replace in O(n) using a shrinkable sliding window over QWER frequencies.
LC 1888 asks for the minimum flips to make a binary string alternating after any rotations. Double the string and slide a fixed window of size n against both target patterns — the canonical circular sliding window trick.
LC 1456 asks for the maximum vowels in any substring of length k. A canonical fixed-size sliding window — add the new right character, subtract the departing left character, track the running max. O(n) time, O(1) space.
LC 1151 asks for minimum swaps to group all 1s in a circular binary array. Count total 1s to set the window size, then maximize 1s inside any window position using modulo indexing. O(n) time, O(1) space.
LC 2516 asks for the minimum minutes to collect at least k of each character from a string's ends. Flip it: find the longest middle window you can skip so the outside has enough of each character. O(n) time, O(1) space.
LC 1052 maximizes satisfied customers by finding the optimal k-minute grumpiness suppression window. Decompose into a fixed base plus a variable bonus — then find the max-bonus window with a standard fixed-size sliding window. O(n) time, O(1) space.
LC 1208 asks for the longest substring of s transformable to t within total cost maxCost, where each character costs the absolute ASCII difference. Classic variable sliding window: expand right, shrink left while cost exceeds budget. O(n) time, O(1) space.
LC 1358 counts substrings containing at least one a, b, and c. Track the last-seen index of each character — the count of valid substrings ending at position i is min(last_seen) + 1. O(n) time, O(1) space.
LC 974 counts subarrays whose sum is divisible by k using prefix sums modulo k and a frequency map of remainders. O(n) time, O(k) space. The standard FAANG pattern for all modular subarray problems.
LeetCode 487 asked at Microsoft, Meta, and Amazon. Track the last zero index instead of a counter to handle the streaming follow-up in O(n) time and O(1) space.
LC 2260 asks for the shortest consecutive sequence of cards containing a matching pair. Track the last-seen index of each card value — update the minimum window each time a duplicate is encountered. O(n) time, O(n) space.
Find the longest contiguous subarray of 1s after deleting exactly one element. Reframe as "longest window with at most one zero," then subtract 1 for the mandatory deletion. A clean shrinkable window problem.
Sort an array of 0s, 1s, and 2s in one pass with no extra space using the Dutch National Flag algorithm. Three pointers maintain sorted invariants for all three partitions simultaneously.
Check if a string can become a palindrome by deleting at most one character. Two pointers from both ends; on the first mismatch, try skipping left or skipping right and check if either remainder is a palindrome.