Hard

161 articles

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

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

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

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

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

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

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

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