Medium

348 articles

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 →
dsa13 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 →
dsa18 min read

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

LeetCode 152 looks like a simple extension of Maximum Sum Subarray — until you hit negative numbers. A negative times a negative is positive, which means the current minimum can instantly become the new maximum. Learn why tracking BOTH cur_max and cur_min is the essential insight, how zeros act as hard resets, the four bugs every candidate makes, and step-by-step dry runs on key examples. Python and JavaScript solutions from O(n²) brute force to the elegant O(n) DP approach.

Read →
dsa14 min read

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

Daily Temperatures [Medium] — Monotonic Stack Masterclass [Amazon, Google]

LeetCode 739 — Find the number of days until a warmer temperature for each day using a monotonic decreasing stack. The key insight: store indices, not temperatures, in the stack. When a warmer day arrives, it is the "next greater element" for every cooler day still waiting on the stack — a fundamental pattern that appears in at least six other LeetCode problems.

Read →
dsa1 min read

Single Number III — XOR Partition

Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.

Read →
dsa1 min read

Sum of Two Integers — Bit Addition

Add two integers without + or - operators. Simulate: sum = a XOR b (no carry), carry = (a AND b) << 1. Repeat until carry = 0.

Read →
dsa1 min read

Subsets — Bitmask Enumeration

Generate all subsets of an array. Each subset corresponds to a bitmask of n bits where bit i = 1 means element i is included.

Read →
dsa1 min read

House Robber — Skip Adjacent DP

Maximize amount robbed without robbing adjacent houses. Classic skip-one DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).

Read →
dsa1 min read

House Robber II — Circular Array DP

Houses arranged in a circle: first and last are adjacent. Run linear House Robber twice: once excluding last house, once excluding first.

Read →
dsa2 min read

Coin Change — Unbounded Knapsack DP

Find minimum coins to make amount. Unbounded knapsack DP: dp[amount] = min(dp[amount-coin]+1) over all coins. Bottom-up from 0 to amount.

Read →
dsa1 min read

Jump Game — Greedy Reachability

Check if you can reach the last index. Greedy: track furthest reachable index. If current position > reach, stuck.

Read →
dsa1 min read

Decode Ways — Counting DP

Count ways to decode a digit string as letters (A=1,...,Z=26). DP: single digit + valid double digit transitions.

Read →
dsa1 min read

Word Break — Reachability DP

Check if string can be segmented into dictionary words. DP: dp[i]=true if some dp[j] is true and s[j:i] is in wordDict.

Read →
dsa1 min read

Target Sum — DP Count Ways

Assign + or - to each number to reach target sum. DP counts ways to reach each sum. Reduces to 0/1 knapsack subset sum count.

Read →
dsa1 min read

Unique Paths — Grid Path Count DP

Count paths from top-left to bottom-right moving only right or down. dp[i][j] = dp[i-1][j] + dp[i][j-1]. Math formula O(1) also works.

Read →
dsa1 min read

Minimum Path Sum — Grid DP

Find minimum cost path from top-left to bottom-right moving right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).

Read →
dsa1 min read

Triangle — Bottom-Up 1D DP

Minimum path sum from top to bottom of triangle. Bottom-up DP: dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).

Read →
dsa1 min read

Interleaving String — 2D DP

Check if s3 is formed by interleaving s1 and s2. dp[i][j] = can s3[:i+j] be formed from s1[:i] and s2[:j].

Read →
dsa1 min read

Ones and Zeroes — 2D 0/1 Knapsack

Find maximum strings using at most m zeros and n ones. 2D 0/1 knapsack: dp[i][j] = max strings using i zeros and j ones.

Read →
dsa1 min read

Gas Station — Greedy Circular

Find starting gas station index to complete circular route. If total gas >= total cost, a solution exists. Track running balance; reset start when negative.

Read →
dsa1 min read

Remove K Digits — Greedy Monotonic Stack

Remove k digits to get smallest number. Monotonic increasing stack: pop larger digits when they appear before a smaller one. Remove remaining from end.

Read →
dsa3 min read

Find K Closest Elements

Find K closest elements to x in a sorted array using binary search to find the optimal left boundary.

Read →
dsa2 min read

Top K Frequent Elements

Return the K most frequent elements using a frequency map plus min-heap, or bucket sort for O(n) solution.

Read →
dsa1 min read

Sort Characters By Frequency

Sort characters in a string by decreasing frequency using a frequency counter and max-heap or bucket sort.

Read →
dsa2 min read

K Closest Points to Origin

Find K points closest to the origin using a max-heap of size K or quickselect for O(n) average.

Read →
dsa2 min read

Task Scheduler

Find minimum CPU intervals to schedule tasks with cooldown using a greedy max-heap simulation.

Read →
dsa3 min read

Reorganize String

Rearrange a string so no two adjacent characters are the same using a greedy max-heap approach.

Read →
dsa2 min read

Find K Pairs with Smallest Sums

Find K pairs (u, v) with smallest sums from two sorted arrays using a min-heap initialized with first row candidates.

Read →
dsa2 min read

Ugly Number II

Find the nth ugly number (only prime factors 2, 3, 5) using three pointers for the 2x, 3x, 5x merge streams.

Read →
dsa2 min read

Meeting Rooms II

Find minimum conference rooms required by tracking room end times with a min-heap of ongoing meeting endings.

Read →
dsa2 min read

Car Pooling

Check if a car can pick up all passengers by processing start/end events with a sorted timeline or heap.

Read →
dsa2 min read

Furthest Building You Can Reach

Greedily use ladders for the largest climbs and bricks for smaller gaps, managed with a min-heap of ladder sizes.

Read →
dsa3 min read

Process Tasks Using Servers

Assign tasks to available servers using two heaps: one for free servers and one for busy servers sorted by free time.

Read →
dsa2 min read

Super Ugly Number

Find the nth super ugly number with prime factors only from a given list using K-pointer dynamic programming.

Read →
dsa3 min read

Design Twitter

Design a simplified Twitter with follow/unfollow and a news feed showing the 10 most recent tweets from followed users.

Read →
dsa2 min read

Ugly Number III

Find the nth number divisible by a, b, or c using binary search with inclusion-exclusion counting formula.

Read →
dsa2 min read

Longest Happy String

Build the longest string with at most 2 consecutive identical characters by always using the most frequent available character.

Read →
dsa1 min read

Find Right Interval

For each interval find the interval with the smallest start point >= the end point using sorted starts and binary search.

Read →
dsa1 min read

Kth Largest Sum in a Binary Tree

Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.

Read →
dsa2 min read

Total Cost to Hire K Workers

Minimize total hiring cost by always choosing the cheapest candidate from the first or last p candidates using two min-heaps.

Read →
dsa1 min read

Seat Reservation Manager

Design a seat manager that reserves the lowest numbered available seat and unreserves seats using a min-heap.

Read →
dsa1 min read

Stock Price Fluctuation

Track stock prices with corrections by maintaining a sorted multiset and a timestamp-to-price map.

Read →
dsa1 min read

Reduce Array Size to At Least Half

Find the minimum number of elements to remove to reduce array size by half by greedily removing most frequent elements.

Read →
dsa3 min read

Delete Node in a BST

Find and delete a node from a BST while maintaining BST properties using in-order successor.

Read →
dsa2 min read

Sum Root to Leaf Numbers

Compute the total sum of all root-to-leaf numbers formed by concatenating digits along each path.

Read →
dsa3 min read

Maximum Width of Binary Tree

Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.

Read →
dsa2 min read

Convert BST to Greater Tree

Replace each node value with the sum of all values greater than or equal to it using reverse in-order traversal.

Read →
dsa2 min read

Find Duplicate Subtrees

Find all duplicate subtrees by serializing each subtree and using a hash map to detect duplicates.

Read →
dsa2 min read

Unique Binary Search Trees II

Generate all structurally unique BSTs with values 1 to n using divide and conquer with memoization.

Read →
dsa2 min read

Trim a Binary Search Tree

Trim a BST so all values lie within [low, high] by recursively pruning out-of-range subtrees.

Read →
dsa2 min read

Recover Binary Search Tree

Find and swap the two misplaced nodes in a BST using in-order traversal to detect the violations.

Read →
dsa2 min read

House Robber III

Maximize robbery from a tree-structured neighborhood where adjacent (parent-child) nodes cannot both be robbed.

Read →
dsa2 min read

Distribute Coins in Binary Tree

Count minimum moves to distribute coins evenly by tracking excess/deficit coins flowing through each edge.

Read →
dsa3 min read

Kth Ancestor of a Tree Node

Find the Kth ancestor of any tree node in O(log k) per query using binary lifting (sparse table DP).

Read →
dsa2 min read

Find Leaves of Binary Tree

Collect leaves by height (distance from leaf) repeatedly, returning all leaves at each height level.

Read →
dsa2 min read

Count Complete Tree Nodes

Count nodes in a complete binary tree in O(log^2 n) by comparing left and right heights to identify full subtrees.

Read →
dsa2 min read

Unique Binary Search Trees

Count the number of structurally unique BSTs with n nodes using Catalan numbers and DP.

Read →
dsa1 min read

Binary Tree Pruning

Remove all subtrees that do not contain a 1 by recursively returning null for subtrees with only zeros.

Read →
dsa2 min read

Binary Search Tree Iterator

Implement an in-order BST iterator with O(h) space using a stack to simulate recursive in-order traversal.

Read →
dsa2 min read

Binary Tree Upside Down

Transform a binary tree so every right child becomes a sibling and left child becomes parent using iterative rotation.

Read →
dsa2 min read

Add One Row to Tree

Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.

Read →
dsa1 min read

Deepest Leaves Sum

Sum all nodes at the deepest level of a binary tree using BFS to process level by level.

Read →
dsa2 min read

Construct Quad Tree

Build a quad tree from a 2D grid by recursively checking if a region is uniform and splitting into four quadrants.

Read →