Amazon

653 articles

dsa8 min read

Remove Zero Sum Consecutive Nodes — Prefix Sum HashMap Explained

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.

Read →
dsa8 min read

Reverse Linked List II — In-Place Partial Reversal Explained

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.

Read →
dsa8 min read

Merge Nodes Between Zeros — In-Place Pointer Walk Explained

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.

Read →
dsa8 min read

Reverse Nodes in Even Length Groups — Group Counting Linked List

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.

Read →
dsa8 min read

Linked List Components — HashSet Membership Count Explained

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.

Read →
dsa8 min read

Reverse Nodes in k-Group — Recursive and Iterative Deep Dive

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.

Read →
dsa9 min read

Merge K Sorted Lists — Min-Heap and Divide & Conquer Explained

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.

Read →
dsa8 min read

Sort List Bottom-Up — O(1) Space Merge Sort on Linked Lists

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.

Read →
dsa8 min read

Convert Sorted List to BST — O(n) In-Order Construction Explained

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.

Read →
dsa8 min read

LRU Cache — Doubly Linked List + HashMap from Scratch

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.

Read →
dsa8 min read

Design Browser History — Doubly Linked List Implementation Explained

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.

Read →
dsa8 min read

Kruskal Minimum Spanning Tree — Greedy Edge Selection with Union-Find

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.

Read →
dsa9 min read

A* Search — Heuristic Shortest Path for Grids and Maps [LC 1091, Google, Tesla]

Master A* search: a heuristic-guided best-first search that finds optimal shortest paths far faster than Dijkstra by combining actual distance g(n) with an admissible estimate h(n). The interview pattern behind LeetCode 1091 Shortest Path in Binary Matrix and the algorithm powering Google Maps, game AI, and robotics navigation.

Read →
dsa12 min read

Contains Duplicate (LeetCode 217) — Hash Set in O(n)

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.

Read →
dsa4 min read

Plus One — Carry Propagation in Arrays

LeetCode 66 — increment a large integer represented as a digit array, propagating the carry. The deceptively simple FAANG warmup that catches careless coders.

Read →
dsa23 min read

Intersection of Two Arrays (LC 349 + LC 350) — HashSet, HashMap, and Scalability Follow-ups [Amazon / Google]

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.

Read →
dsa13 min read

Pascal's Triangle — From Combinatorics to DP Mastery [Easy]

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.

Read →
dsa12 min read

Valid Anagram — Frequency Array, HashMap & Sort [LeetCode 242]

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).

Read →
dsa18 min read

Count Primes — Sieve of Eratosthenes O(n log log n) [Amazon Easy]

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.

Read →
dsa18 min read

Majority Element — Boyer-Moore Voting Algorithm Explained Deeply [LeetCode 169]

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.

Read →
dsa19 min read

Kth Largest Element in a Stream — Min-Heap Design [Amazon Easy]

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.

Read →
dsa18 min read

Running Sum of 1D Array (LC 1480) — Prefix Sum Foundation [Amazon Easy]

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.

Read →
dsa15 min read

Container With Most Water — Greedy Two-Pointer Proof [Google, Amazon, Meta]

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.

Read →
dsa12 min read

Merge Intervals — The Definitive Guide (LeetCode 56) [Google, Meta, Amazon, Microsoft]

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.

Read →
dsa13 min read

Group Anagrams — Hashmap Key Design Mastery [Amazon, Google, Meta]

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.

Read →
dsa19 min read

Maximum Product Subarray — Why Kadane's Fails and How to Fix It [Google, Amazon, Microsoft]

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.

Read →
dsa14 min read

Combination Sum [Medium] — Backtracking with Pruning (LC 39)

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.

Read →
dsa5 min read

4Sum — LC 18 Two Loops Plus Two Pointers

LeetCode 18 generalizes 3Sum to four numbers with target sum. Sort, fix two indices, and run two pointers — O(n^3) time and clean duplicate handling.

Read →
dsa6 min read

Gas Station — Greedy One-Pass Circuit Feasibility [LC 134]

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.

Read →
dsa6 min read

Daily Temperatures — Monotonic Stack Next Greater Element [LC 739]

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.

Read →
dsa6 min read

Partition Labels — Greedy Last-Occurrence Interval Merging [LC 763]

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.

Read →
dsa5 min read

Task Scheduler — Greedy Formula and Max-Heap Simulation [LC 621]

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.

Read →
dsa5 min read

Minimum Arrows to Burst Balloons — Greedy Interval Scheduling [LC 452]

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.

Read →
dsa6 min read

Maximum Swap — Greedy Last-Occurrence Digit Tracking [LC 670]

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.

Read →
dsa5 min read

Find Peak Element — Binary Search on Slope O(log n) [LC 162]

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.

Read →
dsa5 min read

Missing Number — Gauss Formula and XOR Trick [LC 268]

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.

Read →
dsa6 min read

Majority Element II — Extended Boyer-Moore Voting [LC 229]

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.

Read →
dsa6 min read

Wiggle Sort II — O(n) Virtual Index Rearrangement [LC 324]

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.

Read →
dsa5 min read

Summary Ranges — Linear Scan Two-Pointer [LC 228]

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.

Read →
dsa5 min read

Candy — Two-Pass Greedy Rating Satisfaction [LC 135]

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.

Read →
dsa5 min read

Minimum Moves to Equal Array Elements II — Why the Median Wins [LC 462]

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.

Read →
dsa5 min read

Array Nesting — Cycle Detection in Functional Graphs [LC 565]

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.

Read →
dsa6 min read

Advantage Shuffle — Greedy Sun Tzu Strategy [LC 870]

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.

Read →
dsa6 min read

Subsets II — Backtracking with Duplicate Skip [LC 90]

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.

Read →
dsa5 min read

Rotate String — The Concatenation Trick [LC 796]

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.

Read →
dsa6 min read

Trapping Rain Water — Two-Pointer O(n) O(1) [LC 42]

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.

Read →
dsa6 min read

Sliding Window Maximum — Monotonic Deque O(n) [LC 239]

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.

Read →
dsa6 min read

First Missing Positive — Cyclic Sort Index Marking [LC 41]

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].

Read →
dsa6 min read

Largest Rectangle in Histogram — Monotonic Stack O(n) [LC 84]

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.

Read →
dsa16 min read

Minimum Window Substring [Hard] — The Canonical Sliding Window Problem

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.

Read →
dsa15 min read

Count of Smaller Numbers After Self [Hard] — Merge Sort

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.

Read →
dsa14 min read

Maximal Rectangle [Hard] — Histogram Stack per Row

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.

Read →
dsa17 min read

Reverse Pairs [Hard] — The Modified Merge Sort That Counts Before It Merges

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.

Read →
dsa18 min read

Minimum Number of Refueling Stops [Hard] — Greedy Max-Heap + DP

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.

Read →
dsa18 min read

Max Points on a Line [Hard] — Slope Hashing with GCD [Google / Amazon]

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.

Read →
dsa19 min read

Longest Valid Parentheses [Hard] — Stack, DP, and Two-Pass Counters

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.

Read →
dsa17 min read

Minimum Domino Rotations For Equal Row [Medium] — Candidate Reduction + Greedy

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.

Read →
dsa7 min read

Maximum Events Attended — Greedy and Min-Heap [LC 1353, Google]

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).

Read →
dsa6 min read

Minimum XOR Sum of Two Arrays — Bitmask DP with XOR Pairing

LeetCode 1879 Minimum XOR Sum of Two Arrays — pair every element of nums1 with a unique element of nums2 to minimize total XOR. Bitmask DP turns assignment into a 2^n state space. Step-by-step bit manipulation walkthrough for FAANG interviews.

Read →
dsa6 min read

Amazon — Number of Islands II (Dynamic Union-Find)

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.

Read →
dsa5 min read

Amazon — Task Scheduler (Greedy + Frequency Heap)

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.

Read →
dsa5 min read

Amazon — Merge K Sorted Lists (Min-Heap)

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.

Read →
dsa5 min read

Amazon — Top K Frequent Elements (Bucket Sort or Heap)

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.

Read →
dsa10 min read

Climbing Stairs — The Gateway Problem to 1D Dynamic Programming

LC 70 Climbing Stairs is the canonical introduction to 1D dynamic programming. The recurrence dp[n] = dp[n-1] + dp[n-2] is pure Fibonacci, and mastering why it works — recursion to memoization to tabulation — unlocks the entire family of staircase DP problems asked at Google, Amazon, and Meta.

Read →
dsa10 min read

Min Cost Climbing Stairs — Adding a Cost Function to Fibonacci DP

LC 746 Min Cost Climbing Stairs extends the Climbing Stairs Fibonacci DP with per-step costs. The recurrence dp[i] = cost[i] + min(dp[i-1], dp[i-2]) computes the minimum total cost to leave each step. Asked at Amazon and Google as a direct test of whether you can adapt a known recurrence pattern under new constraints.

Read →
dsa10 min read

House Robber — The Skip-One DP Pattern Every FAANG Interview Tests

LC 198 House Robber asks you to maximize stolen money without robbing adjacent houses. The recurrence dp[i] = max(dp[i-1], dp[i-2] + nums[i]) is the canonical skip-one DP pattern asked at Amazon, Google, and Microsoft. Master the derivation, the three-phase DP evolution, and the O(1) space solution.

Read →
dsa10 min read

House Robber II — Handling the Circular Constraint with Two Linear Passes

LC 213 House Robber II extends House Robber to a circular arrangement where the first and last houses are adjacent. The elegant solution runs the linear House Robber DP twice — once excluding the first house, once excluding the last — and returns the maximum. A top FAANG interview problem that tests systematic problem decomposition.

Read →
dsa11 min read

Delete and Earn — Disguised House Robber on a Value Array

LC 740 Delete and Earn looks like a game problem but reduces to House Robber DP after a preprocessing step. Choosing value v earns v * count(v) points and forces deletion of v-1 and v+1, exactly the skip-adjacent constraint. Asked at Amazon and Meta to test whether candidates see through surface-level descriptions to the underlying DP pattern.

Read →
dsa9 min read

Maximum Subarray — Kadane's Algorithm and the DP Behind It

LC 53 Maximum Subarray is the foundational problem behind Kadane's Algorithm — a deceptively simple O(n) DP that asks: at each position, should I extend the current subarray or start fresh? Asked at Amazon, Google, and Microsoft and the basis for Maximum Product Subarray and other contiguous-subarray problems.

Read →
dsa11 min read

Maximum Product Subarray — Tracking Both Min and Max for Sign Flips

LC 152 Maximum Product Subarray extends Kadane's Algorithm by tracking both the running maximum and minimum products simultaneously. A negative number flips today's minimum into tomorrow's maximum. This dual-tracking insight is tested at Amazon, Google, and LinkedIn as a harder follow-up to Maximum Subarray.

Read →
dsa11 min read

Coin Change — Unbounded Knapsack DP for Minimum Coins

LC 322 Coin Change finds the minimum number of coins to make a target amount using unlimited coin supply. The recurrence dp[i] = min(dp[i - coin] + 1) over all coins is the canonical unbounded knapsack minimization problem, asked at Amazon, Google, and Microsoft as a core DP interview question.

Read →
dsa11 min read

Coin Change II — Counting Combinations with Unbounded Knapsack DP

LC 518 Coin Change II counts the number of combinations (not permutations) of coins that sum to a target amount. The key insight is the loop order: coins outer, amounts inner. This unbounded knapsack counting pattern is tested at Amazon and Google to distinguish candidates who understand loop-order reasoning from those who memorize templates.

Read →
dsa11 min read

Perfect Squares — Coin Change DP with Square Numbers as Coins

LC 279 Perfect Squares finds the minimum number of perfect square integers that sum to n. It is isomorphic to Coin Change (LC 322) where the "coins" are all perfect squares up to n. The DP recurrence dp[i] = min(dp[i - j*j] + 1) runs in O(n * sqrt(n)) time and is asked at Google and Amazon.

Read →
dsa10 min read

Jump Game — DP Reachability and the Greedy Insight

LC 55 Jump Game asks if you can reach the last index given maximum jump lengths. The DP approach is O(n^2) but the greedy insight — tracking the farthest reachable index — reduces it to O(n) O(1). Asked at Amazon and Google as a test of recognizing when greedy is provably optimal over DP.

Read →
dsa11 min read

Jump Game II — Minimum Jumps with the Greedy Window Technique

LC 45 Jump Game II finds the minimum number of jumps to reach the last index. The DP solution is O(n^2), but the greedy window technique — extending the current reachable window whenever a boundary is crossed — achieves O(n) O(1). Asked at Amazon and Google as a harder follow-up to Jump Game.

Read →
dsa11 min read

Decode Ways — Counting Valid Decodings with Conditional Fibonacci DP

LC 91 Decode Ways counts the number of ways to decode a digit string as letters A-Z. The recurrence combines one-digit and two-digit transitions — a conditional Fibonacci DP. Heavily tested at Amazon, Google, and Meta because it combines string parsing, edge case handling, and DP reasoning in a single problem.

Read →
dsa11 min read

Word Break — Reachability DP on String Segmentation

LC 139 Word Break checks if a string can be segmented into dictionary words. The reachability DP dp[i] = true if some dp[j] is true and s[j:i] is in the dictionary. Asked heavily at Amazon, Google, and Microsoft as a test of string DP with set-based lookups.

Read →
dsa11 min read

Longest Increasing Subsequence — From O(n²) DP to O(n log n) Patience Sorting

LC 300 Longest Increasing Subsequence finds the length of the longest strictly increasing subsequence. The O(n²) DP is the expected starting point; the O(n log n) patience sorting binary search optimization is what FAANG interviewers look for. This problem is asked at Amazon, Google, and Microsoft and is the foundation for Russian Doll Envelopes.

Read →
dsa7 min read

Russian Doll Envelopes — 2D LIS with the Tie-Breaker Trick

LeetCode 354 Russian Doll Envelopes is a sneaky 2D Longest Increasing Subsequence problem. Sort by width ascending and height descending so equal widths cannot stack, then run patience-sort LIS on heights for an O(n log n) DP solution beloved by FAANG interviewers.

Read →
dsa6 min read

Palindromic Substrings — Expand Around Center vs 2D DP

LeetCode 647 Palindromic Substrings is the canonical center-expansion problem. We derive the 2D DP recurrence, simplify it to expand-around-center for O(1) memory, and walk through a full DP table dry run with FAANG interview tips on why this beats Manacher in real interviews.

Read →
dsa7 min read

Longest Palindromic Subsequence — Interval DP Done Right

LeetCode 516 Longest Palindromic Subsequence is the cleanest interval DP recurrence in interview prep. We derive the dp[i][j] formulation, fill the table along diagonals, and reduce memory from O(n^2) to O(n) — exactly the depth Amazon and Google look for.

Read →
dsa7 min read

Partition Equal Subset Sum — 0/1 Knapsack on a Boolean Array

LeetCode 416 Partition Equal Subset Sum is the cleanest 0/1 knapsack disguise on the platform. We reduce it to subset-sum-equals-half, derive the boolean DP recurrence, walk through the reverse-iteration trick, and finish with a one-liner bitset version that crushes interviews.

Read →
dsa8 min read

Target Sum — Knapsack Reduction with Sign Assignment

LeetCode 494 Target Sum looks like sign-assignment but reduces to subset-sum count via a beautiful algebra trick. We derive the reduction, build the 1D DP, dry-run a tabulation, and discuss why this O(n * sum) solution beats 2^n brute force at FAANG.

Read →
dsa7 min read

Longest Common Subsequence — The 2D DP Template You Will Reuse Forever

LeetCode 1143 Longest Common Subsequence is the foundational two-string DP every FAANG interviewer expects you to nail. We derive the dp[i][j] recurrence, walk a full table, optimize space from O(m*n) to O(min(m,n)), and trace why this template powers Edit Distance, Shortest Common Supersequence, and diff tooling.

Read →
dsa8 min read

Triangle — Bottom-Up DP on a Variable-Width 2D Structure

LC 120 Triangle asks for the minimum-sum path from apex to base. The bottom-up DP approach eliminates border initialization complexity and achieves O(n) space — a classic 2D DP problem that tests your ability to work on non-rectangular structures.

Read →
dsa9 min read

Longest Common Subsequence — The Essential Sequence DP Problem for FAANG

LC 1143 Longest Common Subsequence is the foundational sequence DP problem at every FAANG company. Master the 2D recurrence, space-optimize to O(n), and learn how to reconstruct the actual LCS — skills that transfer directly to Edit Distance, Shortest Common Supersequence, and Diff algorithms.

Read →
dsa10 min read

Burst Balloons — Interval DP with Reverse Thinking (The Hardest Grid DP Pattern)

LC 312 Burst Balloons is the classic hard-level interval DP problem asked at Google, Amazon, and Meta. The key insight is thinking in reverse — instead of choosing which balloon to burst first, choose which one to burst last in each interval. This transforms an impossible ordering problem into clean O(n^3) DP.

Read →
dsa8 min read

Best Time to Buy and Sell Stock — Single Transaction State Machine DP

LC 121 Best Time to Buy and Sell Stock is the foundational stock DP problem at every FAANG company. While solvable with a one-pass greedy approach, understanding its state machine formulation (hold/not-hold states) unlocks the full stock problem series from LC 122 through LC 714.

Read →
dsa9 min read

Best Time to Buy and Sell Stock II — Unlimited Transactions State Machine

LC 122 Best Time to Buy and Sell Stock II allows unlimited buy-sell transactions (hold at most 1 share at a time). Solvable with a greedy slope-collection approach, but the state machine DP extension reveals how unlimited transactions differ structurally from single-transaction stock problems.

Read →
dsa9 min read

Best Time to Buy and Sell Stock III — At Most 2 Transactions State Machine

LC 123 Best Time to Buy and Sell Stock III limits transactions to at most 2. The state machine tracks 4 explicit states — buy1, sell1, buy2, sell2 — evolving each day through clean transitions. This is the hardest single-interview stock variant and the direct precursor to the k-transactions generalization in LC 188.

Read →
dsa9 min read

Best Time to Buy and Sell Stock IV — At Most k Transactions 2D DP

LC 188 Best Time to Buy and Sell Stock IV generalizes the stock problem to at most k transactions using a 2D DP table where dp[t][i] tracks the maximum profit using t transactions through day i. This is the hardest stock variant in FAANG interviews and requires combining the k-transaction state machine with the unlimited-transaction shortcut for large k.

Read →
dsa9 min read

Best Time to Buy and Sell Stock with Cooldown — 3-State Machine DP

LC 309 Best Time to Buy and Sell Stock with Cooldown adds a 1-day cooldown after selling. The state machine expands to 3 states — holding, sold (cooldown), and resting — and the buy transition reads from 2 days ago instead of 1 day ago. This structural change is the cleanest example of how constraints reshape state machine DP.

Read →
dsa10 min read

Best Time to Buy and Sell Stock with Transaction Fee — State Machine DP with Cost

LC 714 Best Time to Buy and Sell Stock with Transaction Fee extends unlimited transactions by subtracting a fee on each sell. The state machine is identical to Stock II with one modification: the sell transition subtracts the fee. This is the final stock series variant and the cleanest demonstration that state machine DP is a modular framework.

Read →
dsa9 min read

Interleaving String — 2D DP for String Validity Checking

LC 97 Interleaving String asks whether s3 can be formed by interleaving s1 and s2 while preserving character order. The 2D DP table dp[i][j] checks whether s3[:i+j] can be formed from s1[:i] and s2[:j] — a classic Boolean 2D DP problem asked at Google and Amazon.

Read →
dsa9 min read

Wildcard Matching — String DP with `?` and `*` Done Cleanly

LeetCode 44 Wildcard Matching is the classic 2D string DP question Meta and Google ask to test recurrence design under tricky base cases. We derive the dp[i][j] transitions for ? and *, dry-run a full table, and finish with a two-pointer optimization that drops memory to O(1).

Read →
dsa10 min read

Dungeon Game — Reverse 2D DP from Goal to Start

LeetCode 174 Dungeon Game is the textbook example of why DP direction matters. We derive why forward DP fails, build the backward dp[i][j] = max(1, ...) recurrence, dry-run the grid, and finish with a space-optimized 1D solution loved at FAANG.

Read →
dsa7 min read

Ones and Zeroes — 2D 0/1 Knapsack with Two Capacities

LeetCode 474 Ones and Zeroes is the cleanest two-capacity 0/1 knapsack on the platform. We derive the dp[i][j] recurrence, walk a full 2D table, and ship a 1D-collapsed solution that handles the dual-resource constraint while staying interview-friendly.

Read →
dsa8 min read

Strange Printer — Interval DP with Merge-on-Match

LeetCode 664 Strange Printer is the canonical O(n^3) interval DP every senior FAANG interviewer expects you to handle. We derive the dp[i][j] recurrence, walk through the merge-on-match optimization, dry-run a full table, and discuss where Strange Printer sits in the Burst Balloons / MCM family.

Read →
dsa10 min read

Walls and Gates — Multi-Source BFS Every FAANG Grid Interview Tests

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.

Read →
dsa10 min read

Count Sub Islands — The AND Logic DFS Mistake Everyone Makes

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.

Read →
dsa7 min read

Clone Graph — Deep Copy with BFS, DFS and HashMap Bookkeeping

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.

Read →
dsa7 min read

Course Schedule — Cycle Detection via Topological Sort

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.

Read →
dsa7 min read

Graph Valid Tree — Cycle and Connectivity Check

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.

Read →
dsa10 min read

Word Ladder — BFS on an Implicit Graph of Word Transformations

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.

Read →
dsa6 min read

Next Greater Element I — Your First Monotonic Stack Problem

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.

Read →
dsa6 min read

Daily Temperatures — Monotonic Stack With Index Distances

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.

Read →
dsa6 min read

Remove K Digits — Build the Smallest Number with a Monotonic Stack

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.

Read →
dsa6 min read

132 Pattern — Scanning Right-to-Left with a Monotonic Stack

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.

Read →
dsa6 min read

Maximal Rectangle — Applying Histogram Analysis Row by Row

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.

Read →
dsa6 min read

Next Greater Element II — Circular Array Monotonic Stack

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.

Read →
dsa7 min read

Minimum Cost to Connect Sticks — Huffman Greedy with Min-Heap

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.

Read →
dsa6 min read

Partition Labels — Greedy Last-Occurrence Interval Merge

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.

Read →
dsa9 min read

Find Common Characters — Frequency Intersection Across String Arrays

Find Common Characters teaches frequency intersection — the element-wise minimum of character counts across multiple strings. This pattern appears in multi-set intersection problems, resource allocation, and constraint satisfaction at tech company interviews.

Read →
dsa8 min read

Jewels and Stones — HashSet Membership Lookup Done Right

Jewels and Stones is the cleanest demonstration of the "build a lookup set, then query it" pattern. While the problem itself is easy, the skill it teaches — converting a repeated linear search into O(1) lookups — is fundamental to optimizing real-world code.

Read →
dsa8 min read

Group Anagrams — Canonical Keys and the Group-By Pattern

Group Anagrams is a medium-difficulty milestone that teaches the canonical-key grouping pattern — one of the most broadly applicable hash map techniques. Amazon, Google, and Meta use it as a filter for candidates who can design O(n k) grouping algorithms over O(n^2 k) brute-force comparisons.

Read →
dsa9 min read

Top K Frequent Elements — Bucket Sort Beats the Heap

Top K Frequent Elements is a classic interview problem that tests whether you know the O(n) bucket sort approach over the standard O(n log k) heap. Amazon, Google, Meta, and Microsoft all ask this problem because it reveals whether you can identify when domain constraints enable a better algorithm.

Read →
dsa9 min read

Subarray Sum Equals K — Prefix Sums and the Complement Map

Subarray Sum Equals K is the definitive prefix-sum hash map problem. It teaches the pattern of converting a range-sum query into a complement lookup — reducing O(n^2) to O(n). Amazon, Google, and Meta ask this in nearly every data-focused interview loop.

Read →
dsa10 min read

Continuous Subarray Sum — Prefix Modulo and Remainder Collisions

Continuous Subarray Sum applies the modular prefix sum trick — one of the most elegant applications of number theory to hash map design. Google uses this problem to test whether candidates can combine modular arithmetic with hash-map complement lookup.

Read →
dsa9 min read

Longest Consecutive Sequence — HashSet and the Smart Sequence Start

Longest Consecutive Sequence is a deceptively hard problem that Google and Meta use to test whether candidates can achieve O(n) without sorting. The key insight — only start counting from sequence beginnings — turns an O(n^2) brute force into an O(n) HashSet solution.

Read →
dsa9 min read

Insert Delete GetRandom O(1) — The Array+HashMap Design Trick

Insert Delete GetRandom O(1) is a classic design interview problem that Google, Amazon, and Meta use to assess compound data structure thinking. The trick — swapping the target with the last element before deletion — enables O(1) removal from a dynamic array.

Read →
dsa9 min read

Find All Anagrams in a String — Fixed Sliding Window With Frequency Matching

Find All Anagrams in a String combines the frequency-count pattern with a fixed sliding window — a compound technique that Google and Amazon use to filter candidates who understand both string hashing and window management. The "match counter" optimization is the key to an elegant O(n) solution.

Read →
dsa9 min read

Random Pick with Weight — Prefix Sums and Probabilistic Sampling

Random Pick with Weight teaches weighted random sampling — a foundational technique in machine learning, A/B testing, and traffic routing. Google and Meta use this problem to assess whether candidates understand prefix sums and binary search well enough to implement probability distributions from scratch.

Read →
dsa9 min read

Brick Wall — Counting Gap Positions With a Frequency Map

Brick Wall teaches the insight of counting the complement — instead of minimizing bricks crossed, maximize gaps hit. Google uses this problem to test whether candidates can reframe a minimization problem as a maximization problem and solve it in O(n) with a frequency map.

Read →
dsa8 min read

Unique Number of Occurrences — Double Hash Validation in One Pass

Unique Number of Occurrences teaches the double-hash technique: build a frequency map, then check if all frequency values are distinct. This two-layer hashing pattern appears in data validation, duplicate detection, and constraint checking problems at every major company.

Read →
dsa10 min read

Count Wonderful Substrings — Bitmask XOR and Prefix Parity Maps

Count Wonderful Substrings combines bitmask XOR with prefix parity tracking to count substrings where at most one character has an odd frequency. This advanced hashing problem teaches the bit-manipulation pattern that Google and Meta use to filter candidates for senior-level roles.

Read →
dsa6 min read

Make Sum Divisible by P — Prefix Mod With a Hashmap

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.

Read →
dsa8 min read

Design HashMap — Building a Hash Table from Scratch

Implement a HashMap from scratch using an array of buckets with chaining for collision resolution — the foundational data structure interview that every engineer should be able to implement cold.

Read →
dsa6 min read

Count Good Meals — Power-of-Two Complement Counting

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.

Read →
dsa7 min read

4Sum II — Meet in the Middle with a Frequency Map

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.

Read →
dsa7 min read

Palindrome Pairs — HashMap Split Enumeration (Hard)

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.

Read →
dsa8 min read

Meeting Rooms II — Minimum Conference Rooms via End-Time Heap

Find the minimum number of conference rooms required for all meetings by tracking room availability with a min-heap of end times — a classic interval scheduling problem asked at every major tech company and fundamental to resource allocation.

Read →
dsa9 min read

IPO — Greedy Capital Maximization with Two Heaps

Maximize capital after k IPO investments by unlocking affordable projects into a max-profit heap — a sophisticated two-heap greedy problem asked at Google, Amazon, and Facebook that models real-world portfolio optimization.

Read →
dsa5 min read

Super Ugly Number — Multi-Pointer Heap DP Interview

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.

Read →
dsa6 min read

Middle of the Linked List — Fast and Slow Pointer You Must Know Cold

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.

Read →
dsa8 min read

Linked List Cycle — Floyd's Tortoise and Hare Explained Step by Step

LC 141 Linked List Cycle is a classic interview question asked by Amazon, Microsoft, and Google that tests your mastery of the two-pointer fast/slow technique. Learn Floyd's tortoise and hare algorithm with a visual dry run, Python and JavaScript solutions, and key interview tips.

Read →
dsa9 min read

Palindrome Linked List — Split, Reverse, Compare in O(1) Space

LC 234 Palindrome Linked List is a popular interview problem at Facebook, Amazon, and Apple that combines three core techniques: fast/slow pointer midpoint finding, in-place list reversal, and two-pointer comparison. Master the O(1) space solution with Python and JavaScript code and a step-by-step dry run.

Read →
dsa8 min read

Intersection of Two Linked Lists — The Two Pointer Length Equalizer

LC 160 Intersection of Two Linked Lists is a popular O(1) space interview question at Amazon, Facebook, and Microsoft. Learn the elegant two-pointer length-equalizer trick, the mathematical proof behind why it works, visual dry run, and Python/JavaScript solutions.

Read →
dsa8 min read

Remove Linked List Elements — Dummy Head Pattern for Clean Deletion

LC 203 Remove Linked List Elements is a fundamental interview problem asked at Google and Amazon that teaches the dummy head sentinel pattern for handling head deletion cleanly. Learn O(n) solutions in Python and JavaScript with visual dry run, common mistakes, and recursive variant.

Read →
dsa9 min read

Remove Nth Node From End of List — One-Pass Two-Pointer Solution

LC 19 Remove Nth Node From End of List is a classic one-pass interview problem at Amazon, Google, and Facebook that combines the dummy head sentinel with a two-pointer n-gap technique. Learn the optimal O(n) single-pass solution with Python and JavaScript, step-by-step dry run, and common interview traps.

Read →
dsa8 min read

Odd Even Linked List — Two-Chain In-Place Grouping Explained

LC 328 Odd Even Linked List is a medium interview problem at Facebook, Amazon, and LinkedIn that tests your ability to maintain two separate pointer chains simultaneously. Learn the O(1) space two-chain pattern with Python and JavaScript, a visual dry run, and interview tips.

Read →
dsa8 min read

Rotate List — Circular Reconnection With Length Normalization

LC 61 Rotate List is a medium interview problem at Amazon and Microsoft that tests your ability to use circular linked list manipulation and modular arithmetic to rotate by k positions efficiently. Learn the optimal O(n) solution with Python and JavaScript, detailed dry run, and the critical k mod n insight.

Read →
dsa8 min read

Reorder List — Split, Reverse, Merge in One Pass

LC 143 Reorder List is a composite interview problem at Facebook, Amazon, and Google that combines three core patterns: fast/slow midpoint finding, in-place second-half reversal, and interleaved merging. Master the O(1) space solution with Python and JavaScript, step-by-step visual trace, and interview approach.

Read →
dsa9 min read

Add Two Numbers — Carry Simulation on Reversed Linked Lists

LC 2 Add Two Numbers is one of the most iconic interview problems at Amazon, Google, and Microsoft where you simulate grade-school addition on two reversed linked lists digit by digit. Master the carry propagation technique with Python and JavaScript solutions, visual dry run, and common pitfalls.

Read →
dsa9 min read

Add Two Numbers II — Stack-Based Reverse-Order Addition Explained

LC 445 Add Two Numbers II is a medium interview problem at Amazon and Google where numbers are stored most-significant-digit first, requiring stacks or list reversal to process from LSB. Learn the optimal stack-based solution with Python and JavaScript, dry run, and the key difference from LC 2.

Read →
dsa8 min read

Partition List — Two Dummy Head Chains for Stable Partitioning

LC 86 Partition List is a medium interview problem at Bloomberg and Amazon that extends the dummy-head two-chain pattern to partition by value comparison. Learn the stable O(n) solution with Python and JavaScript, visual dry run, and critical edge cases including the tail-cycle trap.

Read →
dsa9 min read

Sort List — Merge Sort on a Linked List Step by Step

LC 148 Sort List is a classic O(n log n) interview problem at Amazon, Google, and Facebook that applies merge sort to a linked list using fast/slow pointer splitting and recursive merging. Learn top-down merge sort with Python and JavaScript, a complete dry run, and the bottom-up O(1) space follow-up.

Read →
dsa8 min read

Remove Duplicates from Sorted List II — Delete All Occurrences with Dummy Head

LC 82 Remove Duplicates from Sorted List II is a medium interview problem at Google, Amazon, and Bloomberg where you remove ALL nodes that appear more than once from a sorted list. Learn the dummy-head predecessor skip pattern with Python and JavaScript, step-by-step dry run, and the critical difference from LC 83.

Read →
dsa8 min read

Copy List with Random Pointer — HashMap Clone and O(1) Space Interleave

LC 138 Copy List with Random Pointer is a medium interview problem at Amazon, Microsoft, and Facebook that requires deep-copying a linked list where each node has a random pointer. Learn the O(n) space hash map approach and the clever O(1) space interleave technique with Python and JavaScript solutions and detailed dry run.

Read →
dsa9 min read

Flatten Multilevel Doubly Linked List — Stack-Based DFS Explained

LC 430 Flatten a Multilevel Doubly Linked List is a medium interview problem at Microsoft and Amazon that uses DFS or an explicit stack to inline child sub-lists into the main list. Learn the iterative stack approach and the recursive approach with Python and JavaScript, step-by-step dry run, and interview tips.

Read →
dsa9 min read

Linked List Cycle II — Floyd's Algorithm to Find Where the Cycle Starts

LC 142 Linked List Cycle II is a medium interview problem at Amazon, Microsoft, and Google where you find the exact node where a cycle begins using Floyd's algorithm and a mathematical proof. Learn the two-phase approach with Python and JavaScript, the math proof, visual dry run, and common interview questions.

Read →
dsa10 min read

Find the Duplicate Number — Floyd's Cycle Detection on an Array

LC 287 Find the Duplicate Number is a brilliant medium interview problem at Amazon, Google, and Facebook where you find a duplicate in an n+1 integer array in O(1) space by treating the array as an implicit linked list and applying Floyd's cycle detection algorithm. Master the connection between arrays and linked lists with Python and JavaScript solutions and detailed proof.

Read →
dsa6 min read

Amazon Leadership Principles — DSA Interview Alignment Guide

Map Amazon's 16 Leadership Principles to coding and behavioral interview behaviors. Includes the LP-to-question mapping, how to weave LP language naturally into technical explanations, the Bar Raiser format, and a per-LP preparation template.

Read →
dsa9 min read

Sudoku Solver — Constraint Propagation Plus Backtracking

LC 37 Sudoku Solver is the most-asked constraint-satisfaction problem in tech interviews. Master row, column, and box bitsets, MRV heuristic ordering, and the cell-by-cell decision tree that solves any 9x9 grid in milliseconds.

Read →
dsa7 min read

Implement Stack Using Queues — Queue Rotation Design Problem

Implement a LIFO stack using only queue operations. Learn both the single-queue rotation trick and the two-queue approach — a classic data-structure design problem that tests your understanding of LIFO vs FIFO at FAANG interviews.

Read →
dsa7 min read

Implement Queue Using Stacks — Amortized O(1) Lazy Transfer

Implement a FIFO queue using two stacks with amortized O(1) push and pop. The two-stack lazy-transfer trick is a FAANG interview staple that demonstrates deep understanding of amortized complexity and LIFO vs FIFO semantics.

Read →
dsa7 min read

Baseball Game — Stack Simulation for Record Scoring

Simulate a baseball scoring game using a stack to handle score records, doubles, sum operations, and cancellations in O(n) time. A clean stack-simulation problem that tests your ability to model stateful operations with LIFO access.

Read →
dsa7 min read

Number of Recent Calls — Sliding Window Queue Design

Count ping requests within the last 3000ms using a FIFO queue that evicts expired timestamps from the front in O(1) amortized time. A clean introduction to the sliding window queue pattern used in rate limiters and real-time counters.

Read →
dsa8 min read

Make the String Great — Stack Adjacent Pair Removal

Remove adjacent pairs of same letters with different cases using a stack that processes each character and cancels bad pairs immediately. A clean application of the stack-based adjacent-pair-removal pattern common in FAANG string interviews.

Read →
dsa7 min read

Daily Temperatures — Monotonic Decreasing Stack Explained

Find how many days until a warmer temperature using a monotonic decreasing stack of unresolved day indices. The canonical monotonic stack problem asked at every FAANG company — master the pattern here and unlock 20+ harder problems.

Read →
dsa7 min read

Next Greater Element I — Monotonic Stack with HashMap

Find the next greater element for each query using a monotonic stack on nums2 and a hash map lookup in O(n+m) time. A classic application of the monotonic stack pattern combined with hash map lookups for efficient query answering.

Read →
dsa8 min read

Next Greater Element II — Circular Array Monotonic Stack

Find the next greater element in a circular array by processing 2n indices with modulo indexing and a monotonic stack. The circular variant of the classic monotonic stack pattern — an elegant trick that extends NGE I to handle wrap-around in O(n) time.

Read →
dsa7 min read

Online Stock Span — Monotonic Stack with Span Accumulation

Calculate the stock price span using a monotonic decreasing stack that stores (price, span) pairs and accumulates spans in O(1) amortized time. A classic streaming design problem that tests span accumulation and the monotonic stack pattern.

Read →
dsa8 min read

Remove K Digits — Monotonic Increasing Stack Greedy

Remove k digits from a number string to form the smallest possible number using a monotonic increasing stack with greedy removal. A key FAANG problem testing greedy thinking, stack manipulation, and edge case handling with leading zeros.

Read →
dsa7 min read

Decode String — Two-Stack for Nested Encodings

Decode a run-length encoded string with nested brackets like 3[a2[bc]] using two stacks for counts and partial strings. A key FAANG problem testing nested structure parsing with stacks — the same pattern used in expression evaluators and compilers.

Read →
dsa7 min read

Evaluate Reverse Polish Notation — Operand Stack Calculator

Evaluate a Reverse Polish Notation expression by pushing operands and applying operators to the top two stack elements in O(n) time. The canonical stack-based expression evaluation problem asked at Amazon, LinkedIn, and Microsoft.

Read →
dsa8 min read

Sliding Window Maximum — Monotonic Deque for O(n) Solution

Find the maximum in every sliding window of size k using a monotonic decreasing deque that maintains candidate indices in O(n) total time. The hardest and most elegant deque problem — mastering this unlocks Shortest Subarray with Sum At Least K and Jump Game VI.

Read →
dsa8 min read

Score of Parentheses — Stack Depth Doubling and O(1) Space

Calculate the score of a balanced parentheses string where () = 1 and (A) = 2*A using a stack and an elegant O(1) space depth-doubling trick. A FAANG medium problem that rewards deep thinking with a beautiful bit-shift optimization.

Read →
dsa7 min read

Task Scheduler — Greedy Cooldown Formula and Priority Queue

Find the minimum CPU intervals to execute all tasks with cooldown n using a greedy formula based on maximum frequency. A key FAANG problem testing greedy reasoning, frequency counting, and optionally heap-based simulation asked at Amazon, Google, and Facebook.

Read →
dsa8 min read

Word Search II — Trie + DFS Backtracking on a Grid

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.

Read →
dsa8 min read

Shortest Palindrome — KMP Failure Function on a Concatenated String

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.

Read →
dsa5 min read

Design Browser History — Stack-Based Navigation

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.

Read →
dsa5 min read

Design a Leaderboard — Score Tracking with Top K

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.

Read →
dsa6 min read

Design Snake Game — Deque-Based State Machine

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.

Read →
dsa5 min read

Design Log Storage System — Timestamp Range Retrieval

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.

Read →
dsa6 min read

Design Phone Directory — Available Number Pool Management

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.

Read →
dsa6 min read

Design In-Memory Database — Multi-Field Filtering

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.

Read →
dsa5 min read

Design Min Stack — O(1) Minimum with Auxiliary Stack

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.

Read →
dsa6 min read

Design Circular Queue — Ring Buffer Implementation

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.

Read →
dsa5 min read

Design URL Shortener (TinyURL) — Hashing and Encoding

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.

Read →
dsa5 min read

Design Parking System — Counter-Based Slot Management

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.

Read →
dsa7 min read

Path Sum III — Prefix Sum HashMap on Binary Trees (LC 437)

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.

Read →
dsa5 min read

Delete Node in a BST — LC 450 Interview Deep Dive

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.

Read →
dsa6 min read

Populate Next Right Pointers in Each Node — LC 116 O(1) Space BFS

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.

Read →
dsa6 min read

All Nodes Distance K in Binary Tree — LC 863 BFS with Parent Map

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.

Read →
dsa6 min read

House Robber III — Tree DP with Pair Return (LC 337)

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.

Read →
dsa6 min read

Binary Tree Cameras — LC 968 Greedy 3-State DFS

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.

Read →
dsa6 min read

Distribute Coins in Binary Tree — LC 979 Post-Order Flow Analysis

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.

Read →
dsa6 min read

Kth Ancestor of a Tree Node — LC 1483 Binary Lifting

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.

Read →
dsa6 min read

Binary Tree Maximum Path Sum — LC 124 Hard DFS Interview Classic

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.

Read →
dsa6 min read

Serialize and Deserialize Binary Tree — LC 297 FAANG Hard

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.

Read →
dsa6 min read

Maximum Sum BST in Binary Tree — LC 1373 Post-Order Metadata

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.

Read →
dsa5 min read

Find Leaves of Binary Tree — LC 366 Height-Based Grouping

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.

Read →
dsa5 min read

Path Sum IV — LeetCode 666 Encoded Tree DFS

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.

Read →
dsa5 min read

Add One Row to Tree — BFS Insertion at Depth in O(n)

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.

Read →
dsa6 min read

Count Nodes in a Complete Binary Tree — LC 222 O(log^2 n) Proof

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.

Read →
dsa6 min read

Construct Quad Tree — LC 427 Divide and Conquer Grid

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.

Read →
dsa7 min read

Word Search II — Trie + Backtracking on a Grid

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.

Read →
dsa6 min read

Replace Words — Trie for Shortest Root Replacement

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.

Read →
dsa7 min read

Maximum XOR of Two Numbers in an Array — Binary Trie

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.

Read →
dsa7 min read

Search Suggestions System — Trie Powered Autocomplete

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.

Read →
dsa7 min read

Prefix and Suffix Search — Combined Key Trie Trick

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.

Read →
dsa6 min read

Sum of Prefix Scores of Strings — Counted Trie Aggregation

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.

Read →
dsa7 min read

Concatenated Words — Trie + Word Break DP

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).

Read →
dsa7 min read

Short Encoding of Words — Reverse Trie Suffix Deduplication

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.

Read →
dsa6 min read

Map Sum Pairs — Trie with Cumulative Sum Propagation

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.

Read →
dsa8 min read

Maximum XOR With an Element From Array — Offline Binary Trie

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.

Read →
dsa7 min read

Find the Length of the Longest Common Prefix — Digit Trie

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.

Read →
dsa6 min read

Count Distinct Substrings — Suffix Trie Node Counting

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).

Read →
dsa5 min read

Tries — Master Recap and Interview Cheatsheet

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.

Read →
dsa5 min read

Grumpy Bookstore Owner — Fixed Sliding Window Bonus (LC 1052)

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.

Read →