Neetcode 150

Alfonso's intuition-first study bank — 150 problems

18 categories 150 solutions Generated 2026-03-19

Arrays & Hashing (9)

Contains Duplicate #217
Hash Set / Bloom Filter detection
Think of this like a bouncer at a club checking the guest list. As each person arrives, you check if their name is already in your log. If it is - dup...
Encode and Decode Strings #271
Length-delimited serialization. Self-describing format where each item encodes its own size, making the data immune to whatever characters it contains.
Think of this like packaging boxes for shipping. If you just wrote each box's contents and then stacked them, you couldn't tell where one box ends and...
Group Anagrams #49
Keyed grouping / Canonical form hashing
Think of each string as a recipe - if two recipes have the exact same ingredients in the exact same quantities, they're the same 'type' of recipe rega...
Longest Consecutive Sequence #128
Set-based sequence detection with the 'start point' optimization. This leverages a hash set to achieve O(1) membership checking.
Imagine you're looking at a bunch of numbered blocks scattered on a table. Some of them happen to form continuous chains - like 4,5,6,7 sitting next t...
Product of Array Except Self #238
Prefix/Suffix Product (Two-Pass Accumulation)
Think of this like a river flowing through checkpoints. At each position i, you need to know the total 'flow' (product) from both upstream (all elemen...
Top K Frequent Elements #347
Bucket Sort by Frequency / Counting Sort Adaptation
Think of this like finding the most popular items in a store inventory. You have a list of what sold, and you want to know which k products were purch...
Two Sum #1
Hash table complement lookup - for each element, compute what you need (target - current) and check if it's already been seen.
Imagine you're balancing a scale. You have a target weight (the sum you need), and as you place each number on the scale, you're instantly checking if...
Valid Anagram #242
Frequency Count / Hash Map
Think of each string as a 'chemical composition' - you're checking if two substances have the exact same atoms in the exact same quantities, just arra...
Valid Sudoku #36
Multi-dimensional Uniqueness Validation with Hash Sets
Think of Sudoku validation as checking three independent 'conservation laws' simultaneously. Each digit 1-9 is like a unique 'energy packet' that can ...

Two Pointers (5)

3Sum #15
Two Pointers with Sorting (specifically the 'sort + two pointers' pattern for 2-sum)
Think of this like finding three weights that balance perfectly on a see-saw - they need to sum to zero. The key insight: once you sort the array, it ...
Container With Most Water #11
Two Pointers (opposite ends, moving toward center)
Imagine two vertical cliffs forming a valley. The water it can hold is limited by BOTH the distance between them (width) AND the shorter cliff (height...
Trapping Rain Water #42
Two Pointers (greedy)
Imagine this as a valley system where water accumulates. The key insight: at any position, the water level is determined by the SHORTER of the two 'wa...
Two Sum II #167
Two Pointers (opposite direction)
Think of this like balancing a scale. You have a sorted list of weights from lightest to heaviest, and you want two weights that exactly equal a targe...
Valid Palindrome #125
Two Pointers (opposite ends moving inward)
Think of a palindrome as a system in equilibrium — like a perfectly balanced scale. The first character must equal the last, the second must equal the...

Sliding Window (6)

Best Time to Buy and Sell Stock #121
Single Pass Scan / Implicit Sliding Window
Think of this like a hiker walking through a mountain range who can only look forward in time. They want to find the lowest valley BEFORE a peak — the...
Longest Repeating Character Replacement #424
Sliding Window (Longest Substring with Condition)
Think of this like a 'squeeze' or purification problem. You have a window of characters and a budget of k 'impurities' (characters that don't match th...
Longest Substring Without Repeating Characters #3
Sliding Window with HashMap - Two Pointer Technique
Imagine you're maintaining a 'clean zone' on a conveyor belt - you expand your window to the right, adding new characters. But the moment you spot a r...
Minimum Window Substring #76
Sliding Window (Expand-Contract with Two Pointers)
Think of this like a filtration or scanning problem. You have a 'target signature' (string t) — like a bouncer checking if you have all required docum...
Permutation in String #567
Sliding Window with Frequency Counter and Match Tracking
Imagine you're looking for a chord (any permutation of s1's notes) inside a longer song (s2). The order of notes within the chord doesn't matter - you...
Sliding Window Maximum #239
Monotonic Deque (Monotonic Decreasing Queue)
Think of this like a VIP section at a club. As people line up (the sliding window), you need to know who the tallest person is in the current VIP grou...

Stack (7)

Car Fleet #853
Sort + Stack (or single counter)
Imagine cars as particles flowing toward an energy minimum (the target). A faster car behind a slower car is like a particle that can get 'captured' b...
Daily Temperatures #739
Monotonic Decreasing Stack (Next Greater Element pattern)
Think of this like a thermodynamic system where each day is 'seeking equilibrium' with a warmer future day. The key insight: when a warmer day arrives...
Evaluate Reverse Polish Notation #150
Stack - Expression Evaluation
Think of RPN like cooking from a recipe card. You read instructions in order: when you see an ingredient (number), you put it on the counter. When you...
Generate Parentheses #22
Backtracking / Depth-First Search on a state tree
Think of building parentheses like maintaining a 'height' or 'balance' in a system. Each '(' is like stepping up, each ')' is like stepping down. You ...
Largest Rectangle in Histogram #84
MONOTONIC STACK (increasing)
Picture the histogram as a city skyline. You're looking for the largest rectangle that fits under any part of this skyline. Here's the key insight: fo...
Min Stack #155
Stack with augmented state - storing auxiliary information at each stack frame
Imagine you're managing a stack of weighted crates and need to answer 'what's the lightest crate in the entire stack?' instantly at any moment. When y...
Valid Parentheses #20
Stack (Last-In-First-Out)
Think of this like a seesaw or balance scale. When you see an opening bracket '(', you're placing weight on one side. The matching closing bracket ')'...

Binary Search (7)

Binary Search #704
Binary Search on a sorted array
Imagine you're looking for a specific book in a perfectly alphabetized library with millions of books. You wouldn't check every book from A to Z — tha...
Find Minimum in Rotated Sorted Array #153
Modified Binary Search for Boundary Detection
Think of this like finding the seam where two sorted stacks of papers were taped together. Originally you had one sorted stack, then someone rotated i...
Koko Eating Bananas #875
Binary Search on Answer (Monotonic Predicate)
Think of Koko's eating speed like water flow through a pipe. You need a minimum flow rate to push all the bananas through within the time limit. If th...
Median of Two Sorted Arrays #4
Binary Search on Partition (searching for a cut point in a sorted structure)
Think of two sorted decks of cards. You want to find the median of all cards combined. Instead of merging (which is slow), imagine making a single cut...
Search a 2D Matrix #74
Binary Search on Virtual Sorted Array
Imagine you have a perfectly sorted list of numbers, but someone drew grid lines over it — splitting it into rows where each row continues from where ...
Search in Rotated Sorted Array #33
Modified Binary Search with Sorted-Half Identification
Think of a sorted bookshelf where someone picked up a stack of books and reinserted them at a different position - that's the rotation. The key insigh...
Time Based Key-Value Store #981
Binary Search on Sorted Arrays
Think of this like a version control system or document editing history. When you 'get' a value at timestamp 7, you're asking 'what was the value of t...

Linked List (11)

Add Two Numbers #2
Simultaneous traversal with persistent state (carry). This is essentially a 'two-pointer merge' where both pointers advance together while maintaining a running state.
Think of adding two numbers on paper, column by column from right to left. The linked lists are already in the perfect order for this - the first node...
Copy List with Random Pointer #138
Hash Table + Two-Pass Traversal (or Interweaving)
Think of this like cloning a city map where: - `next` pointers are sequential streets (linear, predictable) - `random` pointers are secret tunnels tha...
Find the Duplicate Number #287
Floyd's Tortoise and Hare (Cycle Detection in a Linked List)
Imagine the array as a linked list where each value points to the next index to visit. Since we have n+1 numbers all pointing to indices in a 1..n ran...
Linked List Cycle #141
Floyd's Cycle Detection Algorithm (Two Pointer / Tortoise and Hare)
Imagine two runners on a track. If the track is a straight line (no cycle), the faster runner will eventually finish and leave the slower runner behin...
LRU Cache #146
HashMap + Doubly Linked List
Imagine a library desk where you keep your most-used reference books within arm's reach. When you need a book, you grab it from the desk (fast access)...
Merge K Sorted Lists #23
Heap-based merging (Priority Queue optimization)
Imagine k sorted streams of water flowing into one river. At each moment, you only care about finding the smallest drop at the very front of ALL strea...
Merge Two Sorted Lists #21
Two-pointer merge (merge sorted sequences)
Imagine two conveyor belts delivering sorted packages, and you need to unload them onto a single belt in order. Both belts are already sorted, so at a...
Remove Nth Node From End of List #19
Fast-Slow Pointer (Two Pointer) with Dummy Head
Imagine two runners on a track. The second runner starts n positions behind the first. When the first runner reaches the finish line (end of list), th...
Reorder List #143
Three-step pointer manipulation: (1) Find middle using slow/fast pointers, (2) Reverse the second half, (3) Interleave nodes from first half with reversed second half.
Think of this like shuffling a deck of cards. You split the deck in half, reverse the second half, then interleave them like shuffling. The challenge ...
Reverse Linked List #206
Three-pointer in-place reversal
Imagine a train with cars connected in a line. Each car has a coupler pointing forward to the next car. To reverse the train, you don't detach the car...
Reverse Nodes in K-Group #25
Reversal with boundary checking - this is the 'localized reversal' pattern where you reverse a bounded segment while maintaining the list's overall structure. It combines: (1) boundary detection - checking if k nodes exist, (2) classic 3-pointer linked list reversal, and (3) reconnection - stitching the reversed segment back into the list.
Think of this like reversing paragraphs in an essay while keeping sentences intact. You have a linked list (like a train of k-car segments), and you r...

Trees (15)

Balanced Binary Tree #110
Bottom-up recursion with early termination (post-order traversal)
Think of a balanced tree like a well-designed building - no single column should be dramatically taller than its neighbor, or the structure becomes un...
Binary Tree Level Order Traversal #102
BFS (Breadth-First Search) on a tree using a queue, with level-by-level processing
Think of this like ripples spreading outward from a stone dropped in water. When you process a tree breadth-first, you're essentially flooding it leve...
Binary Tree Maximum Path Sum #124
Post-order DFS with state propagation. Each recursive call returns the maximum path sum starting from that node and going DOWN (single branch), while updating a global answer for paths that go THROUGH the node (both branches).
Think of each node as a junction where energy/power can flow through. A path through a node can either: (1) flow from one child through the node to th...
Binary Tree Right Side View #199
Level-order traversal (BFS) or Depth-first search with right-first ordering
Imagine standing on the right side of a binary tree and taking a photograph. What do you see? At each horizontal 'depth level', you see the rightmost ...
Construct Binary Tree from Preorder and Inorder Traversal #105
Recursive divide-and-conquer with index tracking and hashmap lookup
Think of this like archaeology at two dig sites. Preorder (root-first) tells you 'here's the family head,' and inorder (left-root-right) tells you 'he...
Count Good Nodes in Binary Tree #1448
DFS with path state tracking. We maintain the maximum value encountered along the current root-to-node path as we traverse.
Think of this like a 'peak detector' on a mountain range. As you walk from the root down any path, you're tracking the highest elevation seen so far. ...
Diameter of Binary Tree #543
Post-order DFS with global state tracking. This pattern applies when: (1) you need information from children before computing parent results, (2) the answer isn't necessarily at the root, and (3) you need to track a global maximum while doing local computations at each node.
Think of the tree as a network of branches. The diameter is the longest distance between any two leaf nodes in this network. Here's the key insight: t...
Invert Binary Tree #226
Depth-First Search (DFS) with recursion - specifically post-order traversal where we process children before the parent. This is a divide-and-conquer approach.
Think of this like reflecting a binary tree in a vertical mirror. Every left child becomes a right child and vice versa - it's a horizontal flip. At e...
Kth Smallest Element in a BST #230
In-order traversal with early termination
Think of a BST as a sorted array that's been 'folded' into a tree shape. The BST property (left subtree < root < right subtree) means if you read it i...
Lowest Common Ancestor of a BST #235
Binary Search on Tree (using BST property to prune half the search space at each step)
Think of a BST as a sorted hierarchy - like an org chart sorted by employee ID. The two nodes p and q each have a 'path' from the root. The LCA is whe...
Maximum Depth of Binary Tree #104
DFS (Depth-First Search) with recursion / divide and conquer
Think of this like measuring how tall a tree grows — from the trunk (root) down to the farthest leaf. You're essentially asking: 'How many levels of b...
Same Tree #100
Depth-First Search (DFS) / Structural Recursion
Imagine you're comparing two trees in a forest - you need to check if every branch, twig, and leaf is in exactly the same position. Two trees are iden...
Serialize and Deserialize Binary Tree #297
Pre-order depth-first traversal with null sentinel markers
Think of serialization like creating a shipping manifest for a fractal structure. A binary tree has 'gaps' where branches don't exist — you need to re...
Subtree of Another Tree #572
Recursive tree traversal with equality checking (the 'check everywhere' pattern).
Think of this like finding a pattern in a larger structure. Imagine you're looking for a specific subtree shape within a bigger tree - it's like patte...
Validate Binary Search Tree #98
Tree traversal with constraint propagation (bounded recursion)
Think of a BST like a distribution center with strict ordering rules. Every piece of mail going left must be 'less than' the current location, every p...

Tries (3)

Design Add and Search Words Data Structure #211
Trie (Prefix Tree) with DFS backtracking for wildcard search
Think of this like organizing words in a physical dictionary where each page represents a letter. If you're looking for 'cat', you go to the 'c' secti...
Implement Trie (Prefix Tree) #208
Trie (Prefix Tree) with hashmap children
Imagine a filing cabinet where you organize words by their first letter, then within each drawer you organize by second letter, and so on. That's esse...
Word Search II #212
Trie + Backtracking (DFS)
Imagine you're searching for words in a crossword puzzle. Instead of taking each word from your list and individually hunting for it on the grid (slow...

Heap / Priority Queue (7)

Design Twitter #355
Merge K Sorted Streams with Heap (Top-K Selection)
Think of this like a news aggregator merging multiple feeds. Each user has their own feed (a stream of tweets sorted by time). When you want your news...
Find Median from Data Stream #295
Two-Heap / Dual Priority Queue Pattern
Think of median as finding the 'balance point' on a number line where half your data sits on each side. The most elegant way to maintain this split is...
K Closest Points to Origin #973
Max Heap / Priority Queue (maintain k-smallest elements)
Imagine you're at a party and you want to find the k people closest to you. You could measure everyone's distance, sort everyone by how close they are...
Kth Largest Element in a Stream #703
Heap as a sliding window / maintain k largest elements
Think of this like maintaining a 'water level' in a lake. The kth largest element is like the k-th highest point. If you're at a party and someone ask...
Kth Largest Element in an Array #215
K-Largest Elements Heap Pattern (Min-heap of size k)
Think of this like finding the kth tallest person in a crowd. You could sort everyone by height (expensive), or you could maintain a 'top k' list that...
Last Stone Weight #1046
Max Heap / Priority Queue - Extract Max pattern
Think of this like a collision/energy dissipation system. When two stones smash, their 'energy' (weight) partially dissipates - if equal, all energy i...
Task Scheduler #621
Greedy formula from max frequency - calculate the minimum intervals needed based on the most frequent task's spacing requirements
Think of this like scheduling workers at a factory. You have different types of jobs (tasks), but if you do the same job twice too quickly, the machin...

Backtracking (9)

Combination Sum II #40
Backtracking with sorting-based duplicate elimination
Think of this as exploring a decision tree where each number can either be included or excluded from our current combination. The key insight is that ...
Combination Sum #39
Backtracking with sorting and pruning
Think of this as a budget allocation problem. You have a target 'spending limit' and a list of 'items' you can buy (the candidates). Each item costs i...
Letter Combinations of a Phone Number #17
Cartesian Product via Backtracking - you're computing the Cartesian product of multiple sets (the letters corresponding to each digit), generating all possible tuples by taking one element from each set.
Think of this like a tree growing horizontally. You start with an empty branch, and for each digit, you SPLIT that branch into multiple smaller branch...
N-Queens #51
Backtracking with state sets
Imagine each queen as a radio tower broadcasting interference along its row, column, and two diagonals. Your job is to place N towers so their 'signal...
Palindrome Partitioning #131
Backtracking with palindrome validation
Think of this like a factory line where you're cutting a rope into segments. At each position, you decide whether to make a cut. Each segment you prod...
Permutations #46
Backtracking / Depth-First Search on a choice tree
Think of arranging books on a shelf. You have n books and n slots. For the first slot, you can pick any of the n books. For the second slot, any of th...
Subsets II #90
Backtracking with duplicate skipping (sort-and-skip pattern)
Think of this like organizing a photo album where you have multiple identical photos of the same person. You want to create pages representing all pos...
Subsets #78
Backtracking / Decision Tree Traversal
Think of this like exploring all possible paths in a decision tree. For each element in the array, you face a binary choice: include it in your curren...
Word Search #79
Backtracking (Depth-First Search on a grid)
Imagine you're exploring a cave system looking for a hidden message written on rocks. You can only move up, down, left, or right, and you can't step o...

Graphs (13)

Clone Graph #133
Graph Traversal with Node Mapping (DFS/BFS with Hash Map)
Think of this like copying a social network. You know one person, and you need to map out ALL their connections, then build an exact duplicate network...
Course Schedule II #210
Topological Sort using Kahn's Algorithm (BFS with in-degree counting)
Think of this like a dependency resolution system — like a package manager installing software where each package might depend on others already insta...
Course Schedule #207
Cycle Detection in Directed Graph using Topological Sort (Kahn's Algorithm)
Think of this like planning a construction project. Each course is a 'task' and each prerequisite is a 'dependency' - you must complete prerequisites ...
Graph Valid Tree #261
Union-Find (Disjoint Set Union) / Cycle Detection
Think of a tree as a connected water pipeline system with n houses. To connect ALL houses, you need exactly n-1 pipes. Any more and you create a loop ...
Max Area of Island #695
Graph traversal - finding connected components using flood fill (DFS or BFS).
Think of the grid as a city where 1s are buildings and 0s are empty lots. You want to find the largest contiguous block of buildings. The trick: when ...
Number of Connected Components in an Undirected Graph #323
Union-Find (Disjoint Set Union / DSU)
Think of this like counting isolated islands on a map. Each connected group of nodes is like an island - you can travel between any two nodes within a...
Number of Islands #200
Depth-First Search (DFS) flood fill / Connected Components
Think of the grid as a map where '1' is land and '0' is water. Each island is a connected blob of land - like a territory on a map. The key insight: o...
Pacific Atlantic Water Flow #417
Reverse flood-fill from boundaries (also called 'multi-source BFS/DFS')
Imagine you're a drop of water on a mountain range. You can only flow downhill (or stay level) to neighboring cells. The Pacific Ocean touches the lef...
Redundant Connection #684
Union-Find / Disjoint Set Union (DSU)
Think of this like building a river delta. A tree is like a river system with no loops - there's exactly one path from any point to any other. When yo...
Rotting Oranges #994
Multi-Source Breadth-First Search (BFS)
Think of this like a contagion spreading through a population. Rotten oranges are 'infected' nodes that transmit the infection to adjacent healthy nod...
Surrounded Regions #130
Boundary-Connected Flood Fill with Complement
Think of this like water flow or an escape room. The 'O's on the boundary are like exits - any 'O' connected to the boundary can 'escape' to the outsi...
Walls and Gates #286
Multi-Source Breadth-First Search (BFS)
Think of this as dropping pebbles (gates) into a pond simultaneously. Each ripple expands outward one unit at a time. When a ripple first touches an e...
Word Ladder #127
BFS on an implicit graph with bidirectional wildcard indexing. This is fundamentally a shortest-path problem on an unweighted graph where nodes are words and edges exist between words differing by exactly one letter.
Imagine each word as a node in a vast network, and you can jump between nodes if they're exactly one letter apart (like 'hit' → 'hot'). You're trying ...

Advanced Graphs (6)

Alien Dictionary #269
Topological Sort (Kahn's Algorithm)
Imagine you're a linguist trying to reconstruct an alien alphabet from a dictionary. You have words sorted in unknown order, and you need to deduce ch...
Cheapest Flights Within K Stops #787
Constrained Shortest Path with Bellman-Ford
Think of this like finding the cheapest subway route where you're limited in how many transfers (stops) you can make. Each flight is a 'step' in the j...
Min Cost to Connect All Points #1584
Minimum Spanning Tree (MST) using Prim's Algorithm
Think of this like building a railway network across cities. You need to connect all cities but want to minimize total track length. The key insight: ...
Network Delay Time #743
Single-Source Shortest Path (SSSP) with Dijkstra's Algorithm
Think of this like dropping a stone in a pond and watching the ripples spread outward. The signal propagates from source k like a wavefront, with each...
Reconstruct Itinerary #332
Hierholzer's Algorithm variant with greedy edge selection (Eulerian Path in directed graph)
Think of this like planning a road trip where you MUST use every single road exactly once - you're finding a Eulerian path. The key insight: when you ...
Swim in Rising Water #778
Minimax path with node costs using modified Dijkstra's algorithm. Instead of summing edge weights, we take the maximum of the path cost and current node's cost.
Think of this like escaping a flooding terrain. You start at the highest point of your path and wait as water rises. The question is: how high must th...

1-D Dynamic Programming (12)

Climbing Stairs #70
Fibonacci Sequence / Dynamic Programming with O(1) Space
Imagine water flowing down a staircase. At each step, the 'flow' (number of ways to arrive) comes from two sources: the step immediately above (arrive...
Coin Change #322
Dynamic Programming - Bottom-up Tabulation (Unbounded Knapsack variant for minimization)
Think of this like climbing a ladder where each coin is a step size. You're at amount 0 and want to reach your target amount. Each coin denomination l...
Decode Ways #91
1-D Dynamic Programming (Fibonacci-like)
Think of this like a signal propagating through a chain. Each digit is a signal that can either stand alone (decode as a single letter) or combine wit...
House Robber II #213
1-D Dynamic Programming with circular boundary handling - breaking a circular constraint into two linear subproblems
Imagine the houses as a circular necklace. The key insight is that in a circle, if you rob house 0, you CANNOT rob house n-1 (they're adjacent). But i...
House Robber #198
1-D Dynamic Programming with Linear Scrolling State
Imagine you're a mountain climber choosing which peaks to summit. You can only move to non-adjacent peaks (can't rob neighboring houses). At each peak...
Longest Increasing Subsequence #300
Patience Sorting with Binary Search (O(n log n)) - a greedy + binary search hybrid
Imagine you're stacking coins in a row, but you can only place each new coin on top of a smaller coin - you want the tallest possible tower. You don't...
Longest Palindromic Substring #5
Two-pointer expansion from centers (also called 'center expansion').
Think of a palindrome as a mirror image - the left side reflects the right side. For any position in a string, imagine you're standing at a center poi...
Maximum Product Subarray #152
Extended Kadane's Algorithm with dual state tracking
Think of this like tracking a signal that can flip polarity. In Maximum Sum Subarray, we could just track the best positive sum because negatives only...
Min Cost Climbing Stairs #746
1-D Dynamic Programming with optimal substructure
Think of this like a ball rolling up a hill with energy costs at each position. At every stair, the ball has two choices: take one step or skip one. T...
Palindromic Substrings #647
Expand Around Center - a fundamental palindrome enumeration technique
Think of a palindrome like a balanced system - it has a center of symmetry, and characters mirror outward from that center like a ripple in a pond. Wh...
Partition Equal Subset Sum #416
Subset Sum / 0-1 Knapsack - Each element can be either IN a subset or NOT in it (two choices), and we want to hit an exact target sum.
Think of this like a balance scale. If the total weight is odd, the scale can never balance—immediate fail. If it's even, we just need to find ONE sub...
Word Break #139
Linear Scan with Reachability DP
Think of this as a pathfinding problem through the string. You're standing at position 0 and want to reach position n (the end). Each valid word in th...

2-D Dynamic Programming (11)

Best Time to Buy and Sell Stock with Cooldown #309
State Machine DP with three states
Think of this as a state machine with three positions: (1) HOLDING a stock, (2) NOT HOLDING and CAN BUY, (3) COOLDOWN (just sold yesterday, can't buy ...
Burst Balloons #312
Interval Dynamic Programming (also called 'Divide and Conquer DP')
Think of this backwards: instead of asking which balloon to burst FIRST, ask which one was burst LAST. When the final balloon bursts, its only neighbo...
Coin Change II #518
2D Dynamic Programming with outer loop over coins, inner loop over amounts
Think of this as counting the number of ways to distribute a 'flow' of amount units across different coin types. Imagine coins as different colored ba...
Distinct Subsequences #115
2D Dynamic Programming (DP)
Think of this as counting the number of distinct paths through s that can spell out t. At each character in s, you have a choice: either match it with...
Edit Distance #72
2D Dynamic Programming on Two Sequences
Think of this as transforming one system (word1) into another (word2). Each character is a component, and you're allowed three 'moves': insert a new c...
Interleaving String #97
2-D Dynamic Programming (grid path-finding)
Think of this like two rivers merging. s1 and s2 are tributaries that must merge to form s3, maintaining their internal order but mixing characters. I...
Longest Common Subsequence #1143
2D Dynamic Programming (Edit Distance family)
Imagine two rivers (the two strings) flowing side by side. A subsequence is like a path that follows the river but can skip around. The LCS is the lon...
Longest Increasing Path in a Matrix #329
DFS with Memoization (Topological DP on DAG)
Imagine each cell's value as an elevation. You're a hiker who can only walk uphill (to strictly higher values). You want to find the longest possible ...
Regular Expression Matching #10
2-D Dynamic Programming on two strings (like Longest Common Subsequence, Edit Distance, Wildcard Matching)
Think of this as a signal propagation or state machine problem. You're trying to find a 'path' through both strings where each step either consumes a ...
Target Sum #494
Subset Sum / 0-1 Knapsack (counting variation)
Think of this as a conservation law problem - imagine you have weights (the array elements) and you want to balance a scale. Placing a number on the l...
Unique Paths #62
2D Dynamic Programming (Grid DP)
Imagine this like water flowing through a grid of pipes. At each intersection, the water can split — it can go right or down. The number of ways to re...

Greedy (8)

Gas Station #134
Greedy with proof / Single-pass proof. We make a locally optimal choice (move start forward when we fail) that guarantees global optimality because of the conservation law (total gas vs total cost).
Think of this as an energy conservation problem. At each station, you gain gas[i] and spend cost[i] to move forward. If total_gas < total_cost over th...
Hand of Straights #846
Greedy with Counter/Frequency Map
Think of this like organizing numbered books into consecutive groups. You have a pile of numbered books and need to form stacks where each stack has c...
Jump Game II #45
Greedy - Always choose the option that maximizes immediate reach (lookahead one step)
Imagine you're hopping across lily pads. Each lily pad tells you how far you can jump from there. You want minimum hops to reach the last pad. The gre...
Jump Game #55
Greedy - keep track of maximum reach
Think of this like a signal propagating outward from the start position. Each element tells you the maximum range of that signal - from position i, th...
Maximum Subarray #53
Kadane's Algorithm (Greedy)
Imagine you're tracking your bank balance over time. Each day has a positive or negative balance change. You want to find the contiguous period (subar...
Merge Triplets to Form Target Triplet #1899
Greedy - greedy selection works because the problem has a matroid-like structure. We don't need to optimize which triplets to pick; we only need to verify existence. Once a triplet is valid (all values <= target), adding more valid triplets can only help (never hurt) because we're taking max values.
Think of each triplet as a 'supply' of three resources. You can only use triplets where ALL three values are at or below the target (otherwise you'd o...
Partition Labels #763
Two-pass greedy with last occurrence tracking. First, find each character's final position. Then, traverse while maintaining the furthest last-seen position of any character in the current partition. When current index hits that furthest point, we have a complete partition.
Think of each letter as a 'signal' that starts at its first appearance and ends at its last appearance. We're trying to find natural boundaries where ...
Valid Parenthesis String #678
Greedy with range tracking (min/max balance)
Think of parentheses like a see-saw or a balance scale. At any point, the number of '(' minus ')' represents how much 'weight' is on the left side. No...

Intervals (6)

Insert Interval #57
Linear scan with three-way case analysis (intervals before, intervals after, intervals that overlap with new). This is essentially a 'sweep line' where we process intervals in sorted order and decide what to do with each one relative to the new interval.
Think of this like adding a new meeting to a calendar. You have a list of non-overlapping meetings sorted by start time. When you add a new meeting, y...
Meeting Rooms II #253
Min-Heap (Priority Queue) / Sweep Line
Think of this like a busy hotel. When guests check in, they need rooms. When they check out, rooms become available. The question is: at the busiest m...
Meeting Rooms #252
Sorting + Sequential Greedy Check (Sweep Line variant)
Imagine you're scheduling trains on a single track. Each meeting is like a train that occupies the track for a certain duration. Can all trains run on...
Merge Intervals #56
Sort and Scan (Sweep Line variant)
Think of intervals like train tracks laid out on a table. Some tracks overlap (share rails), some are separate. Your job is to find all the continuous...
Minimum Interval to Include Each Query #1851
Sweep Line with Priority Queue (Active Intervals)
Think of this like matching 'service providers' (intervals) to 'customers' (query points). Each provider covers a range, and each customer needs servi...
Non-overlapping Intervals #435
Greedy - Activity Selection (Earliest Finish Time)
Imagine you're packing boxes into a fixed-length shelf. To fit the most boxes, you'd pick the narrowest boxes first - they leave maximum room for the ...

Math & Geometry (8)

Detect Squares #2013
Diagonal-pair enumeration with hash-based point lookup
Think of this like a resonance detector. When you add a point, it creates potential 'vibrations' that can resonate with other points to form squares. ...
Happy Number #202
Floyd's Tortoise and Hare (Cycle Detection) - same technique used for detecting loops in linked lists.
Think of this like a feedback loop in a system. You take a number, crunch its digits into a new number, and feed that back in. The question is: does t...
Multiply Strings #43
Digit-by-digit multiplication with positional accumulation
Think of multiplication like waves colliding. When you multiply digit[i] from the first number with digit[j] from the second, their 'energy' arrives a...
Plus One #66
Carry propagation / digit-by-digit processing
Think of adding 1 like pouring water into a graduated cylinder. You fill up the rightmost 'bucket' (ones place). If it overflows (hits 10), it empties...
Pow(x, n) #50
Binary Exponentiation (Exponentiation by Squaring)
Think of exponentiation like a nuclear chain reaction or signal propagation. If you want x^16, you don't multiply x by itself 16 times - you double: x...
Rotate Image #48
Layer-by-layer 4-way swap with in-place rotation
Imagine you're rotating a physical photo frame 90° clockwise. The top-left corner moves to top-right, top-right to bottom-right, and so on. Here's the...
Set Matrix Zeroes #73
In-place State Preservation using matrix boundaries as markers
Think of this like contamination detection. Each 0 is a 'contaminant' that needs to spread along its entire row and column. The challenge: you need to...
Spiral Matrix #54
Boundary Traversal / Layer-by-layer peeling
Think of a snail crawling through the matrix starting from the top-left corner. It crawls right until it hits a wall, then turns down, then left, then...

Bit Manipulation (7)

Counting Bits #338
Dynamic Programming on binary representation. The recurrence relation is: dp[n] = dp[n >> 1] + (n & 1).
Think of binary numbers as a tree where each number's 'parent' is itself right-shifted by 1 (dividing by 2). A number's bit count = its parent's bit c...
Missing Number #268
XOR Identity / Sum Conservation
Think of this like a conservation law. We know the complete set should be 0 through n, but one number is 'leaking' out. If we add up what we SHOULD ha...
Number of 1 Bits #191
Bit Manipulation - Remove Rightmost Set Bit
Think of each set bit as an 'energy source' in a system. The trick `n & (n-1)` acts like a drain that removes exactly one source per operation — speci...
Reverse Bits #190
Bit-by-bit extraction and reconstruction
Think of the 32 bits as a line of 32 dominoes. Each domino is either standing (1) or fallen (0). 'Reversing bits' is like reflecting this line in a mi...
Reverse Integer #7
Digit-by-digit accumulation with overflow guards
Think of reversing an integer like stacking rings on a pole. Each new digit taken from the original number gets placed on top, pushing everything else...
Single Number #136
XOR Cancellation / Bit Manipulation
Imagine each number as a particle, and pairs of identical numbers as matter and antimatter - when they meet, they annihilate completely (become 0). XO...
Sum of Two Integers #371
Iterative Bitwise Carry Propagation
Think of binary addition like water flowing in connected containers. When you add 1+1 at any bit position, you get 0 there but create a 'overflow' (ca...