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.
Master reversing nodes in groups of k in a linked list — the classic hard interview problem asked at Amazon, Google, Facebook, and Microsoft. Learn both the elegant recursive solution and the iterative approach with clear pointer diagrams.
Master two optimal approaches to merge k sorted linked lists: min-heap for O(n log k) time and divide-and-conquer for O(n log k) with lower constant factors. A top-tier interview problem at Amazon, Google, Facebook, Microsoft, and Uber that tests your mastery of heaps and recursive merging.
Master bottom-up merge sort on a linked list for O(n log n) time and O(1) space — eliminating the O(log n) recursive stack. A hard interview problem at Amazon, Google, and Facebook that demonstrates deep understanding of merge sort and linked list mechanics.
Learn the optimal O(n) approach to convert a sorted linked list to a height-balanced BST using in-order construction — consuming list nodes sequentially without finding the midpoint each time. A clever interview technique at Amazon, Google, and Microsoft that demonstrates advanced recursion thinking.
Build an LRU Cache from scratch using a doubly linked list with sentinel nodes and a HashMap for O(1) get and put operations. The most frequently asked hard design problem at Amazon, Microsoft, Google, and Facebook — explained step by step with diagrams.
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.
LC 28 Find the Index of the First Occurrence in a String is the canonical KMP problem at Google, Meta, and Amazon. Build the failure function in O(m), search in O(n), and never re-examine a matched character again.
Ace behavioral interviews in 2026 with the STAR method, a full breakdown of Amazon Leadership Principles, a reusable story bank framework, and word-for-word answer examples for the 10 most common questions. For engineers targeting FAANG and senior-level roles.
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.
Use Tarjan's low-link technique to find every bridge (critical edge) and articulation point (cut vertex) in an undirected graph in O(V + E). The interview pattern behind LeetCode 1192 Critical Connections, asked at Google, Meta, and Amazon.
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 advanced Dijkstra: state augmentation, K-stop limits, two-cost optimisation, k-th shortest paths, and modified relaxation. The interview pattern behind LeetCode 787, 1928, and 1976, asked at Google, Amazon, and Meta.
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 LeetCode 1192 Critical Connections in a Network: a textbook Tarjan bridge-finding algorithm using DFS with discovery times and low-link values to detect every edge whose removal disconnects the graph. A FAANG hard graph interview classic at Google, Amazon, and Meta.
Master LeetCode 332 Reconstruct Itinerary using Hierholzer's algorithm: a single DFS that traverses every edge exactly once and assembles an Eulerian path via post-order insertion. A FAANG hard interview classic asked at Google, Meta, and Amazon, and the foundational pattern for de Bruijn sequences and DNA fragment assembly.
Master LeetCode 778 Swim in Rising Water by reducing a grid puzzle to a minimax shortest-path problem. Solve it three ways — Dijkstra with max-relax, binary search plus BFS, and Kruskal-style union-find — and learn when each approach wins. A FAANG hard interview classic 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.
A complete walkthrough of network flow for FAANG interviews: the max-flow min-cut theorem, Ford-Fulkerson, Edmonds-Karp BFS-augmenting paths, residual graphs, and practical applications including bipartite matching and project selection. Asked at Google, Amazon, and Meta as a senior-level systems-design-meets-algorithms screen.
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 1 — Two Sum is the most-asked Amazon, Google, and Meta phone screen warmup. Single-pass hash map gives O(n) time and unlocks the complement-lookup pattern.
LeetCode 121 — track the running minimum and the running best profit in a single linear pass. The cleanest greedy pattern asked at Amazon, Google, and Microsoft.
LeetCode 217 asks whether any value repeats in an array. The hash set answer runs in O(n) time and O(n) space. This guide compares it against sorting and brute force, shows why hash sets degrade to O(n) in the worst case, and works through the Contains Duplicate II and III follow-ups interviewers actually ask next.
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.
LeetCode 283 — move all zeroes to the end while keeping nonzero order, in place and in O(n). The write pointer technique tested at Meta, Amazon, and Microsoft.
LeetCode 66 — increment a large integer represented as a digit array, propagating the carry. The deceptively simple FAANG warmup that catches careless coders.
Master the write pointer pattern — the canonical technique for in-place array modification. Full walkthrough of LeetCode 26 with visual dry run, common mistakes, and the LC 80 generalization. Python and JavaScript solutions included.
Find the one element that appears once while every other appears twice. The XOR bit trick delivers O(n) time and O(1) space — no extra memory, no sorting. Master the three XOR properties that make it work, then see how interviewers escalate to Single Number II and III.
Two problems, one pair of concepts: LC 349 asks for the unique intersection (HashSet), LC 350 asks for the frequency-aware intersection (HashMap). Master all three approaches for LC 349 — HashSet, sort+two pointers, binary search — then learn why the follow-up questions on LC 350 are what Google and Amazon actually care about: sorted input, skewed sizes, and data that does not fit in memory.
Master Pascal's Triangle (LeetCode 118 & 119) by understanding the binomial coefficient connection, the row-by-row DP pattern, space-optimized O(k) single-row generation, and five hidden mathematical properties that show up in Unique Paths, Coin Change, and beyond.
Master LeetCode 242 Valid Anagram with three approaches — sort O(n log n), 26-element frequency array O(n)/O(1), and HashMap O(n)/O(k). Includes a visual dry run, the critical Unicode follow-up, and the direct connection to Group Anagrams (LC 49).
LeetCode 387 is deceptively simple — but the way you solve it, explain it, and handle its follow-ups separates candidates who get the offer from those who do not. Master the two-pass frequency map, understand why O(1) space is possible, and be ready for every streaming and ordering twist Amazon throws at you.
Count primes below n sounds trivial — until your naive solution times out on n=5,000,000. Master the Sieve of Eratosthenes, one of the most elegant algorithms in all of computer science, and learn the exact intuition that separates candidates who pass Amazon and Google screens from those who do not.
LeetCode 268 hides four distinct valid solutions behind a deceptively simple problem. Learn Sort, HashSet, Gauss Formula, and XOR — understand exactly why each exists, when interviewers ask for each one, and why XOR is the most elegant answer in the room.
The Boyer-Moore Voting Algorithm solves LeetCode 169 in O(n) time and O(1) space using a brilliantly counterintuitive cancellation trick. Learn the proof, the dry run, all four approaches, and why interviewers love this problem — plus the Majority Element II follow-up that extends the same idea to two candidates.
Design a class to track the kth largest element in a live data stream. Learn why a min-heap of exactly k elements is the perfect data structure, trace through a full dry run, avoid the classic pitfalls, and walk away with clean Python and JavaScript solutions ready for FAANG interviews.
LeetCode 1480 is the gateway to one of the most powerful patterns in competitive programming and FAANG interviews: prefix sums. Master the in-place O(1) space solution, understand why the prefix sum array unlocks O(1) range queries, and learn the real follow-up questions — range sum queries, subarray sum equals K, and 2D matrix prefix sums — that interviewers ask once you solve this problem in thirty seconds.
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 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.
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 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 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 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 268 — asked at Amazon, Microsoft, and Google. Find the missing number from 0 to n using the Gauss sum formula in O(n) time and O(1) space. Alternatively use XOR for a bit-manipulation approach. Both are classic array interview questions at FAANG companies.
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 228 — asked at Amazon, Google, and Microsoft. Collapse a sorted unique integer array into the smallest list of ranges. Use a two-pointer linear scan to detect where consecutive runs break. O(n) time, O(1) space — clean and fast.
LeetCode 135 — asked at Amazon, Google, and Microsoft. Give each child the minimum candies so higher-rated neighbors get more. Two greedy passes: left-to-right for left-neighbor constraint, right-to-left for right-neighbor constraint. O(n) time, O(n) space.
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 796 — asked at Amazon and Google. Check if string s can become string goal by rotating. The elegant O(n) trick: concatenate s with itself and check if goal is a substring. One line of code once you see the insight.
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.
LeetCode 42 — one of the most asked hard problems at Amazon, Google, Microsoft, and Meta. Compute trapped rainwater using two pointers in O(n) time and O(1) space. The key: water at any position is min(left_max, right_max) minus the height. Move the pointer with the smaller max inward.
LeetCode 239 — asked at Amazon, Google, and Microsoft. Find the maximum in each sliding window of size k in O(n) using a monotonic decreasing deque. The deque stores indices in decreasing order of value — pop from front when out of window, pop from back when current element is larger.
LeetCode 41 — asked at Amazon, Google, and Microsoft. Find the smallest missing positive integer in O(n) time and O(1) space. Use the array itself as a hash map: place each number i at index i-1, then scan for the first mismatch. The answer must be in [1, n+1].
LeetCode 84 — asked at Amazon, Google, and Microsoft. Find the largest rectangle in a histogram using a monotonic increasing stack. For each bar, find the nearest shorter bars on both sides to compute the maximum width. O(n) time, O(n) space.
Master LeetCode 76 — the gold-standard Hard sliding window problem asked at Google, Meta, and Amazon. Learn the "formed" counter trick that reduces window validity checks from O(|t|) to O(1), trace through a full dry run, and avoid the five bugs that most often break this one.
Master LeetCode 315 — one of the most common FAANG hard problems. Learn why a naive O(n²) scan fails at scale, how merge sort secretly counts inversions as a side effect, and how to trace through every swap on paper. Includes both brute-force and optimal solutions in Python and JavaScript, a full complexity table, and the three follow-up problems that frequently appear in the next interview round.
LeetCode 4 is one of the most feared Hard problems in FAANG interviews. Learn exactly why the partition insight works, trace through a full binary search dry run, understand the five common bugs that cause silent wrong answers, and walk away with production-quality Python and JavaScript solutions.
Master LeetCode 85 — Maximal Rectangle by building on LC 84 Largest Rectangle in Histogram. Learn the row-as-histogram insight, a visual row-by-row dry run, common pitfalls, and clean Python + JavaScript solutions that interviewers love.
LeetCode 493 trips up even strong candidates because the count step must happen before the merge step — not during it. Learn exactly why that ordering matters, trace through a full dry run on [1,3,2,3,1], understand the five most common bugs, and walk away with clean Python and JavaScript solutions you can reproduce under pressure.
Master LeetCode 410: learn why binary searching on the answer (not the array) is the key insight, walk through a full greedy feasibility check, and see both the DP and binary search solutions with line-by-line commentary.
Negative numbers completely break the classic sliding window for minimum-length subarray problems. Learn exactly why, then master the only correct approach — a monotonic deque on prefix sums — with a step-by-step visual trace, the three mistakes every candidate makes, and every real interview follow-up with approach hints.
Master LeetCode 327 — Count of Range Sum — with deep intuition, a visual dry run, brute-force to O(n log n) merge sort progression, and real interview follow-ups covering BIT, LC 315, and LC 493.
Master LC 871 with two complementary strategies: a greedy max-heap that asks "which station gives me the most fuel when I am stuck?" in O(n log n), and a DP table that asks "what is the farthest I can reach with exactly k stops?" in O(n²). Both are asked at Amazon and Google. Learn the intuition, see a full dry run, and understand when each approach fits.
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.
LeetCode 149 asks you to find the maximum number of collinear points on a 2D plane. The trick is representing slope as a GCD-reduced integer fraction — no floats, no precision bugs — and using a HashMap to count how many points share the same slope relative to each anchor. This post covers the full intuition, a step-by-step visual dry run, every edge case (vertical lines, duplicates, sign normalization), well-commented Python and JavaScript solutions, and the real FAANG follow-up questions that separate good candidates from great ones.
LeetCode 32 is one of the most deceptive Hard problems on the platform — the brute-force is obvious, but all three optimal solutions require genuinely different mental models. Master the index-sentinel stack, the DP recurrence, and the two-pass counter sweep, and you will be able to answer any follow-up a FAANG 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.
LC 992 is one of the cleanest examples of a non-obvious reduction in competitive programming. Learn the "exactly K = atMost(K) minus atMost(K-1)" insight, trace through a full visual dry run, and understand how this single pattern unlocks five related hard problems in one shot.
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.
LeetCode 704 — the foundational FAANG binary search problem solved in O(log n) using the classic three-way exact-match template with overflow-safe midpoint.
LeetCode 278 — find the first bad version among n versions in O(log n) API calls using left-boundary binary search, the canonical FAANG predicate-search problem.
LeetCode 35 — find the index where a target exists or should be inserted in a sorted array. The canonical FAANG left-boundary binary search and the from-scratch implementation of bisect_left.
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.
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 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.
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 4 is the most famous FAANG hard problem. Solve the median of two sorted arrays in O(log(min(m,n))) by binary searching for the correct partition position.
LeetCode 315 is a Google and Amazon classic. Count how many elements to the right are smaller than each element using merge sort with index tracking or a Fenwick Tree, both running in O(n log n).
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 1891 finds the maximum ribbon length such that we can cut at least k pieces. A clean O(n log max) binary-search-on-answer template every interviewer expects.
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.
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 1351 asks you to count negatives in a matrix sorted both row-wise and column-wise. The O(m+n) staircase approach is optimal; an O(m log n) binary-search-per-row alternative is also acceptable. Both demonstrate how sorted structure eliminates naive O(mn) scanning.
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 1346 asks if any element and its double both appear in an array. The optimal O(n) hash set approach processes elements one by one. An O(n log n) sort-and-binary-search alternative demonstrates the binary search pattern. A good warm-up for two-sum variants.
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).
Find the kth smallest element from two sorted arrays in O(log(m+n)) without merging. Binary elimination: compare the k/2-th element of each array; the smaller one cannot contain the kth element, so eliminate k/2 candidates. Builds directly to LC 4 (Median of Two Sorted Arrays).
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.
Master bit manipulation for FAANG interviews: XOR tricks, popcount, bitmask DP, Brian Kernighan, two-complement identities, and 5-language operator reference with full problem index.
LC 136 Single Number is the canonical XOR interview problem. Every duplicate cancels itself via a^a=0, leaving only the unique element. Master this identity and every follow-up variant before your next coding screen.
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 191 Number of 1 Bits: count set bits using Brian Kernighan trick n & (n-1). Foundational popcount technique that every FAANG interviewer expects you to know cold.
LeetCode 338 Counting Bits: compute popcount for every integer 0..n in O(n). Master the elegant DP recurrence dp[i] = dp[i >> 1] + (i & 1) that FAANG interviewers love.
LeetCode 190 Reverse Bits: reverse the binary representation of a 32-bit unsigned integer. Master the shift loop and the elegant divide-and-conquer mask reversal used in real-world DSP and crypto code.
LeetCode 268 Missing Number: find the one missing integer in [0..n] using XOR cancellation or the Gauss arithmetic-series formula. Two O(n) techniques every FAANG interviewer expects you to compare.
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 1879 Minimum XOR Sum of Two Arrays — pair every element of nums1 with a unique element of nums2 to minimize total XOR. Bitmask DP turns assignment into a 2^n state space. Step-by-step bit manipulation walkthrough for FAANG interviews.
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 1178 Number of Valid Words for Each Puzzle — count words containing the puzzle’s first letter using only puzzle letters. The 26-bit bitmask plus the (sub - 1) AND parent submask trick crushes a brute-force quadratic solution.
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.
Strategic playbook for FAANG-specific DSA preparation. Covers Google graph and DP focus, Meta tree and string emphasis, and Amazon Leadership Principles alignment with BFS, heap and design problems.
Count the number of islands after each addLand operation using incremental Union-Find with path compression. Amazon tests this to evaluate dynamic graph connectivity and disjoint set data structures.
Design a class to find the kth largest element in a stream using a min-heap of size k. Amazon tests this to evaluate heap design, streaming data patterns, and online algorithm thinking.
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.
Merge k sorted linked lists into one sorted list using a min-heap for O(N log k) efficiency. Amazon uses this to test heap-based k-way merge, a critical pattern in distributed data systems.
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.
Master Two Sum and its variants — 3Sum, 4Sum, Two Sum II — using hashmap for O(N) and two pointers for sorted arrays. Amazon relies on this problem family to assess foundational array skills and generalization ability.
Find the median of two sorted arrays in O(log(min(m,n))) using binary search on partition points. Amazon and Google use this hard problem to test binary search on abstract criteria and numerical reasoning under pressure.
A complete cheatsheet of FAANG company-specific DSA problems, patterns, and optimal approaches. Use this as your final review before any Meta, Amazon, or Google coding interview.
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 70 Climbing Stairs is the canonical introduction to 1D dynamic programming. The recurrence dp[n] = dp[n-1] + dp[n-2] is pure Fibonacci, and mastering why it works — recursion to memoization to tabulation — unlocks the entire family of staircase DP problems asked at Google, Amazon, and Meta.
LC 746 Min Cost Climbing Stairs extends the Climbing Stairs Fibonacci DP with per-step costs. The recurrence dp[i] = cost[i] + min(dp[i-1], dp[i-2]) computes the minimum total cost to leave each step. Asked at Amazon and Google as a direct test of whether you can adapt a known recurrence pattern under new constraints.
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 53 Maximum Subarray is the foundational problem behind Kadane's Algorithm — a deceptively simple O(n) DP that asks: at each position, should I extend the current subarray or start fresh? Asked at Amazon, Google, and Microsoft and the basis for Maximum Product Subarray and other contiguous-subarray problems.
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 354 Russian Doll Envelopes is a sneaky 2D Longest Increasing Subsequence problem. Sort by width ascending and height descending so equal widths cannot stack, then run patience-sort LIS on heights for an O(n log n) DP solution beloved by FAANG interviewers.
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.
The complete 2D Dynamic Programming roadmap for FAANG interviews — LCS, Edit Distance, grid path counting, interval DP, stock state machines, and 2D knapsack with Python and JavaScript templates.
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 72 Edit Distance (Levenshtein Distance) is the hard-level sequence DP benchmark at Google, Amazon, and Meta. Master the 3-operation recurrence, space-optimize to O(n), and understand how this algorithm powers spell-checkers, DNA alignment, and autocomplete systems.
LC 1092 Shortest Common Supersequence combines LCS computation with DP table reconstruction to produce the actual shortest string containing both inputs as subsequences. A hard-level 2D DP problem asked at Google and Amazon that demands both algorithm depth and reconstruction skill.
LC 312 Burst Balloons is the classic hard-level interval DP problem asked at Google, Amazon, and Meta. The key insight is thinking in reverse — instead of choosing which balloon to burst first, choose which one to burst last in each interval. This transforms an impossible ordering problem into clean O(n^3) DP.
LC 121 Best Time to Buy and Sell Stock is the foundational stock DP problem at every FAANG company. While solvable with a one-pass greedy approach, understanding its state machine formulation (hold/not-hold states) unlocks the full stock problem series from LC 122 through LC 714.
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 123 Best Time to Buy and Sell Stock III limits transactions to at most 2. The state machine tracks 4 explicit states — buy1, sell1, buy2, sell2 — evolving each day through clean transitions. This is the hardest single-interview stock variant and the direct precursor to the k-transactions generalization in LC 188.
LC 188 Best Time to Buy and Sell Stock IV generalizes the stock problem to at most k transactions using a 2D DP table where dp[t][i] tracks the maximum profit using t transactions through day i. This is the hardest stock variant in FAANG interviews and requires combining the k-transaction state machine with the unlimited-transaction shortcut for large k.
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 44 Wildcard Matching is the classic 2D string DP question Meta and Google ask to test recurrence design under tricky base cases. We derive the dp[i][j] transitions for ? and *, dry-run a full table, and finish with a two-pointer optimization that drops memory to O(1).
LeetCode 174 Dungeon Game is the textbook example of why DP direction matters. We derive why forward DP fails, build the backward dp[i][j] = max(1, ...) recurrence, dry-run the grid, and finish with a space-optimized 1D solution loved at FAANG.
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.
LeetCode 664 Strange Printer is the canonical O(n^3) interval DP every senior FAANG interviewer expects you to handle. We derive the dp[i][j] recurrence, walk through the merge-on-match optimization, dry-run a full table, and discuss where Strange Printer sits in the Burst Balloons / MCM family.
The full 2D Dynamic Programming cheatsheet for FAANG interviews — seven pattern transitions, stock state machine, interval DP template, LCS reconstruction, and the complete problem index.
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.
Solve LeetCode 733 Flood Fill with simple DFS in O(m*n) time. The paint bucket tool from MS Paint reduced to a five-line recursion — the cleanest introduction to grid traversal you can give an interviewer.
Solve LeetCode 463 Island Perimeter in O(m*n) without DFS or BFS. The trick: every land cell contributes 4 edges, minus 2 for each shared edge with another land cell. Pure counting beats traversal.
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.
LC 286 Walls and Gates asks you to fill each empty room with its distance to the nearest gate. The key insight is to flip the direction: instead of BFS from every room, do multi-source BFS from all gates simultaneously and push distances outward in O(m*n) time.
LC 1020 Number of Enclaves asks you to count land cells that cannot reach the grid boundary. The trick is to flip the problem: flood-fill from the boundary inward, eliminating all reachable land, then count what remains.
LC 1905 Count Sub Islands asks how many islands in grid2 are subsets of islands in grid1. The critical trap is short-circuiting DFS on the first invalid cell — you must always complete the traversal to mark the whole island visited, while tracking validity separately.
Flip at most one 0 to 1 to maximize island area. The "color the islands, then try every flip" trick avoids quadratic re-DFS — a top Google interview problem.
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.
Process land additions one at a time and report the island count after each. Union-Find makes each query nearly O(1) amortized — the canonical online connectivity interview problem.
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.
A reachability check between two vertices in an undirected graph. Three optimal approaches: BFS, DFS, and Union Find — each with different trade-offs for follow-up questions about dynamic edges.
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 127 Word Ladder asks for the shortest sequence of one-letter transformations from beginWord to endWord, where every intermediate word must be in the dictionary. BFS on the implicit word-state graph finds the minimum in O(M^2 * N) using wildcard pattern grouping.
LeetCode 126 Word Ladder II asks for every shortest transformation path between two words. Master the layered BFS plus parent-map DFS pattern that survives the brutal time limits at Amazon, Google, and Facebook interviews.
LeetCode 815 Bus Routes is deceptively hard. The trick is that BFS levels count buses, not stops, so the graph you traverse is a route graph. Master the stop-to-routes inversion that beats the time limit at FAANG interviews.
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 882 Reachable Nodes in Subdivided Graph blends Dijkstra with an edge-budget counting trick. Master the optimal pattern that interviewers at Google and Amazon use to filter senior candidates.
LeetCode 455 Assign Cookies is a Google and Amazon warm-up that teaches the greedy exchange argument. Sort both arrays and use two pointers to satisfy the maximum number of children in O(n log n).
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.
LeetCode 135 Candy is an Amazon, Google, and Apple Hard that turns into a 10-line problem when you spot the two-pass greedy. Sweep left then right and take the max to satisfy both rating constraints.
LC 496 Next Greater Element I is the canonical entry point for monotonic stack thinking. Master the decreasing stack pattern and hash map lookup here, and you will recognize the same structure in Daily Temperatures, Largest Rectangle in Histogram, and Trapping Rain Water.
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 84 Largest Rectangle in Histogram is the canonical hard monotonic stack problem. The key insight — use an increasing stack and compute maximum rectangle area when a shorter bar causes a pop — unlocks both this problem and Maximal Rectangle.
LC 42 Trapping Rain Water is one of the most famous hard problems in FAANG interviews. The optimal two-pointer approach uses O(1) space. Knowing all three approaches and their trade-offs separates senior candidates from junior ones.
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 85 Maximal Rectangle is a hard problem that reduces to running Largest Rectangle in Histogram on each row. Build cumulative height histograms row by row and apply the O(n) monotonic stack solution — the reduction is the key insight.
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.
Master the hashmap interview patterns that power 87 percent of FAANG O(1) lookup questions: complement maps, frequency counting, prefix-sum hashing, two-way bijections, and cache design across 45 LeetCode problems.
LeetCode 1 Two Sum is the most asked FAANG hashmap interview question. Master the one-pass complement HashMap that turns the brute-force O(n^2) into O(n).
LeetCode 242 Valid Anagram is a top FAANG warm-up that trains the frequency-array hashmap pattern reused in Group Anagrams, Find All Anagrams, and Minimum Window Substring.
LeetCode 383 Ransom Note is a FAANG warm-up that trains the supply-versus-demand frequency hashmap pattern reused in inventory, scheduling, and rate-limit interview questions.
LeetCode 205 Isomorphic Strings is a classic FAANG hashmap interview question that trains the bidirectional bijection check used in cipher validation, schema mapping, and Word Pattern.
LeetCode 202 Happy Number is a FAANG hashmap interview classic that trains HashSet cycle detection and the Floyd two-pointer alternative for O(1) space.
LeetCode 219 Contains Duplicate II is a FAANG hashmap interview question that trains the last-seen-index pattern and the bounded sliding-window HashSet alternative.
Find Common Characters teaches frequency intersection — the element-wise minimum of character counts across multiple strings. This pattern appears in multi-set intersection problems, resource allocation, and constraint satisfaction at tech company interviews.
Jewels and Stones is the cleanest demonstration of the "build a lookup set, then query it" pattern. While the problem itself is easy, the skill it teaches — converting a repeated linear search into O(1) lookups — is fundamental to optimizing real-world code.
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.
Unique Number of Occurrences teaches the double-hash technique: build a frequency map, then check if all frequency values are distinct. This two-layer hashing pattern appears in data validation, duplicate detection, and constraint checking problems at every major company.
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 653 (Easy) asks if any two nodes in a BST sum to k. Google, Facebook, and Amazon frequently use it as a warm-up to test whether you can combine DFS traversal with the Two Sum hash-set pattern.
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.
Implement a HashMap from scratch using an array of buckets with chaining for collision resolution — the foundational data structure interview that every engineer should be able to implement cold.
Implement a HashSet from scratch using either a bit array for dense integer keys or chaining for general keys — the implementation-level interview that tests your understanding of set data structures.
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 819 Most Common Word finds the most frequent non-banned word in a paragraph using normalization, regex tokenization, and a frequency hash map — a practical string-processing problem tested at Amazon and Microsoft.
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.
LC 460 LFU Cache implements O(1) get and put using three hash maps and ordered per-frequency buckets — one of the most complex design problems in FAANG interview prep, seen at Google and Amazon for senior roles.
LC 432 All O'one Data Structure supports inc, dec, getMaxKey, and getMinKey all in O(1) using a doubly linked list of frequency buckets — one of the most elegant O(1) designs in FAANG interview prep.
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.
Find all index pairs (i, j) such that words[i] + words[j] forms a palindrome, using a reverse-word hashmap and systematic prefix/suffix palindrome splits in O(N * K^2) time. A FAANG hard problem that fuses string algorithms with hash table mastery.
Solve LeetCode 1046 Last Stone Weight, a classic Amazon and Google warmup that teaches max-heap simulation by repeatedly smashing the two heaviest stones.
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 295 (Hard) — a FAANG favorite. Maintain a dynamic median from a live data stream using two heaps: a max-heap for the lower half and a min-heap for the upper half, achieving O(log n) per insert.
LeetCode 23 (Hard) — the most-asked heap problem at FAANG. Merge k sorted linked lists in O(N log k) using a min-heap that always tracks the smallest active head.
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.
LeetCode 630 (Hard) — a Google scheduling classic. Maximize courses you can finish before deadlines using a greedy max-heap that swaps out the longest course when budget overflows.
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.
Maximize capital after k IPO investments by unlocking affordable projects into a max-profit heap — a sophisticated two-heap greedy problem asked at Google, Amazon, and Facebook that models real-world portfolio optimization.
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 407 Trapping Rain Water II is a Google and Meta hard interview problem. Solve it with min-heap BFS that processes the elevation map inward from the border in O(mn log(mn)).
LeetCode 778 Swim in Rising Water is a Google and Amazon hard problem disguised as Dijkstra. Solve it with a min-heap that minimizes the maximum elevation along any path in O(N^2 log N).
LeetCode 632 Smallest Range Covering Elements from K Lists is a Google and Meta hard interview problem. Solve it with a K-way merge min-heap that maintains a sliding range across K sorted lists in O(N log K).
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 871 Minimum Number of Refueling Stops is an Amazon and Google hard interview problem. Use a max-heap to greedily pick the richest station retroactively in O(N log N).
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 1383 Maximum Performance of a Team is a Google and Amazon hard interview classic. Use a sorted sweep over efficiency with a size-k min-heap of speeds to compute the answer in O(N log N).
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).
LeetCode 895 Maximum Frequency Stack is an Amazon, Google, and Meta hard design interview problem. Achieve O(1) push and pop using frequency-bucket stacks — beating the naive max-heap approach.
LeetCode 1675 Minimize Deviation in Array is a Google and Amazon hard interview problem. Reduce it to a one-directional max-heap by doubling odds upfront, then halve the max iteratively in O(N log N log M).
Compute the median for each sliding window using two heaps with lazy deletion — the definitive template for dynamic order statistics in interview problems.
Answer range-coverage queries offline by sorting both intervals and queries, sweeping through with a min-heap ordered by interval size — a canonical offline query pattern.
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.
Sort an array by element frequency ascending (ties broken by value descending) using a frequency map and custom comparator — a clean problem that tests mastery of custom sort keys.
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.
LeetCode 2099 solved with a heap-based top-K selection followed by an index-preserving reconstruction. Tests whether you can decouple selection from ordering — a classic FAANG screening pattern.
A complete linked list interview playbook covering 7 core patterns (reversal, fast/slow, dummy head, merge, in-place, clone, design) with copy-paste templates and a curated index of 45 LeetCode problems mapped to every pattern.
LeetCode 206 Reverse Linked List is the foundational pointer-manipulation problem at FAANG interviews. Master the iterative three-pointer rewiring and the recursive call-stack reversal — both are used as subroutines in dozens of harder problems.
LeetCode 876 Middle of the Linked List teaches the fast/slow pointer technique that appears in half of all linked-list interview problems. Find the middle node in one pass with zero extra space, and understand exactly which middle you get for even-length lists.
LC 141 Linked List Cycle is a classic interview question asked by Amazon, Microsoft, and Google that tests your mastery of the two-pointer fast/slow technique. Learn Floyd's tortoise and hare algorithm with a visual dry run, Python and JavaScript solutions, and key interview tips.
LC 21 Merge Two Sorted Lists is one of the most frequently asked linked list interview problems at Amazon, Google, and Microsoft. Learn the dummy head merge pattern with step-by-step Python and JavaScript solutions, visual dry run, and interview tips.
LC 234 Palindrome Linked List is a popular interview problem at Facebook, Amazon, and Apple that combines three core techniques: fast/slow pointer midpoint finding, in-place list reversal, and two-pointer comparison. Master the O(1) space solution with Python and JavaScript code and a step-by-step dry run.
LC 160 Intersection of Two Linked Lists is a popular O(1) space interview question at Amazon, Facebook, and Microsoft. Learn the elegant two-pointer length-equalizer trick, the mathematical proof behind why it works, visual dry run, and Python/JavaScript solutions.
LC 1290 Convert Binary Number in a Linked List to Integer is an easy interview problem that combines linked list traversal with binary number conversion. Learn the elegant bit-shift accumulation pattern with Python and JavaScript solutions, dry run, and interview tips.
LC 203 Remove Linked List Elements is a fundamental interview problem asked at Google and Amazon that teaches the dummy head sentinel pattern for handling head deletion cleanly. Learn O(n) solutions in Python and JavaScript with visual dry run, common mistakes, and recursive variant.
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 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.
Master mathematical algorithms for FAANG DSA interviews: primes, GCD, modular arithmetic, fast exponentiation, combinatorics, and number theory with complexity reference and full problem index.
LC 204 Count Primes is the gateway sieve problem at Google and Amazon. Master the Sieve of Eratosthenes, understand why you start marking at p*p, and apply the technique to interval queries, prime factorization, and every sieve variant an interviewer can ask.
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.
Number theory basics — divisibility, congruences, digit DP, perfect numbers — power half of the math problems at Amazon and Microsoft. Master the divisibility rules, modular congruence properties, and digit-extraction tricks before tackling advanced number theory.
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.
Complete reference for math and number theory DSA patterns: algorithm selection guide, complexity table, template library, and top 25 interview problems ranked by FAANG frequency.
Week 4 of the FAANG mock program runs full company-specific simulations matching the actual format, difficulty mix, and evaluation rubric of Google, Meta, and Amazon. The same problem communicated differently wins different ratings at each company.
Map Amazon's 16 Leadership Principles to coding and behavioral interview behaviors. Includes the LP-to-question mapping, how to weave LP language naturally into technical explanations, the Bar Raiser format, and a per-LP preparation template.
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 51 N-Queens is the gold standard for testing backtracking, constraint propagation, and bit-mask elegance. Master row-by-row placement, three diagonal-tracking sets, and the bitmask trick that runs N=15 in milliseconds.
LC 37 Sudoku Solver is the most-asked constraint-satisfaction problem in tech interviews. Master row, column, and box bitsets, MRV heuristic ordering, and the cell-by-cell decision tree that solves any 9x9 grid in milliseconds.
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.
Solve the Knight's Tour with backtracking and Warnsdorff's heuristic. Visit every square exactly once on an n by n board with O(8^(n^2)) brute force tamed by smart move ordering.
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.
Master Segment Trees and Binary Indexed Trees for FAANG interviews: range sum, min, max queries, point updates, lazy propagation, 2D BIT, and full problem index with complexity reference.
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.
Count smaller elements to the right of every index using a Binary Indexed Tree (Fenwick Tree) with coordinate compression. The cleanest O(n log n) solution every interviewer expects.
Count pairs (i, j) with i less than j and nums[i] greater than twice nums[j]. The classic Hard problem for modified merge sort and BIT counting — the two techniques every senior interviewer expects.
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.
Track range coverage with addRange, removeRange, and queryRange. Maintain disjoint intervals in a sorted map for amortized O(log n) — the canonical interview problem for interval merging logic.
Track the tallest stack height as squares fall onto a number line. The textbook problem for segment trees with lazy propagation, range max queries, and range-assign updates.
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.
Solve LeetCode 732 My Calendar III using a sweep-line difference array in O(n) per booking, then upgrade to a dynamic lazy segment tree with coordinate compression for O(log n) range updates and max queries.
Crack LeetCode 363 Max Sum of Rectangle No Larger Than K by fixing two row boundaries to collapse 2D into 1D, then using prefix sums plus a sorted set (or BIT/segment tree) to find the best subarray sum bounded above by K.
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.
The definitive guide to every stack and queue pattern asked in FAANG interviews — monotonic stack, BFS, two-stack tricks, deque, and design problems with templates and a 50-problem index.
Master the Valid Parentheses problem using a stack to match nested brackets in O(n) time. The canonical LIFO warm-up problem asked at Google, Meta, Amazon, and Microsoft — learn the hash-map trick and every edge case.
Implement a LIFO stack using only queue operations. Learn both the single-queue rotation trick and the two-queue approach — a classic data-structure design problem that tests your understanding of LIFO vs FIFO at FAANG interviews.
Implement a FIFO queue using two stacks with amortized O(1) push and pop. The two-stack lazy-transfer trick is a FAANG interview staple that demonstrates deep understanding of amortized complexity and LIFO vs FIFO semantics.
Design a stack that supports push, pop, top, and getMin in O(1) time using a parallel min-tracking stack. A classic FAANG design interview problem testing stack invariants and auxiliary state maintenance.
Simulate a baseball scoring game using a stack to handle score records, doubles, sum operations, and cancellations in O(n) time. A clean stack-simulation problem that tests your ability to model stateful operations with LIFO access.
Compare two typed strings after applying backspace characters using a stack simulation or O(1) space two-pointer from the right. Covers both approaches with full complexity analysis and FAANG interview tips.
Find the minimum operations to return to the root folder by simulating file system navigation with a stack depth counter in O(n) time and O(1) space. A clean warm-up problem testing stack simulation and boundary conditions.
Count ping requests within the last 3000ms using a FIFO queue that evicts expired timestamps from the front in O(1) amortized time. A clean introduction to the sliding window queue pattern used in rate limiters and real-time counters.
Remove adjacent pairs of same letters with different cases using a stack that processes each character and cancels bad pairs immediately. A clean application of the stack-based adjacent-pair-removal pattern common in FAANG string interviews.
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 for each query using a monotonic stack on nums2 and a hash map lookup in O(n+m) time. A classic application of the monotonic stack pattern combined with hash map lookups for efficient query answering.
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.
Find the maximum in every sliding window of size k using a monotonic decreasing deque that maintains candidate indices in O(n) total time. The hardest and most elegant deque problem — mastering this unlocks Shortest Subarray with Sum At Least K and Jump Game VI.
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 127 Word Ladder using BFS with a queue and a wildcard pattern map for O(1) neighbor lookups. A FAANG hard at Amazon, Google, Meta, and Microsoft that tests BFS on implicit graphs.
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 1944 Number of Visible People in a Queue in O(n) using a monotonic decreasing stack. A FAANG hard interview problem at Amazon, Google, and Meta that uses LIFO stack semantics for visibility queries.
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.
Solve LeetCode 84 Largest Rectangle in Histogram in O(n) using a monotonic increasing stack. The single most important monotonic stack interview problem at FAANG.
Solve LeetCode 85 Maximal Rectangle in O(m times n) by reducing each row to a histogram and applying the monotonic stack. A FAANG hard interview classic.
Solve LeetCode 224 Basic Calculator with a single-pass stack approach handling +, -, parentheses, and arbitrary whitespace in O(n). A FAANG hard parsing classic.
Solve LeetCode 295 Find Median from Data Stream with two heaps (max-heap for low half, min-heap for high half) giving O(log n) addNum and O(1) findMedian. A FAANG streaming classic.
Solve LeetCode 297 Serialize and Deserialize Binary Tree with a BFS queue producing a level-order encoding parsed in O(n). A FAANG hard tree design favorite.
Solve LeetCode 42 Trapping Rain Water in O(n) using a monotonic decreasing stack to fill water layer by layer. The signature FAANG monotonic stack hard problem.
A printable cheatsheet for the entire Stacks and Queues category — seven patterns, ready-to-paste templates, Big-O reference, and a MAANG priority order.
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.
Manacher finds the longest palindromic substring in O(n) by exploiting palindrome symmetry to skip redundant character comparisons. The same mirror trick that powers the Z algorithm, applied to the palindrome radius array.
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.
A suffix array sorts all suffixes of a string lexicographically. Built in O(n log n) with prefix doubling and paired with the Kasai LCP array, it answers substring search, distinct substring count, and longest repeated substring queries in optimal time.
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.
Word Search II (LC 212) is the canonical FAANG hard combining trie data structures with grid backtracking. Build a trie from the dictionary, DFS each cell, and prune aggressively to convert an exponential brute force into a fast practical algorithm.
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.
Shortest Palindrome (LC 214) is a hard FAANG problem that hides a classic KMP application. Concatenate s with reversed(s) and the failure function reveals the longest palindromic prefix in linear time. Master this trick and you unlock half a dozen related KMP applications.
Counting distinct substrings of a string is the gateway problem to suffix arrays and suffix automata. Three classical solutions — n^2 hash set, suffix array plus LCP, and suffix automaton — span the full toolbox of competitive programming and FAANG hard interviews.
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.
Beyond the basic trie there is a rich landscape of advanced applications — XOR tries for maximum-XOR queries, prefix-and-suffix tries, ternary tries, compressed tries (PATRICIA), and persistent tries. Master these and you have the toolkit for half a dozen FAANG hards.
A curated and battle-tested set of the string problems that show up most often in Meta and Google onsite loops, with the canonical pattern for each. Cover this list and you cover roughly 80 percent of string-heavy FAANG screens.
Aho-Corasick matches all patterns simultaneously in O(n+m+z) where z is the number of matches. It builds failure links on a trie exactly like KMP does on a single pattern. Master multi-pattern search for FAANG string algorithm interviews.
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.
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.
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.
Design an in-memory key-value database with field-level get, set, delete, and sorted scan operations. Uses nested hashmaps and sorted structures—the foundation of Redis hashes and LeetCode contest scoring.
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.
Design a parking system with big, medium, and small spaces. O(1) addCar checks slot availability and decrements the counter—a warm-up problem testing array indexing and capacity management in FAANG phone screens.
LeetCode 104 — Maximum Depth of Binary Tree, asked by Amazon, Google, Meta and Apple as a phone-screen warmup. Solve it in one line of recursive DFS or with iterative BFS level counting in O(n) time.
LeetCode 226 — Invert Binary Tree, the famous Max Howell / Google whiteboard rejection question. Solve recursively in 4 lines or iteratively with BFS in O(n) time.
LeetCode 101 — Symmetric Tree, asked at Amazon, Microsoft and Bloomberg. Compare opposite subtrees with a two-pointer recursive helper to check mirror symmetry in O(n) time.
LeetCode 112 — Path Sum, asked at Amazon, Microsoft, Apple and Meta. Use DFS with a running remainder to detect any root-to-leaf path that sums to a target value in O(n) time.
LeetCode 100 — Same Tree, asked at Amazon, Meta, Google and Apple. Walk both trees simultaneously and return false on the first structural or value mismatch in O(n) time.
LeetCode 110 — Balanced Binary Tree, asked at Amazon, Meta, Google and Microsoft. Use a postorder DFS that returns -1 on imbalance to solve it in O(n) time instead of the naive O(n log n).
LeetCode 617 — Merge Two Binary Trees, asked at Amazon, Apple, Meta and Microsoft. Walk both trees in parallel, sum overlapping nodes, and reuse existing pointers in O(n) time.
LeetCode 938 — Range Sum of BST, asked at Amazon, Facebook (Meta), Google and Apple. Use the BST property to prune entire out-of-range subtrees and run in O(h + k) time.
LeetCode 700 — Search in a BST, asked at Amazon, Microsoft, Apple and Meta. Eliminate half the tree at each step using the BST property and finish in O(h) time, O(1) iterative space.
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 543 Diameter of Binary Tree — top Tree DP problem at Amazon, Meta, Google, Bloomberg. Single DFS that returns height while tracking the longest path through any node.
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 968 Binary Tree Cameras asks for the minimum number of cameras to monitor all nodes. The O(n) greedy solution assigns three states per node in a bottom-up DFS — delay camera placement as high as possible, a pattern tested at Amazon and Google.
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 124 Binary Tree Maximum Path Sum finds the highest-value path in a binary tree where the path can start and end at any node. The O(n) solution uses a post-order DFS that tracks the global max while returning only one branch to the parent — a critical FAANG interview problem at Amazon, Google, and Facebook.
LC 297 Serialize and Deserialize Binary Tree is a top FAANG hard problem asked at Facebook, Amazon, and Google. The DFS preorder approach with null markers gives a compact O(n) codec; BFS level-order is more intuitive. Both are valid interview answers.
LC 1373 Maximum Sum BST in Binary Tree finds the highest sum among all BST subtrees of a binary tree. The O(n) solution uses post-order DFS returning a 4-tuple of (is_bst, min, max, sum) metadata — a hard FAANG problem tested at Amazon and Google.
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.
LeetCode 834 Sum of Distances in Tree is a Google and Meta favorite hard problem solved in O(n) using two-pass DFS with the rerooting technique on an undirected tree.
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 671 (Easy) asked at Amazon and Lyft. Find the second minimum value in a special binary tree where every node equals the min of its children, using DFS with pruning in O(n) time.
LeetCode 606 (Easy) asked at Amazon and Apple. Serialize a binary tree in preorder with parentheses, omitting empty parens only when they do not affect the one-to-one mapping, in O(n) time.
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 993 Cousins in Binary Tree checks if two nodes are at the same depth with different parents. The clean O(n) BFS solution processes one level at a time — a foundational tree problem tested at Amazon and Microsoft.
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 589 N-ary Tree Preorder and LC 590 Postorder Traversal generalize binary tree DFS to trees with any number of children. These easy problems build the foundation for harder n-ary tree problems asked at Amazon and Google.
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.
Master Tries for FAANG interviews: insert, search, prefix operations, Word Search II, autocomplete, XOR binary trie for max XOR, and 5-language implementations with full problem index.
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 212 — find every dictionary word hidden in a board. The optimal solution builds a trie over the words and DFS-traverses the grid once, pruning entire branches the moment the path leaves the trie. A textbook FAANG hard problem.
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 336 — find every pair (i,j) such that words[i] + words[j] is a palindrome. The trie solution stores reversed words and tags palindrome-suffix indices, enabling O((N times K^2)) lookup.
LeetCode 1032 — design a class that returns true whenever the suffix of a streamed character sequence matches any dictionary word. Solved with a reverse trie and a bounded sliding buffer in O(W) per query.
LeetCode 745 — design a structure that returns the highest-indexed word matching a given prefix and suffix. The combined-key trie inserts every (suffix#word) variant, turning a 2D query into a 1D trie walk.
LeetCode 2416 — for each word, sum the scores of all its non-empty prefixes where score = number of words sharing that prefix. The counted trie pattern aggregates O(N times L) work into O(N times L) trie nodes with a count counter.
LeetCode 472 — find every word that can be formed by concatenating two or more shorter words from the same list. Trie accelerates the prefix-membership test inside a Word Break DP, turning O(2^L) brute force into O(N times L^2).
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 2185 — count how many strings in words have pref as a prefix. The simple linear scan is optimal for a single query; the trie shines once you anticipate many queries against the same word list.
LeetCode 1707 — for each query (xi, mi), find max xi XOR nums[j] where nums[j] does not exceed mi. Sort queries by mi, sort nums, insert lazily into a binary trie, answer each query in O(32). The offline-trie pattern unlocks bounded XOR queries.
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).
Complete Tries cheatsheet for FAANG interviews: core operations, 5 patterns, binary trie for XOR, decision guide, complexity table, and problem index covering all 20 trie problems.
LeetCode 125 Valid Palindrome is the most common two pointer warm-up at Meta, Microsoft, and Amazon. Learn the inward-converging pointer technique that runs in O(n) time and O(1) space without building a cleaned copy of the string.
LeetCode 344 Reverse String is the simplest two pointer swap problem and a daily warm-up at Amazon, Apple, and Meta. Solve it in O(n) time and O(1) space using opposite-end pointers without allocating a new array.
LeetCode 977 Squares of a Sorted Array is a classic Google and Bloomberg two pointer question. Squaring negatives flips the sort order, so we merge from the outside in to produce a sorted output in O(n) time without re-sorting.
LeetCode 27 Remove Element introduces the fast and slow pointer pattern used in dozens of in-place array problems. Master the read and write index template here and LC 26, LC 283, and LC 80 become trivial.
LeetCode 26 Remove Duplicates from Sorted Array is the canonical fast and slow pointer deduplication problem. Microsoft, Meta, and Amazon use it to verify that candidates can compare against the previous kept element in O(n) time and O(1) space.
LeetCode 88 Merge Sorted Array is the classic three pointer in-place merge problem at Microsoft, Bloomberg, and Amazon. Walk both arrays from the end into the trailing empty slots to achieve O(m plus n) time with O(1) extra space.
LeetCode 392 Is Subsequence is a Google and Amazon greedy two pointer problem. Walk both strings forward, advance the source pointer only on matches, and answer in O(m plus n) time with O(1) space.
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 1176 Diet Plan Performance is a Google fixed sliding window problem. Maintain a running sum of exactly k consecutive calories to score points or penalties in O(n) time and O(1) space.
LeetCode 1480 Running Sum of 1D Array introduces the prefix sum technique used in dozens of FAANG range query problems. Build the running sum in O(n) time and O(1) extra space and unlock LC 303, LC 560, and LC 974.
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 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 992 Subarrays with K Different Integers is a Google, Amazon, and Meta hard. Solve in O(n) using the atMost(K) minus atMost(K-1) decomposition.
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 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 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 1984 asks for the minimum max-minus-min over any k chosen scores. The optimal k scores are always contiguous in sorted order — sort once then scan windows of size k in O(n log 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.
LeetCode 727 asked at Google and Amazon. A forward scan finds a valid right boundary, then a backward scan tightens the left boundary in O(|s|*|t|) time.
LeetCode 30 asked at Google, Amazon, and Meta. Run a word-aligned sliding window for each of the wlen possible offsets to find every concatenation start in O(n*wlen) time.
Count subarrays where score = sum × length is less than k using a shrinkable sliding window with a running sum. Counting all valid subarrays ending at each right pointer is the key trick that avoids an inner loop.
Find the smallest window in s containing all characters of t using have/need counters and a frequency map. The canonical hard sliding-window problem asked at every top tech company.
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque of indices — the classic hard problem that separates senior engineers from the rest.
Find the shortest subarray whose sum is at least k, even with negative numbers, using a monotone increasing deque on prefix sums — the canonical hard problem where a simple sliding window fails.
Find the longest substring containing at most 2 distinct characters using a variable sliding window backed by a character frequency map — a premium LinkedIn and Google problem with a clean generalization to k distinct.
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.
Check whether an integer array can be split into three contiguous parts with equal sum. LeetCode 1013 in O(n) using a greedy single-pass counter, with full Python and JavaScript code.
Solve LeetCode 42 Trapping Rain Water in O(n) time and O(1) space using the canonical two-pointer technique. Includes intuition, dry run, Python and JavaScript code, and follow-up variants.