Interview

575 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 →
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 →
dsa17 min read

Reverse String — The Two-Pointer Swap Pattern Every Interview Expects

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.

Read →
dsa13 min read

Valid Palindrome — Two Pointer Skip Non-Alphanumeric [Meta Easy]

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.

Read →
dsa19 min read

Longest Common Prefix — The Column Scan That Shows Up at Google

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.

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 →
dsa14 min read

Subarray Sum Equals K — Why Prefix Sum + HashMap Beats Everything [LC 560]

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.

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 →
dsa15 min read

Sort Colors [Medium] — Dutch National Flag Algorithm Explained

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.

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 →
dsa15 min read

Stamping the Sequence [Hard] — Reverse Greedy Simulation

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.

Read →
dsa11 min read

H-Index II — Binary Search on Sorted Citations [LC 275]

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.

Read →
dsa10 min read

Aggressive Cows — Binary Search on Answer (SPOJ / GFG Classic)

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.

Read →
dsa9 min read

Guess Number Higher or Lower — Binary Search with API [LC 374]

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.

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

Alien Dictionary — Google Topological Sort Interview Question

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.

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 →
dsa6 min read

Google — Count Inversions (Modified Merge Sort)

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.

Read →
dsa5 min read

Meta — Subarray Sum Equals K (Prefix Sum + HashMap)

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.

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 →
dsa5 min read

Meta — Binary Tree Right Side View (BFS Level Order)

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.

Read →
dsa6 min read

Google — Word Break II (DP + Backtracking with Memoization)

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.

Read →
dsa5 min read

Meta — Accounts Merge (Union-Find on Emails)

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.

Read →
dsa6 min read

Google — Trapping Rain Water II (3D BFS + Min-Heap)

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.

Read →
dsa5 min read

Meta — Clone Graph (Deep Copy with DFS and HashMap)

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.

Read →
dsa6 min read

BFS and DFS on Graphs and Grids — The Complete Interview Guide

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.

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 →
dsa11 min read

Minimum Effort Path — Dijkstra or Binary Search + BFS

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.

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 →
dsa9 min read

Snakes and Ladders — BFS on Board State

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.

Read →
dsa8 min read

Open the Lock — BFS on State Space

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.

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 →
dsa9 min read

Cheapest Flights Within K Stops — Bellman-Ford with a Twist

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.

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 →
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 →
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 →
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

Design Twitter — K-Way Merge News Feed Interview

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.

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

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 a File System — Trie-Based Path Storage

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.

Read →
dsa6 min read

Time Based Key-Value Store — Binary Search on Timestamps

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.

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 →
dsa7 min read

Design Skiplist — Probabilistic Sorted Structure

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.

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

Find Median from Data Stream — Two-Heap Approach

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.

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

Binary Tree Upside Down — Re-root the Left Spine in O(n)

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.

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 →