Every problem of the NeetCode 150 list, each in its own file, worked extensively: problem statement → brute force → optimal, with code, complexity, and the key insight. The one-line “why this problem is here” and the link to the underlying concept note stay in the tables below; the files are the full solutions.

This complements the concept notes in the folders above (data-structures, algorithms, patterns) — read the concept first to learn the tool, then these to see it applied.

Structure: every solution lives flat in questions/, numbered 001–150 in NeetCode order (so the folder reads in curriculum order without nesting). The topic grouping lives here in this index, not in the folder layout — this README is the map, questions/ is the content.

New to interviews? Read the interview playbook first — the UMPIRE process (reword → clarify → examples → brute-force-then-optimize → code → test) and how to read a problem’s constraints and stated complexity to guess the intended approach before you’ve solved it. The cheat-sheet below is shape → tool; the playbook is how to run the whole interview.

Pattern cheat-sheet — signal → tool

Most of the interview battle is recognizing which of ~18 tools a problem is asking for. This maps the tell-tale signal in a problem to the pattern and its concept note. Read it as “when I see X, reach for Y.”

When you see…Reach forNote
”have I seen this?”, count occurrences, dedupe, find a pair by valueHash map / set — trade space for O(1) lookuphash-maps
sorted array + find a pair/triplet, palindrome, work from both endsTwo pointers converging inward (O(1) space)two-pointers
longest/shortest contiguous substring/subarray meeting a constraintSliding window — grow right, shrink left when invalidsliding-window
matched brackets, “most recent unclosed”, next greater/smaller elementStack / monotonic stackstacks · monotonic-stack
sorted input & search; OR “minimize the max / min feasible speed/capacity”Binary search — incl. on the answer (monotonic predicate)modified-binary-search
reverse a list, detect a cycle, find the middle / n-th from endLinked-list pointers — reversal, fast/slowreversal · fast-slow
”do X at every node, combine children”; OR level-by-levelTree DFS (return up / carry down) · BFS by leveldfs · bfs
prefix / autocomplete queries, search many words in a gridTrie (+ backtracking for grids)tries
”k largest/smallest”, “top k”, running median, merge k sortedHeap (size-k, or two-heap)heaps · top-k
”generate all subsets / permutations / combinations”, place-then-undoBacktracking (choose → recurse → un-choose)backtracking
grid connectivity, islands, flood fill, fewest steps on a gridGraph DFS/BFS (multi-source BFS for nearest)matrix-traversal · graphs
prerequisites, build/task ordering, “can everything be ordered?”Topological sort (Kahn’s) = cycle detectiontopological-sort
”same group?”, dynamic connectivity, cycle in an undirected graphUnion-Find (a failed union = a cycle)union-find
shortest path with weights; OR connect everything at min costDijkstra · MST (Prim/Kruskal); hop-limited → Bellman-Forddijkstra · MST
”count the ways”, min/max over choices, overlapping subproblemsDynamic programming (find the recurrence)DP
a locally-optimal choice that’s provably globally optimalGreedy (justify with an exchange argument)greedy
overlapping ranges, merge intervals, meeting roomsIntervals — sort by start/end, then sweep (+ heap)overlapping-intervals
O(1) space demanded, “appears once”, XOR hints, powers of twoBit manipulation (XOR cancel, n & (n-1))bit-manipulation
rotate/spiral/zero a matrix in place, fast xⁿ, big-int arithmeticMath & geometry (in-place tricks, binary exponentiation)math-and-geometry

Also read the constraints first. The input size n usually leaks the intended complexity — n ≤ 20 hints at exponential backtracking/bitmask, n ≤ ~5000 at O(n²) DP, n ≤ 10⁵ at O(n log n) or O(n), n ≥ 10⁹ at O(log n) or math. See the constraint→complexity heuristic in algorithms.

Progress

  • Arrays & Hashing (9)
  • Two Pointers (5)
  • Sliding Window (6)
  • Stack (7)
  • Binary Search (7)
  • Linked List (11)
  • Trees (15)
  • Tries (3)
  • Heap / Priority Queue (7)
  • Backtracking (9)
  • Graphs (13)
  • Advanced Graphs (6)
  • 1-D Dynamic Programming (12)
  • 2-D Dynamic Programming (11)
  • Greedy (8)
  • Intervals (6)
  • Math & Geometry (8)
  • Bit Manipulation (7)

All 150 solved. ✅

Arrays & Hashing — hash-maps

Trade space for O(1) lookup; recognize when a hash map/set collapses an O(n²) scan to O(n).

#ProblemKey idea
217Contains Duplicatehash set membership
242Valid Anagramchar-count map equality
1Two Summap value → index; look for the complement
49Group Anagramskey by char-count signature
347Top K Frequent Elementscount map + bucket sort
271Encode and Decode Stringslength-prefix each string
238Product of Array Except Selfprefix × suffix, no division
36Valid Sudokuhash sets per row/col/box
128Longest Consecutive Sequenceset; start a run only at its left edge

Two Pointers — two-pointers

#ProblemKey idea
125Valid Palindromepointers in from both ends, skip non-alphanumerics
167Two Sum IIinward pointers; move by sum vs target
153Sumsort, fix one, two-pointer the rest; skip dupes
11Container With Most Waterwidest first; move the shorter wall inward
42Trapping Rain Watertwo pointers tracking left/right max walls

Sliding Window — sliding-window

#ProblemKey idea
121Best Time to Buy and Sell Stocktrack min-so-far; window = buy…sell
3Longest Substring Without Repeating Charactersgrow; shrink on a repeat
424Longest Repeating Character Replacementvalid while (len − maxfreq) ≤ k
567Permutation in Stringfixed window; compare char counts
76Minimum Window Substringexpand to satisfy, contract to minimize
239Sliding Window Maximummonotonic deque of candidate maxima

Stack — stacks-and-queues

#ProblemKey idea
20Valid Parenthesespush opens, match/pop on closes
155Min Stackpair each value with the min-so-far
150Evaluate Reverse Polish Notationpop operands, push results
22Generate Parenthesesbacktracking with open/close counts
739Daily Temperaturesmonotonic stack of indices
853Car Fleetsort by position; monotonic stack of times
84Largest Rectangle in Histogrammonotonic stack of increasing heights
#ProblemKey idea
704Binary Searchthe baseline half-and-discard
74Search a 2D Matrixtreat the grid as one sorted array
875Koko Eating Bananasbinary search on the answer
153Find Minimum in Rotated Sorted Arraycompare mid to right
33Search in Rotated Sorted Arrayfind the sorted half, then bound
981Time Based Key-Value Storebinary search over timestamps
4Median of Two Sorted Arraysbinary search on the partition

Linked List — linked-lists

#ProblemKey idea
206Reverse Linked Listiterative pointer flip
21Merge Two Sorted Liststwo-pointer merge with a dummy
143Reorder Listmid + reverse + interleave
19Remove Nth Node From Endtwo pointers n apart
138Copy List with Random Pointerinterleave clones or old→new map
2Add Two Numbersdigit-by-digit with carry
141Linked List CycleFloyd’s fast/slow
287Find the Duplicate NumberFloyd’s on value-as-pointer
146LRU Cachehash map + doubly linked list
23Merge K Sorted Listsmin-heap of k heads
25Reverse Nodes in k-Groupreverse each k-block

Trees — trees · traversal

#ProblemKey idea
226Invert Binary Treeswap children recursively
104Maximum Depth of Binary Tree1 + max(left, right)
543Diameter of Binary Treemax(left height + right height)
110Balanced Binary Treeheight check returning −1 on imbalance
100Same Treestructural + value recursion
572Subtree of Another Tree”same tree” at every node
235Lowest Common Ancestor of a BSTdescend by BST ordering
102Binary Tree Level Order TraversalBFS by level
199Binary Tree Right Side ViewBFS; last node per level
1448Count Good Nodes in Binary TreeDFS carrying max-on-path
98Validate Binary Search TreeDFS carrying (min, max)
230Kth Smallest Element in a BSTin-order, stop at k
105Construct Tree from Preorder & Inorderroot from pre, split via in
124Binary Tree Maximum Path SumDFS best-arm + global max
297Serialize and Deserialize Binary Treepre-order with null markers

Tries — tries

#ProblemKey idea
208Implement Trie (Prefix Tree)insert / search / startsWith
211Design Add and Search Wordswildcard . → branch DFS
212Word Search IIone trie + grid backtracking

Heap / Priority Queue — heaps · top-k

#ProblemKey idea
703Kth Largest Element in a Streammin-heap of size k
1046Last Stone Weightmax-heap, smash two heaviest
973K Closest Points to Originheap by squared distance
215Kth Largest Element in an Arrayheap O(n log k) vs Quickselect
621Task Schedulermax-heap by count + cooldown
355Design Twitterk-way merge via heap
295Find Median from Data Streamtwo heaps

Backtracking — backtracking

#ProblemKey idea
78Subsetsinclude/exclude each element
39Combination Sumreuse allowed; recurse on same index
46Permutationsswap-in-place or used-set
90Subsets IIsort, skip duplicate siblings
40Combination Sum IIsort, each once, skip dup siblings
79Word Searchgrid DFS with visited + undo
131Palindrome Partitioningcut at every palindromic prefix
17Letter Combinations of a Phone Numberproduct over digit→letters
51N-Queensplace per row; column/diagonal sets

Graphs — graphs · matrix-traversal

#ProblemKey idea
200Number of Islandsgrid flood fill, count components
133Clone GraphDFS/BFS with old→new map
695Max Area of Islandflood fill returning area
417Pacific Atlantic Water Flowreverse-flow BFS from both oceans
130Surrounded Regionsmark border-connected regions safe
994Rotting Orangesmulti-source BFS by minute
286Walls and Gatesmulti-source BFS from gates
207Course Scheduletopological-sort feasibility
210Course Schedule IItopological order itself
684Redundant Connectionunion-find; first cycle edge
323Number of Connected Componentsunion-find; count roots
261Graph Valid Treeunion-find; n−1 edges, no cycle
127Word LadderBFS over one-letter-change neighbors

Advanced Graphs — dijkstra · MST · topo-sort

#ProblemKey idea
332Reconstruct ItineraryHierholzer’s Eulerian path
1584Min Cost to Connect All PointsMST (Prim’s / Kruskal’s)
743Network Delay TimeDijkstra, take the max
778Swim in Rising WaterDijkstra / binary search on max cell
269Alien Dictionaryprecedence edges → topological sort
787Cheapest Flights Within K StopsBellman-Ford bounded to k+1

1-D Dynamic Programming — dynamic-programming

#ProblemKey idea
70Climbing StairsFibonacci shape
746Min Cost Climbing Stairsmin of two prior + cost
198House Robbermax(skip, rob + dp[i-2])
213House Robber IItwo linear runs (drop first/last)
5Longest Palindromic Substringexpand around center
647Palindromic Substringscount center expansions
91Decode Ways1-digit and valid 2-digit splits
322Coin Changeunbounded knapsack
152Maximum Product Subarraytrack running max and min
139Word Breakdp[i] true if a word ends at i
300Longest Increasing Subsequencedp[i]=1+max(dp[j]<); O(n log n)
416Partition Equal Subset Sumsubset-sum to total/2

2-D Dynamic Programming — dynamic-programming

#ProblemKey idea
62Unique Pathsdp[r][c]=dp[r-1][c]+dp[r][c-1]
1143Longest Common Subsequencematch → diagonal+1
309Buy/Sell Stock with Cooldownhold/sold/rest state machine
518Coin Change IIcount combinations
494Target Sum± signs → subset-sum count
97Interleaving String2-D reachability
329Longest Increasing Path in a MatrixDFS + memo
115Distinct Subsequencesmatch → sum; else carry
72Edit Distance1+min(insert, delete, replace)
312Burst Balloonsinterval DP on last balloon
10Regular Expression Matching2-D with */. transitions

Greedy — greedy

#ProblemKey idea
53Maximum SubarrayKadane’s
55Jump Gamefarthest reachable index
45Jump Game IIextend current jump’s range
134Gas Stationfailing point + 1 if total ≥ 0
846Hand of Straightscount map + take runs from smallest
1899Merge Triplets to Form Targetkeep triplets never exceeding target
763Partition Labelsextend to last index of each char
678Valid Parenthesis Stringtrack min/max open count

Intervals — overlapping-intervals

#ProblemKey idea
57Insert Intervalbefore / merge / after
56Merge Intervalssort by start, merge touching
435Non-overlapping Intervalssort by end; count removals
252Meeting Roomssort; any overlap → false
253Meeting Rooms IImin-heap of end times
1851Minimum Interval to Include Each Querysort + heap by size

Math & Geometry — math-and-geometry

#ProblemKey idea
48Rotate Imagetranspose + reverse rows
54Spiral Matrixfour shrinking boundaries
73Set Matrix Zeroesuse row 0 / col 0 as markers
202Happy Numbercycle detection
66Plus Onegrade-school carry
50Pow(x, n)fast exponentiation
43Multiply Stringsdigit-by-digit multiply
2013Detect Squarespoint-count hash map

Bit Manipulation — bit-manipulation

#ProblemKey idea
136Single NumberXOR everything; pairs cancel
191Number of 1 Bitsx &= x-1 (Kernighan)
338Counting Bitscount[i]=count[i>>1]+(i&1)
190Reverse Bitsshift out, shift in, ×32
268Missing NumberXOR indices with values
371Sum of Two IntegersXOR + carry loop
7Reverse Integerreverse digits with overflow guard
↑ Back to Data Structures & Algorithms