Leetcode

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

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

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

Remove Duplicates from Sorted List — Single Pass Pointer Walk Explained

LC 83 Remove Duplicates from Sorted List is a foundational linked list interview problem asked at Bloomberg and Microsoft. Learn the single-pass pointer walk solution with Python and JavaScript, a visual dry run, common traps, and how to extend it to the harder variant (LC 82).

Read →
dsa8 min read

Delete Node in a Linked List — The Copy-and-Skip Trick Explained

LC 237 Delete Node in a Linked List is a clever trick problem asked at Adobe and Microsoft that tests whether you understand linked list node deletion when you only have access to the node itself and not the head. Learn the copy-and-skip approach with Python and JavaScript solutions.

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

Swap Nodes in Pairs — In-Place Pointer Rewiring Without Swapping Values

LC 24 Swap Nodes in Pairs is a medium linked list interview problem at Microsoft and Bloomberg that tests precise multi-step pointer manipulation. Learn the iterative dummy-head approach and the recursive solution with Python and JavaScript, detailed visual dry run, and interview tips.

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