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.
Master system design interviews in 2026 using the RADIO framework across seven canonical problems — URL shortener, Instagram, WhatsApp, Netflix, rate limiter, and key-value store. Aimed at engineers preparing for FAANG and senior-level rounds.
Master data structures and algorithms for tech interviews in 2026 by learning 14 core patterns that solve 90% of LeetCode problems, with a structured 90-day study plan. Built for engineers targeting FAANG and top-tier coding rounds.
Write a software engineer resume that survives ATS filters and earns interviews at FAANG companies in 2026, using the XYZ bullet formula, proven section structure, and before/after examples for junior and senior engineers.
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.
Negotiate your software engineer salary effectively in 2026 with total compensation breakdowns, word-for-word negotiation scripts, equity negotiation tactics, and market rate data for US and India. For engineers at all levels who want to stop leaving money on the table.
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.
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.
A complete pattern guide to arrays and strings problems from LeetCode used by Google, Meta, Amazon, Apple, and Microsoft. Covers prefix sum, Kadane, two pointers, sliding window, hash maps, and Dutch flag in Python and JavaScript.
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 344 is the canonical two-pointer problem — and it shows up at Meta, Microsoft, and Amazon as both a standalone question and as the foundation for palindrome checks, anagram detection, and rotate-array problems. Learn the in-place swap pattern deeply, trace through every edge case, and master the follow-ups that separate passing candidates from standout ones.
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.
Master LeetCode 125 — Valid Palindrome with the O(1)-space two-pointer technique. Learn why every FAANG loop starts here, visualize the pointer walk on a classic example, avoid the four most common pitfalls, and unlock the palindrome follow-up chain: LC 680, LC 5, and LC 647.
LeetCode 14 appears deceptively simple — until the interviewer asks you to do it without sorting, then with binary search, then on a stream of words. Master all three approaches (vertical scan, horizontal fold, binary search on length), understand exactly why each one works, and walk into your Google screen ready for every escalation.
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.
LeetCode 448 is the definitive interview test for index-as-a-hash-key thinking. Learn the O(n) time, O(1) space negation trick that eliminates the need for any extra data structure — and every follow-up question a FAANG interviewer will throw at you after you solve it.
Given a binary array and an integer k, find the longest run of 1s you can create by flipping at most k zeros. Master the variable sliding window pattern that solves this in O(n) time and O(1) space — and learn the follow-up questions Google and Meta actually ask after you get it right.
Master LeetCode 414 — Third Maximum Number. Learn the subtle INT_MIN sentinel trap, two clean approaches (sorted set + three-variable O(1)), and real FAANG follow-up questions interviewers ask after you solve it.
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.
Most shuffle implementations are silently biased. Learn why naive random fails, how Fisher-Yates guarantees every permutation is equally probable, and what FAANG interviewers really want to hear when they ask this question.
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 560 is one of the most-asked FAANG problems because it teaches the prefix sum + hashmap pattern — a technique that handles negative numbers, generalizes to a dozen follow-ups, and cannot be replaced by sliding window. Learn the insight, the dry run, the common mistakes, and the O(n) solution in Python and JavaScript.
LeetCode 33 is a rite of passage in FAANG interviews. Learn the one invariant that makes O(log n) possible on a rotated array, trace through a dry run, avoid the 4 most common bugs, and master the full family of follow-up problems (LC 81, LC 153, LC 154).
LeetCode 55 is a classic FAANG greedy problem that tests whether you can compress O(n²) DP thinking into a single O(n) pass. Learn the "max reachable index" insight, why greedy beats DP here, a full visual dry run, common traps, and every follow-up question interviewers ask next.
LeetCode 189 looks trivial — until the interviewer asks for O(1) space. Learn why three distinct approaches exist, the mathematical reason triple-reverse works, every common pitfall (wrong k, direction confusion, off-by-one), a full visual dry run, and how this trick unlocks Rotate String, Rotate Image, and beyond.
LeetCode 153 is one of the cleanest illustrations of binary search on a non-standard search space. Learn the rotation insight that unlocks O(log n), trace through a full visual dry run, avoid the three mistakes that most often break this one, and walk away ready for the duplicates variant (LC 154) and the full search-in-rotated problem (LC 33).
LeetCode 347 asks for k most frequent elements with a constraint: beat O(n log n). Learn why naive sort fails, how a min-heap of size k achieves O(n log k), and the elegant bucket sort insight that delivers true O(n) — with full visual dry run, common mistakes, and Python/JavaScript solutions for all three approaches.
LeetCode 152 looks like a simple extension of Maximum Sum Subarray — until you hit negative numbers. A negative times a negative is positive, which means the current minimum can instantly become the new maximum. Learn why tracking BOTH cur_max and cur_min is the essential insight, how zeros act as hard resets, the four bugs every candidate makes, and step-by-step dry runs on key examples. Python and JavaScript solutions from O(n²) brute force to the elegant O(n) DP approach.
Learn how to rotate an n×n matrix 90° clockwise in-place using the elegant transpose-then-reverse trick. Understand the math behind it, see the 4-cell direct rotation alternative, dry-run through a worked example, avoid the four most common mistakes, and get clean Python + JavaScript solutions.
Next Permutation is not just an array problem — it is a test of systematic algorithmic thinking under pressure. Learn why you scan from the right, why you swap with the smallest larger element, and why the suffix is reversed rather than sorted. Includes full visual dry runs, the 4 most common bugs, and Python + JavaScript solutions.
LeetCode 287 eliminates every naive approach through three hard constraints: no array modification, O(1) space, O(n) time. The solution — treating the array as an implicit linked list and running Floyd's tortoise-and-hare cycle detection — is one of the most elegant algorithm mappings in all of DSA. Full proof, visual dry run, Python and JavaScript solutions.
Master Dijkstra's Dutch National Flag algorithm to sort 0s, 1s, and 2s in a single pass with O(1) space. Understand the three-pointer invariants, the critical bug most candidates make, and how this pattern unlocks a family of partition problems.
Master LeetCode 57 with the three-phase sweep algorithm. Learn exactly how to insert and merge intervals in O(n) time — a pattern that appears repeatedly at Google, Amazon, and Meta.
Master LeetCode 435 with the greedy earliest-end-time strategy. Learn why sorting by end time is the key insight, walk through a visual dry run, and ace every FAANG follow-up on interval scheduling.
Master LeetCode 39 — Combination Sum by understanding the backtracking decision tree, why unlimited reuse is handled by staying at the same index, and how sorting enables early pruning. Includes Python and JavaScript solutions with line-by-line comments, a full visual dry run, common mistakes, and follow-up questions on LC 40, LC 216, and LC 377.
LC 46 — Permutations is the canonical backtracking problem every interviewer uses to test recursive thinking. Learn two clean approaches — the visited-array method and the in-place swap method — with a full decision-tree dry run for [1,2,3], the three most common interview mistakes, and real follow-up questions on LC 47 and LC 60.
LC 78 is the gateway to every combination and permutation problem in FAANG interviews. Master all three approaches — backtracking, bitmask enumeration, and iterative cascading — with deep visual dry runs, real interview follow-ups, and line-by-line Python and JavaScript solutions.
Master LeetCode 209 from first principles: understand why a variable-size shrinkable sliding window is the insight that cracks this problem in O(n), trace through every pointer movement on a real example, learn the three common interview mistakes, and be ready for the O(n log n) binary search follow-up that Amazon and Microsoft love to ask.
LeetCode 442 is a FAANG favorite that tests whether you can squeeze O(1) space out of a hash-set problem. We use index negation to mark visited values in place.
LeetCode 394 is a classic FAANG string problem testing nested-bracket parsing. We use two stacks to decode any depth of k[encoded] expressions in linear time.
LeetCode 40 is a FAANG backtracking favorite that tests duplicate handling. Sort the candidates and skip same-level repeats to enumerate unique sum combinations.
LeetCode 134 — asked at Amazon, Google, and Microsoft. Find the unique valid starting station in a circular gas route using a two-insight greedy: global feasibility check plus a local reset that eliminates O(n) candidates at once, giving O(n) time and O(1) space.
LeetCode 739 — asked at Amazon, Google, and Meta. Find the number of days until a warmer temperature using a monotonic decreasing stack. Store indices not temperatures, pop when current day is warmer, and solve six related problems with the same O(n) pattern.
LeetCode 128 — asked at Google, Amazon, and Meta. Find the longest consecutive integer sequence in O(n) using a HashSet. Only start counting from numbers where num-1 is absent — each element is visited at most twice total, making an apparent O(n²) nested loop amortized O(n).
LeetCode 763 — asked at Amazon, Google, and Meta. Partition a string into the maximum number of pieces so each letter appears in exactly one piece. Map each character to its last occurrence, then greedily extend the current partition boundary — O(n) time, O(1) space.
LeetCode 621 — asked at Google, Meta, and Amazon. Schedule tasks with a cooldown n to minimize total time. Use the greedy formula max(len(tasks), (max_count - 1) * (n + 1) + count_of_max) or simulate with a max-heap and queue — both O(tasks) time.
LeetCode 452 — asked at Amazon, Google, and Microsoft. Find the minimum number of arrows to burst all balloons by sorting by end coordinate and greedily shooting through overlapping intervals. O(n log n) time, O(1) space — the classic greedy interval scheduling pattern.
LeetCode 670 — asked at Meta and Amazon. Given a non-negative integer, swap at most one pair of digits to get the maximum value. Track the last occurrence of each digit, then greedily find the leftmost position where a larger digit appears later — O(n) time, O(1) space.
LeetCode 162 — asked at Google, Meta, and Amazon. Find any peak element in O(log n) using binary search on slope direction. If nums[mid] < nums[mid+1], a peak must exist in the right half — guaranteed by virtual negative infinity at both boundaries.
LeetCode 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 LeetCode 689 with a full visual dry run, left/right DP insight, Python and JavaScript solutions, and real interview follow-ups on generalizing to k windows.
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.
Master LC 936 Stamping the Sequence with reverse greedy simulation. Learn the core insight that working backwards transforms an impossible forward search into a tractable greedy problem. Python and JavaScript solutions with full commentary.
Find the longest substring that appears at least twice using binary search on the answer length combined with a Rabin-Karp rolling hash. A FAANG-level Hard problem solved in O(n log n) average time with full pseudocode in Python and JavaScript.
Design FreqStack to push values and pop the most frequent element with recency tie-breaking in O(1). Master the freq-map plus group-of-stacks pattern with a full visual dry run, common pitfalls, and Python and JavaScript solutions.
Master every binary search pattern used at FAANG interviews — classic exact match, left and right boundary, rotated array, binary search on answer, parity, and 2D matrix — with copy-pasteable templates and a 23-problem index.
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.
Compute the integer square root (floor) of x using right-boundary binary search. Find the largest k where k*k <= x, understand the upper-mid trick, and learn why this is the mirror image of the left-boundary template.
LC 34 asks for the start and end index of a target in a sorted array. Solve it in O(log n) by running two separate binary searches — one for the left boundary and one for the right boundary. A top FAANG pattern.
Search a rotated sorted array in O(log n) by identifying which half is always sorted at each step and checking whether the target falls inside it. A top FAANG interview problem.
Find the minimum element in a rotated sorted array in O(log n) by comparing mid to hi to decide which side of the rotation pivot you are on. A classic FAANG pivot-search pattern.
LC 74 asks you to search a globally sorted 2D matrix in O(log(m*n)). The key insight: treat the entire matrix as a 1D sorted array using flat-index mapping (row = mid // n, col = mid % n) and run standard binary search.
Find the minimum eating speed that lets Koko finish all bananas in h hours by binary searching over the answer space and using a feasibility check. The canonical binary-search-on-answer problem.
LC 1011 asks for the minimum ship capacity to deliver all packages within D days. Binary search on the capacity range [max(weights), sum(weights)] and greedily simulate loading to check feasibility. A classic binary-search-on-answer pattern.
Find any peak element in O(log n) by always moving toward the uphill neighbor. Understand the slope-chasing invariant that guarantees a peak exists in every search window.
Find the k closest elements to x in a sorted array in O(log(n-k) + k) by binary searching for the optimal left boundary of the result window rather than searching for x itself.
Find the one non-duplicate element in O(log n) time by observing how pair indices shift after the singleton — a parity-based binary search that requires no XOR or extra space.
Find the length of the longest strictly increasing subsequence in O(n log n) using patience sorting — a binary search on a maintained tails array that is simpler and faster than classic DP.
LC 410 asks you to split an array into k non-empty subarrays to minimize the largest subarray sum. Binary search on the answer range [max(nums), sum(nums)] and greedily count splits to check feasibility. O(n log(sum - max)) total time.
Search a rotated sorted array that may contain duplicates in O(log n) average time by handling the ambiguous duplicate case with a safe lo++ shrink. Deep FAANG interview breakdown with visual dry runs and all edge cases.
Find the minimum number of days to make m bouquets of k adjacent flowers by binary searching on the day value and checking feasibility greedily. Full FAANG-level breakdown with visual dry run and all edge cases.
Find the h-index from a sorted citations array in O(log n) time using left-boundary binary search. Full FAANG interview breakdown with visual dry run, all edge cases, and intuition behind the search condition.
Count spell-potion pairs where spell * potion >= success by sorting potions and binary searching for each spell threshold. Full FAANG-level breakdown with visual dry run, all edge cases, and ceiling division intuition.
LC 378 asks for the kth smallest element in an n x n matrix sorted row-by-row and column-by-column. Binary search on the value range [min, max] and count elements <= mid using a staircase walk. O(n log(max-min)) total.
LC 1552 asks you to place m balls in sorted basket positions to maximize the minimum distance between any two balls. Binary search on the minimum distance and greedily place balls to check feasibility. A classic maximize-minimum binary search pattern.
LC 154 extends the rotated minimum search to arrays with duplicates. When nums[mid] == nums[hi], neither half can be ruled out — safely shrink by decrementing hi. Worst case degrades to O(n). A hard variant that tests invariant reasoning.
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.
LC 1060 asks for the kth missing number in a sorted array. Binary search on the missing-count function: at index i, exactly nums[i] - nums[0] - i numbers are missing. Find the first index where this count >= k, then recover the answer. O(log n).
Search a row-and-column sorted 2D matrix in O(m+n) using the staircase technique from the top-right corner. Understand why binary search alone fails and why the corner is the unique elimination point.
Place C cows in N stalls to maximise the minimum distance between any two cows. Learn the canonical binary-search-on-answer pattern — the template behind Magnetic Force Between Two Balls, Split Array, and dozens of other hard problems.
Count subarrays whose sum lies in [lower, upper] using merge sort on prefix sums in O(n log n). Understand the divide-and-conquer counting trick that makes an O(n^2) brute-force drop to linearithmic time.
Find the secret number between 1 and n using the guess() API in O(log n) calls. Master the exact binary search template used in all interactive/guessing problems and understand why the API return values map directly to the lo/hi update rules.
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 367 asks if a positive integer is a perfect square without using built-in sqrt. Binary search on [1, num] for a value k where k*k == num. Also learn the elegant O(sqrt(n)) odd-number identity. A classic easy binary search problem at Google and Apple.
LC 744 finds the smallest letter in a circular sorted array that is strictly greater than the target. Left-boundary binary search with modular wrap-around handles the circular case elegantly. A clean variant that extends the standard left-boundary template.
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 786 asks for the kth smallest fraction a[i]/a[j] from a sorted prime array. Binary search on the fraction value [0.0, 1.0] and count fractions below mid using two pointers. O(n log(1/epsilon)) total. A hard binary search on value problem.
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 981 implements a key-value store where each key can have values at different timestamps. set() in O(1), get(key, timestamp) in O(log n) using right-boundary binary search on the sorted timestamp list. A classic design + binary search interview problem.
LC 1353 asks for the maximum number of events you can attend given start and end days. Greedy approach: each day, attend the event with the earliest end date using a min-heap. Sort events by start day and use a pointer to add available events. O(n log n).
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.
The complete Binary Search interview cheatsheet covering all 7 patterns, the universal template, Binary Search on Answer playbook, complexity reference, and MAANG priority order. Bookmark this for the day before any FAANG interview.
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.
Complete bit manipulation cheatsheet for FAANG interviews: all critical tricks, bitmask DP patterns, XOR properties, complexity table, and full problem index across 18 problems.
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.
LeetCode 240 Search a 2D Matrix II is a Google favourite that tests staircase elimination. We solve it in O(m + n) by walking from the top-right corner — beating the naive O(m * n) scan and the O(m * log n) per-row binary search.
LeetCode 269 Alien Dictionary is a Google premium classic that derives a character ordering from a sorted word list. We model it as a directed graph and run Kahn topological sort BFS to detect cycles and emit a valid order in O(C) time.
LeetCode 239 Sliding Window Maximum is a Google classic that returns the max of every length-k window. The optimal answer maintains a monotonic decreasing deque of indices for amortised O(n) time.
LeetCode 76 Minimum Window Substring is a Google staple solved with a two-pointer sliding window plus a need-and-have frequency counter. Optimal solution runs in O(n + m) time and O(m) space.
Implement a lazy iterator over a nested integer list using a stack. Meta frequently tests this to evaluate iterator design, lazy evaluation, and stack-based tree traversal.
Encode a binary tree to a string and reconstruct it. Meta ranks this as their number-one tree interview question, testing BFS level-order traversal and string parsing under pressure.
Implement a read() function using a read4() primitive that reads exactly 4 characters at a time. Meta uses this to test buffer management, pointer arithmetic, and state machine design for file I/O.
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.
Find the longest substring containing at most k distinct characters using a sliding window with a frequency map. Google asks this to test sliding window mastery and hashmap-based window shrinking.
Generate all valid combinations of n pairs of parentheses using backtracking with open and close counters. Meta asks this to test recursive thinking, pruning, and combinatorial generation under time pressure.
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.
Count the number of inversions in an array using a modified merge sort that counts cross-inversions during the merge step. Google tests this to evaluate divide-and-conquer mastery and algorithmic optimization under O(N log N) constraints.
Count contiguous subarrays whose elements sum to k using prefix sums and a frequency hashmap. Meta asks this to test prefix sum mastery and O(N) optimization over brute-force O(N^2) solutions.
Find the k most frequent elements in an array using a min-heap or bucket sort. Amazon asks this to test frequency counting, heap manipulation, and O(N) bucket sort optimization for bounded frequency ranges.
Return the rightmost visible node at each level of a binary tree using BFS level order traversal. Meta uses this to test BFS confidence, level tracking, and tree traversal variants applied to visual rendering problems.
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.
Return all possible sentence segmentations of a string using valid dictionary words via DP memoization and backtracking. Google tests this to evaluate recursive search pruning and memoization applied to NLP-style segmentation.
Merge accounts that share any email address using Union-Find on email nodes. Meta uses this to test graph connectivity thinking and identity resolution — directly applicable to Facebook account deduplication systems.
Compute trapped rain water in a 3D height map using a min-heap BFS that processes cells from the boundary inward. Google asks this as a hard follow-up to 1D trapping rain water, testing 3D spatial reasoning and heap-driven BFS.
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.
Deep copy an undirected graph using DFS or BFS with a HashMap to track already-cloned nodes. Meta tests this to evaluate graph traversal, deep copy semantics, and cycle detection in recursive graph structures.
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.
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.
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.
Master BFS and DFS on graphs and grids with the seven core patterns that show up in 90 percent of FAANG graph interviews. Learn flood fill, multi-source BFS, shortest path on unweighted graphs, and connected components with Python and JavaScript code.
Solve LeetCode 200 Number of Islands with DFS flood fill in O(m*n) time. The most asked grid traversal problem at Amazon, Google, and Meta — covers DFS, BFS, and Union-Find approaches with Python and JavaScript.
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.
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.
Count islands with unique shapes by encoding each DFS traversal path as a string and storing shapes in a set. A classic interview problem testing DFS + hashing.
Count land islands fully surrounded by water (no border touch). Flood-fill border land first to eliminate open islands, then count remaining closed components.
Find the minimum number of 0s to flip to connect two islands. Use DFS to color the first island, then multi-source BFS to expand outward until hitting the second island.
Find the path from top-left to bottom-right that minimizes the maximum absolute difference between consecutive cells. Dijkstra treats effort as edge weight; binary search + BFS checks feasibility for each candidate effort.
Master Clone Graph (LeetCode 133): a FAANG favorite that tests BFS, DFS, graph traversal, hash map state, and cycle handling. We trace it step by step, derive the optimal pattern, and fortify you against the classic mistakes interviewers love to spot.
LeetCode 547 Number of Provinces is the canonical connected-components question. Learn the DFS, BFS, and Union Find solutions, master the adjacency-matrix walk, and rehearse the FAANG interview script.
Classic graph reachability problem disguised as a puzzle. Treat each room as a node and each key as a directed edge, then run BFS or DFS from room 0 to check if every room can be visited.
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.
BFS from the entrance to find the nearest border empty cell that is not the entrance. Classic BFS shortest-path on a grid with a carefully defined exit condition.
Minimum dice rolls to reach square n² from square 1. The hard part is converting square numbers to board coordinates in Boustrophedon (snake) order. BFS on the state space of squares gives the optimal answer.
Find the minimum number of turns to go from "0000" to the target combination on a 4-wheel lock, avoiding deadend states. Classic BFS on a finite state space — the lock combination is the node, each wheel turn is an edge.
An array problem masquerading as a jump puzzle. Each index is a node with two outgoing edges (i + arr[i] and i - arr[i]), and the question reduces to a textbook BFS or DFS reachability check.
A directed graph cycle-detection problem solved by Kahn topological sort (BFS) or three-color DFS. The bedrock template behind dependency resolution at Maven, npm, Bazel, Make, and every modern build system.
The natural sequel to LC 207. Instead of asking whether you can finish all courses, this problem asks for a valid course ordering. Kahn algorithm gives the answer almost for free.
A graph is a valid tree iff it is connected and has no cycles, equivalently exactly n - 1 edges and one connected component. Solve with BFS, DFS, or Union Find — Union Find is shortest.
Count connected components by Union Find (decrement count on each successful union) or by BFS / DFS (increment count for each unvisited node). Both run in near-linear time.
Find the edge that closes a cycle when added to an n-node, n-edge graph. The first edge whose two endpoints share a Union Find root is the answer — a five-line solve.
LC 743 Network Delay Time asks for the time a signal takes to reach all n nodes from source k. Single-source shortest path via Dijkstra gives every distance in O(E log V); the answer is the maximum among them.
LC 787 Cheapest Flights Within K Stops asks for the cheapest route from src to dst using at most k intermediate stops. Bellman-Ford with exactly k+1 relaxation rounds handles the stop constraint cleanly without Dijkstra getting confused by the layered state.
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.
A complete FAANG-ready guide to greedy algorithms and monotonic stacks: interval scheduling, exchange arguments, next greater element, histogram problems, and trapping rain water patterns.
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 316 Remove Duplicate Letters combines greedy with a monotonic stack to find the lexicographically smallest subsequence containing every character exactly once. The "pop only if the character appears again later" check using last_occurrence is the key insight.
LC 402 Remove K Digits uses a monotonic increasing stack to greedily eliminate digits that make the number larger. The three-part answer construction — pop k times, trim trailing removals, strip leading zeros — is the exact pattern that trips candidates in interviews.
LC 907 Sum of Subarray Minimums introduces the contribution technique: instead of finding the minimum of each subarray, count how many subarrays each element is the minimum of. Two monotonic stacks compute left and right boundaries in O(n).
LC 962 Maximum Width Ramp finds the largest j-i with nums[i] <= nums[j]. The two-pass approach — build a decreasing stack of candidates, then scan right-to-left to match — is a pattern that appears in several max-width-satisfying-condition problems.
LC 456 132 Pattern requires finding i < j < k where nums[i] < nums[k] < nums[j]. The right-to-left decreasing stack maintains the "2" candidate — the key insight that makes an O(n) solution possible where left-to-right fails.
LC 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.
Complete Greedy and Monotonic Stack cheatsheet covering all patterns, templates, complexity table, decision tree, and problem index. The single page to revise before any FAANG interview.
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.
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.
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.
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.
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 355 Design Twitter is a Meta and Twitter system design interview classic. Build post, follow, unfollow, and getNewsFeed using a per-user tweet list and a K-way merge max-heap.
LeetCode 1201 Ugly Number III is a Google and Amazon medium that breaks the heap pattern. Solve it with binary search plus inclusion-exclusion in O(log(n*max)) — far faster than naive heap enumeration.
LeetCode 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).
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.
Complete master recap of the Heaps and Priority Queues section. Covers 7 core heap patterns, complexity tables, and a full FAANG-style problem index for systematic interview preparation.
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.
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.
LC 1979 Find Greatest Common Divisor of Array is the entry point to GCD problems at Google and Meta. Master the Euclidean algorithm in O(log n), compute LCM without overflow, and apply extended GCD for modular inverse.
Modular arithmetic powers nearly every competitive programming problem and is foundational at Google, Stripe, and any system that handles big numbers. Master binary exponentiation in O(log n), modular inverse via Fermat little theorem, and the modulo identities that prevent overflow on the hot path.
Prime factorization is the workhorse of number-theoretic interview problems at Amazon and Microsoft. Master trial division in O(sqrt n), the smallest-prime-factor sieve for batched factorization in O(log n) per query, and the divisor-counting tricks they unlock.
Eulers totient function phi(n) counts integers up to n coprime to n and underpins RSA, modular inverse for composite moduli, and Eulers theorem. Master the prime-factorization formula, the sieve variant in O(N log log N), and the multiplicative-function tricks that make phi indispensable for competitive programming.
Computing C(n, r) modulo a prime appears in nearly every counting problem at Google and Meta. Master Pascal triangle for small n, precomputed factorials with modular inverse for n up to 10^6, and Lucas theorem for n up to 10^18.
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.
Matrix exponentiation collapses any linear recurrence into O(log n) by raising a transition matrix to the n-th power. Master Fibonacci, k-th order recurrences, and DP optimization tricks that let you answer queries with n up to 10^18 in milliseconds.
Bit manipulation is the cheat code of competitive programming and tier-1 interviews. Master the XOR identities, n & (n-1) tricks, subset enumeration over a bitmask, and bitmask DP techniques that turn O(2^n) brute force into elegant constant-factor wins.
Recognising classical number sequences — Fibonacci, Catalan, triangular, Pascal-derived — is the difference between a 30-minute brute force and a 5-minute closed form. Master the recurrences, generating functions, and combinatorial interpretations every interviewer expects you to know.
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.
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.
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.
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.
Complete Segment Tree and Fenwick Tree cheatsheet for FAANG interviews: BIT template, segment tree template, lazy propagation, 2D BIT, decision guide, and full problem index.
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.
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.
Master 21 LeetCode design problems frequently asked at Google, Meta, Amazon, and Apple — LRU/LFU caches, Twitter feed, hit counter, autocomplete and more, all built from first principles.
LeetCode 146 LRU Cache is the most-asked design problem at FAANG. Build O(1) get and put using a doubly linked list and hashmap with full Python and JavaScript code.
Implement a file system that creates paths and associates integer values with them. Uses a HashMap mapping full path strings to values with O(L) operations—a pattern used in virtual file systems and etcd.
Design a hit counter that counts requests in the last 5 minutes using a circular buffer with 300 buckets. This O(1) fixed-memory design is used in rate limiters and analytics pipelines at AWS and Cloudflare.
Design a time-stamped key-value store that retrieves the latest value at or before a given time using binary search on sorted timestamp lists. Google and Amazon test this to evaluate versioned data design and binary search mastery.
Design a search autocomplete that returns top 3 historical queries for the current prefix, ranked by frequency. Combines a Trie with per-node frequency maps, a pattern used in Google Search and Bing.
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.
Implement a skip list from scratch with O(log n) expected search, add, and erase. The probabilistic sorted linked list used in Redis sorted sets and LevelDB—a must-know data structure for senior FAANG interviews.
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.
Maintain a running median from a data stream using two heaps: a max-heap for the lower half and a min-heap for the upper half. A classic FAANG hard problem used in analytics engines and streaming data pipelines.
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.
Complete recap of all 20 system design DSA problems: pattern classification, time complexities, key data structures, and the decision framework for choosing the right design approach in FAANG interviews.
The complete binary tree interview playbook for 2026 — 9 patterns, ready-to-paste DFS/BFS templates, and a curated index of 75 LeetCode tree problems asked at Google, Meta, Amazon, Apple, and Microsoft.
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.
Count nodes in a complete binary tree in O(log^2 n) by comparing left and right spine heights to detect perfect subtrees and skip counting them entirely.
Find the minimum seconds to collect all apples in an undirected tree using post-order DFS — include a subtree path only when it contains at least one apple.
Find the longest zigzag path in a binary tree by DFS — track the current direction and length, reset when the direction breaks, and update a global maximum.
LeetCode 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 272 (Hard) frequently asked at Google and Meta. Use BST inorder traversal to get a sorted list, then a two-pointer shrink window selects the k closest values to a target in O(n) time.
LeetCode 156 (Medium) classically asked at Google and LinkedIn. Re-root a binary tree by flipping each left child into the new parent and the original parent into the new right child, in O(n) time and O(1) extra space iteratively.
LeetCode 510 (Medium) frequently asked at Microsoft and Facebook. Find the inorder successor of a BST node when each node has a parent pointer, in O(h) time and O(1) extra space without access to the root.
LeetCode 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.
Complete recap of the Trees DSA section covering 9 reusable patterns, complexity tables, and a problem index mapped to LeetCode favorites at FAANG interviews.
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.
Design a Trie with insert, search, and startsWith operations. This is the foundational data structure behind autocomplete, spell checkers, and IP routing tables.
LeetCode 211 walkthrough — implement WordDictionary supporting add and search where the search query can contain a "." wildcard. The optimal solution combines a trie with DFS branching at every wildcard, a textbook FAANG interview pattern.
LeetCode 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.
Map of every important trie variant you need for FAANG interviews — binary trie for XOR, reverse trie for suffix matching, counted trie for prefix scoring, offline trie for bounded queries, and the design patterns that compose them.
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.
Master the two pointer and sliding window patterns that drive 15-20 percent of FAANG array and string interviews at Meta, Google, Amazon, Apple, and Netflix. This guide indexes 60 problems and the techniques behind every variant.
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 424 — a classic FAANG sliding window problem (Google, Microsoft, Amazon). Master the max-frequency invariant that powers the optimal O(n) solution.
LeetCode 567 — detect if any permutation of s1 appears as a substring of s2 using a fixed-size sliding window. Frequently asked at Google, Amazon, and Microsoft.
LeetCode 904 — find the longest contiguous subarray with at most two distinct values. A reskinned classic that appears in Google, Amazon, and Microsoft interviews.
LeetCode 1695 — find the maximum sum of a subarray with all unique values using a HashSet sliding window. A favorite at Google and Amazon for testing window invariants.
LC 881 asks for the minimum boats to rescue everyone given a weight limit and at-most-2-per-boat rule. Sort then greedily pair the heaviest with the lightest using two pointers — O(n log n) time, O(1) space.
LC 15 asks for all unique triplets summing to zero. Sort the array, fix each element as the anchor, and use two pointers to scan for pairs — with careful three-level deduplication. A must-know FAANG pattern.
LeetCode 167 Two Sum II is asked at Amazon, Microsoft, Google, and Bloomberg. Solve it in O(n) time and O(1) space with the inward two-pointer technique on a sorted array.
LeetCode 713 Subarray Product Less Than K is asked at Google, Amazon, and Stripe. Count contiguous subarrays in O(n) using a multiplicative sliding window.
LeetCode 1423 Maximum Points You Can Obtain from Cards is asked at Google, Amazon, and Meta. Convert pick-from-ends into a fixed-size minimum-window problem in O(n).
LeetCode 1248 Count Number of Nice Subarrays is asked at Google and Amazon. Convert "exactly k odds" into atMost(k) minus atMost(k-1) for an O(n) solution.
LeetCode 930 Binary Subarrays With Sum is asked at Google, Amazon, and Meta. Count subarrays with exact sum in O(n) using atMost(goal) minus atMost(goal-1).
LeetCode 1838 Frequency of the Most Frequent Element is asked at Google and Amazon. Sort, then slide a window where total cost to lift everything to the rightmost value is at most k.
LeetCode 1658 Minimum Operations to Reduce X to Zero is asked at Amazon, Google, and Meta. Reframe to longest subarray summing to total minus x for an O(n) solution.
LeetCode 845 Longest Mountain in Array is asked at Google, Amazon, and Bloomberg. Find the longest strictly increasing-then-decreasing subarray in O(n) time, O(1) space.
LeetCode 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 1888 asks for the minimum flips to make a binary string alternating after any rotations. Double the string and slide a fixed window of size n against both target patterns — the canonical circular sliding window trick.
LC 1456 asks for the maximum vowels in any substring of length k. A canonical fixed-size sliding window — add the new right character, subtract the departing left character, track the running max. O(n) time, O(1) space.
LC 1151 asks for minimum swaps to group all 1s in a circular binary array. Count total 1s to set the window size, then maximize 1s inside any window position using modulo indexing. O(n) time, O(1) space.
LC 2516 asks for the minimum minutes to collect at least k of each character from a string's ends. Flip it: find the longest middle window you can skip so the outside has enough of each character. O(n) time, O(1) space.
LC 1052 maximizes satisfied customers by finding the optimal k-minute grumpiness suppression window. Decompose into a fixed base plus a variable bonus — then find the max-bonus window with a standard fixed-size sliding window. O(n) time, O(1) space.
LC 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.
LC 2260 asks for the shortest consecutive sequence of cards containing a matching pair. Track the last-seen index of each card value — update the minimum window each time a duplicate is encountered. O(n) time, O(n) space.
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.
Complete master cheatsheet of every two-pointer and sliding window pattern used in coding interviews. Includes template code, problem index, decision tree, and MAANG priority list.