360 questions: 270 Medium + 90 Hard, grouped by coding pattern.
Practice order
- P1: core patterns. Start here.
- P2: variations that build on P1.
- P3: advanced problems and combined patterns.
For each question, write a solution, test edge cases, and explain its time and space complexity. Check it off when you can solve it again without hints. Premium marks questions that require paid access.
Questions
1. Hashing, prefix sums and arrays — 27
- P1 LC 49 — Group Anagrams — Medium · canonical grouping
- P1 LC 128 — Longest Consecutive Sequence — Medium · sequence starts
- P1 LC 238 — Product of Array Except Self — Medium · prefix/suffix products
- P1 LC 560 — Subarray Sum Equals K — Medium · prefix sum frequency
- P1 LC 36 — Valid Sudoku — Medium · constraint sets
- P1 LC 380 — Insert Delete GetRandom O(1) — Medium · index map + swap deletion
- P1 LC 53 — Maximum Subarray — Medium · Kadane invariant
- P1 LC 75 — Sort Colors — Medium · Dutch national flag
- P1 LC 73 — Set Matrix Zeroes — Medium · in-place markers
- P1 LC 54 — Spiral Matrix — Medium · boundary simulation
- P1 LC 48 — Rotate Image — Medium · matrix transpose/reverse
- P2 LC 525 — Contiguous Array — Medium · balanced prefix state
- P2 LC 523 — Continuous Subarray Sum — Medium · modular prefix earliest index
- P2 LC 974 — Subarray Sums Divisible by K — Medium · remainder frequency
- P2 LC 930 — Binary Subarrays With Sum — Medium · binary sum counting
- P2 LC 454 — 4Sum II — Medium · meet-in-the-middle sums
- P2 LC 287 — Find the Duplicate Number — Medium · Floyd cycle on indices
- P2 LC 442 — Find All Duplicates in an Array — Medium · sign marking
- P2 LC 229 — Majority Element II — Medium · Boyer-Moore candidates
- P2 LC 31 — Next Permutation — Medium · lexicographic successor
- P2 LC 189 — Rotate Array — Medium · reversal rotation
- P2 LC 289 — Game of Life — Medium · encoded simultaneous update
- P2 LC 304 — Range Sum Query 2D - Immutable — Medium · 2D prefix sums
- P2 LC 1423 — Maximum Points You Can Obtain from Cards — Medium · complement window
- P2 LC 1031 — Maximum Sum of Two Non-Overlapping Subarrays — Medium · prefix/suffix best windows
- P3 LC 41 — First Missing Positive — Hard · cyclic placement
- P3 LC 1074 — Number of Submatrices That Sum to Target — Hard · compress rows + prefix counts
2. Two pointers and sliding windows — 23
- P1 LC 167 — Two Sum II - Input Array Is Sorted — Medium · sorted inward pointers
- P1 LC 11 — Container With Most Water — Medium · discard dominated boundary
- P1 LC 15 — 3Sum — Medium · sort + duplicate suppression
- P1 LC 3 — Longest Substring Without Repeating Characters — Medium · unique-window invariant
- P1 LC 209 — Minimum Size Subarray Sum — Medium · positive-sum window
- P1 LC 424 — Longest Repeating Character Replacement — Medium · replacement budget
- P1 LC 567 — Permutation in String — Medium · fixed-window counts
- P1 LC 5 — Longest Palindromic Substring — Medium · expand around center
- P1 LC 76 — Minimum Window Substring — Hard · minimum covering window
- P1 LC 42 — Trapping Rain Water — Hard · boundary maxima
- P2 LC 713 — Subarray Product Less Than K — Medium · multiplicative positive window
- P2 LC 1004 — Max Consecutive Ones III — Medium · zero budget
- P2 LC 1658 — Minimum Operations to Reduce X to Zero — Medium · longest retained sum
- P2 LC 1838 — Frequency of the Most Frequent Element — Medium · sorted cost window
- P2 LC 986 — Interval List Intersections — Medium · merge two interval streams
- P2 LC 881 — Boats to Save People — Medium · pair lightest with heaviest
- P2 LC 340 — Longest Substring with At Most K Distinct Characters — Medium · Premium · at-most-K distinct
- P2 LC 142 — Linked List Cycle II — Medium · fast/slow cycle entry
- P3 LC 30 — Substring with Concatenation of All Words — Hard · word-aligned windows
- P3 LC 992 — Subarrays with K Different Integers — Hard · exactly K via two at-most counts
- P3 LC 862 — Shortest Subarray with Sum at Least K — Hard · prefix + monotonic deque
- P3 LC 1438 — Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit — Medium · dual monotonic deques
- P3 LC 239 — Sliding Window Maximum — Hard · deque maxima
3. Strings, parsing and stacks — 19
- P1 LC 155 — Min Stack — Medium · minimum augmentation
- P1 LC 150 — Evaluate Reverse Polish Notation — Medium · postfix evaluation
- P1 LC 394 — Decode String — Medium · nested frames
- P1 LC 1249 — Minimum Remove to Make Valid Parentheses — Medium · parenthesis balance
- P1 LC 71 — Simplify Path — Medium · path normalization
- P1 LC 227 — Basic Calculator II — Medium · precedence without parentheses
- P1 LC 151 — Reverse Words in a String — Medium · tokenize + reverse words
- P2 LC 735 — Asteroid Collision — Medium · collision stack
- P2 LC 1209 — Remove All Adjacent Duplicates in String II — Medium · run-count stack
- P2 LC 678 — Valid Parenthesis String — Medium · balance interval
- P2 LC 636 — Exclusive Time of Functions — Medium · exclusive-time frames
- P2 LC 8 — String to Integer (atoi) — Medium · bounded numeric parsing
- P2 LC 12 — Integer to Roman — Medium · greedy numeral tokens
- P2 LC 43 — Multiply Strings — Medium · digit multiplication
- P2 LC 856 — Score of Parentheses — Medium · parenthesis scoring
- P2 LC 224 — Basic Calculator — Hard · expression sign stack
- P3 LC 772 — Basic Calculator III — Hard · Premium · full precedence parser
- P3 LC 68 — Text Justification — Hard · line packing and spacing
- P3 LC 32 — Longest Valid Parentheses — Hard · valid-parenthesis state
4. Monotonic stacks and ordered sequences — 11
- P1 LC 739 — Daily Temperatures — Medium · next greater with indices
- P1 LC 503 — Next Greater Element II — Medium · circular next greater
- P1 LC 901 — Online Stock Span — Medium · compressed spans
- P1 LC 402 — Remove K Digits — Medium · greedy monotonic deletion
- P2 LC 316 — Remove Duplicate Letters — Medium · lexicographic stack + last occurrence
- P2 LC 1762 — Buildings With an Ocean View — Medium · Premium · right-to-left maximum
- P3 LC 84 — Largest Rectangle in Histogram — Hard · histogram contribution boundary
- P3 LC 85 — Maximal Rectangle — Hard · row histograms
- P3 LC 907 — Sum of Subarray Minimums — Medium · minimum contribution counts
- P3 LC 2104 — Sum of Subarray Ranges — Medium · min/max contribution difference
- P3 LC 895 — Maximum Frequency Stack — Hard · frequency buckets + recency
5. Binary search and answer-space search — 20
- P1 LC 34 — Find First and Last Position of Element in Sorted Array — Medium · lower/upper bounds
- P1 LC 33 — Search in Rotated Sorted Array — Medium · identify sorted half
- P1 LC 153 — Find Minimum in Rotated Sorted Array — Medium · rotated minimum
- P1 LC 162 — Find Peak Element — Medium · slope direction
- P1 LC 74 — Search a 2D Matrix — Medium · flattened ordered matrix
- P1 LC 875 — Koko Eating Bananas — Medium · monotone feasibility
- P1 LC 1011 — Capacity To Ship Packages Within D Days — Medium · capacity feasibility
- P1 LC 528 — Random Pick with Weight — Medium · prefix weighted sampling
- P2 LC 240 — Search a 2D Matrix II — Medium · staircase elimination
- P2 LC 540 — Single Element in a Sorted Array — Medium · pair-index parity
- P2 LC 378 — Kth Smallest Element in a Sorted Matrix — Medium · value count in sorted matrix
- P2 LC 1552 — Magnetic Force Between Two Balls — Medium · greedy placement feasibility
- P2 LC 1482 — Minimum Number of Days to Make m Bouquets — Medium · consecutive-bouquet feasibility
- P2 LC 1891 — Cutting Ribbons — Medium · Premium · piece count feasibility
- P2 LC 1060 — Missing Element in Sorted Array — Medium · Premium · missing-count inversion
- P2 LC 1095 — Find in Mountain Array — Hard · peak + two ordered searches
- P2 LC 981 — Time Based Key-Value Store — Medium · timestamp floor search
- P3 LC 410 — Split Array Largest Sum — Hard · minimize maximum partition sum
- P3 LC 4 — Median of Two Sorted Arrays — Hard · partition two sorted arrays
- P3 LC 719 — Find K-th Smallest Pair Distance — Hard · distance count + window
6. Linked lists — 11
- P1 LC 2 — Add Two Numbers — Medium · carry and dummy head
- P1 LC 19 — Remove Nth Node From End of List — Medium · fixed pointer gap
- P1 LC 92 — Reverse Linked List II — Medium · sublist reversal
- P1 LC 143 — Reorder List — Medium · split + reverse + weave
- P1 LC 138 — Copy List with Random Pointer — Medium · clone with identity map
- P2 LC 82 — Remove Duplicates from Sorted List II — Medium · remove duplicate runs
- P2 LC 86 — Partition List — Medium · stable two-list partition
- P2 LC 148 — Sort List — Medium · merge sort list
- P2 LC 430 — Flatten a Multilevel Doubly Linked List — Medium · flatten with saved continuation
- P3 LC 25 — Reverse Nodes in k-Group — Hard · reverse complete K-blocks
- P3 LC 1171 — Remove Zero Sum Consecutive Nodes from Linked List — Medium · prefix sums on nodes
7. Trees and BSTs — 32
- P1 LC 102 — Binary Tree Level Order Traversal — Medium · level BFS
- P1 LC 199 — Binary Tree Right Side View — Medium · last node per level
- P1 LC 98 — Validate Binary Search Tree — Medium · inherited BST bounds
- P1 LC 230 — Kth Smallest Element in a BST — Medium · inorder rank
- P1 LC 236 — Lowest Common Ancestor of a Binary Tree — Medium · subtree LCA return
- P1 LC 105 — Construct Binary Tree from Preorder and Inorder Traversal — Medium · traversal partition
- P1 LC 113 — Path Sum II — Medium · path backtracking
- P1 LC 129 — Sum Root to Leaf Numbers — Medium · path accumulator
- P1 LC 114 — Flatten Binary Tree to Linked List — Medium · flatten postorder
- P1 LC 173 — Binary Search Tree Iterator — Medium · lazy inorder iterator
- P2 LC 103 — Binary Tree Zigzag Level Order Traversal — Medium · level presentation
- P2 LC 235 — Lowest Common Ancestor of a Binary Search Tree — Medium · BST-directed LCA
- P2 LC 314 — Binary Tree Vertical Order Traversal — Medium · Premium · column BFS order
- P2 LC 545 — Boundary of Binary Tree — Medium · Premium · boundary deduplication
- P2 LC 863 — All Nodes Distance K in Binary Tree — Medium · parent links + distance BFS
- P2 LC 437 — Path Sum III — Medium · path prefix sums
- P2 LC 337 — House Robber III — Medium · take/skip tree DP
- P2 LC 450 — Delete Node in a BST — Medium · BST successor deletion
- P2 LC 652 — Find Duplicate Subtrees — Medium · subtree structural IDs
- P2 LC 662 — Maximum Width of Binary Tree — Medium · normalized positional indices
- P2 LC 1110 — Delete Nodes And Return Forest — Medium · delete and create roots
- P2 LC 951 — Flip Equivalent Binary Trees — Medium · unordered child equivalence
- P2 LC 1650 — Lowest Common Ancestor of a Binary Tree III — Medium · Premium · parent-chain intersection
- P2 LC 333 — Largest BST Subtree — Medium · Premium · valid-BST subtree summaries
- P2 LC 285 — Inorder Successor in BST — Medium · Premium · inorder successor
- P2 LC 366 — Find Leaves of Binary Tree — Medium · Premium · height buckets
- P3 LC 124 — Binary Tree Maximum Path Sum — Hard · best downward gain vs global path
- P3 LC 297 — Serialize and Deserialize Binary Tree — Hard · unambiguous tree serialization
- P3 LC 987 — Vertical Order Traversal of a Binary Tree — Hard · column/row/value ordering
- P3 LC 426 — Convert Binary Search Tree to Sorted Doubly Linked List — Medium · Premium · inorder pointer linking
- P3 LC 428 — Serialize and Deserialize N-ary Tree — Hard · Premium · N-ary arity encoding
- P3 LC 968 — Binary Tree Cameras — Hard · three-state camera DP
8. Heaps, selection and scheduling — 17
- P1 LC 215 — Kth Largest Element in an Array — Medium · randomized quickselect / bounded heap
- P1 LC 347 — Top K Frequent Elements — Medium · frequency selection
- P1 LC 973 — K Closest Points to Origin — Medium · distance selection
- P1 LC 23 — Merge k Sorted Lists — Hard · K-way merge
- P1 LC 295 — Find Median from Data Stream — Hard · two-heap partition
- P1 LC 621 — Task Scheduler — Medium · cooldown scheduling
- P2 LC 692 — Top K Frequent Words — Medium · frequency with lexicographic tie
- P2 LC 767 — Reorganize String — Medium · avoid adjacent repeats
- P2 LC 373 — Find K Pairs with Smallest Sums — Medium · best-first pair frontier
- P2 LC 1642 — Furthest Building You Can Reach — Medium · reserve ladders for largest climbs
- P2 LC 1834 — Single-Threaded CPU — Medium · time simulation + heap
- P2 LC 355 — Design Twitter — Medium · merge user feeds
- P3 LC 871 — Minimum Number of Refueling Stops — Hard · retroactive refueling
- P3 LC 2402 — Meeting Rooms III — Hard · busy/free resource heaps
- P3 LC 502 — IPO — Hard · feasible-project frontier
- P3 LC 480 — Sliding Window Median — Hard · two heaps + lazy deletion
- P3 LC 632 — Smallest Range Covering Elements from K Lists — Hard · smallest range across K lists
9. Intervals, sweep lines and greedy proofs — 26
- P1 LC 56 — Merge Intervals — Medium · sort and merge
- P1 LC 57 — Insert Interval — Medium · three-phase insertion
- P1 LC 253 — Meeting Rooms II — Medium · Premium · overlap count / end heap
- P1 LC 435 — Non-overlapping Intervals — Medium · earliest-finish exchange
- P1 LC 452 — Minimum Number of Arrows to Burst Balloons — Medium · interval stabbing
- P1 LC 55 — Jump Game — Medium · farthest reachable frontier
- P1 LC 45 — Jump Game II — Medium · layered reachability
- P1 LC 763 — Partition Labels — Medium · last-occurrence partition
- P2 LC 729 — My Calendar I — Medium · ordered non-overlap
- P2 LC 731 — My Calendar II — Medium · double-booking intersections
- P2 LC 1094 — Car Pooling — Medium · difference events
- P2 LC 759 — Employee Free Time — Hard · Premium · K-way calendar merge
- P2 LC 134 — Gas Station — Medium · prefix deficit reset
- P2 LC 406 — Queue Reconstruction by Height — Medium · height-order insertion
- P2 LC 846 — Hand of Straights — Medium · consume consecutive runs
- P2 LC 1024 — Video Stitching — Medium · greedy coverage
- P2 LC 1405 — Longest Happy String — Medium · largest feasible next character
- P2 LC 1647 — Minimum Deletions to Make Character Frequencies Unique — Medium · unique frequency allocation
- P2 LC 1653 — Minimum Deletions to Make String Balanced — Medium · prefix deletions state
- P2 LC 646 — Maximum Length of Pair Chain — Medium · interval chain
- P3 LC 732 — My Calendar III — Hard · maximum active bookings
- P3 LC 715 — Range Module — Hard · maintain disjoint ranges
- P3 LC 218 — The Skyline Problem — Hard · active skyline heights
- P3 LC 1851 — Minimum Interval to Include Each Query — Hard · offline queries + eligible heap
- P3 LC 135 — Candy — Hard · two-direction constraints
- P3 LC 1326 — Minimum Number of Taps to Open to Water a Garden — Hard · interval coverage frontier
10. Backtracking and constraint search — 22
- P1 LC 78 — Subsets — Medium · include/exclude subsets
- P1 LC 46 — Permutations — Medium · used-element permutations
- P1 LC 39 — Combination Sum — Medium · unbounded combination choices
- P1 LC 22 — Generate Parentheses — Medium · prefix-valid parentheses
- P1 LC 17 — Letter Combinations of a Phone Number — Medium · Cartesian choices
- P1 LC 79 — Word Search — Medium · grid visited-state restoration
- P1 LC 131 — Palindrome Partitioning — Medium · palindrome cut enumeration
- P2 LC 90 — Subsets II — Medium · duplicate subset pruning
- P2 LC 47 — Permutations II — Medium · duplicate permutation pruning
- P2 LC 40 — Combination Sum II — Medium · single-use duplicate pruning
- P2 LC 77 — Combinations — Medium · combination start index
- P2 LC 216 — Combination Sum III — Medium · fixed-cardinality sum pruning
- P2 LC 93 — Restore IP Addresses — Medium · IP segment validation
- P2 LC 473 — Matchsticks to Square — Medium · symmetric bucket pruning
- P2 LC 698 — Partition to K Equal Sum Subsets — Medium · equal-sum bucket assignment
- P2 LC 526 — Beautiful Arrangement — Medium · position divisibility constraints
- P3 LC 51 — N-Queens — Hard · column/diagonal constraints
- P3 LC 37 — Sudoku Solver — Hard · Sudoku constraint propagation
- P3 LC 301 — Remove Invalid Parentheses — Hard · minimal invalid-parenthesis removal
- P3 LC 291 — Word Pattern II — Medium · Premium · bijective substring mapping
- P3 LC 489 — Robot Room Cleaner — Hard · Premium · physical robot backtracking
- P3 LC 126 — Word Ladder II — Hard · shortest-path DAG enumeration
11. Tries and prefix matching — 10
- P1 LC 208 — Implement Trie (Prefix Tree) — Medium · prefix-tree operations
- P1 LC 211 — Design Add and Search Words Data Structure — Medium · wildcard trie DFS
- P1 LC 1268 — Search Suggestions System — Medium · sorted prefix range / trie
- P2 LC 648 — Replace Words — Medium · shortest root match
- P2 LC 676 — Implement Magic Dictionary — Medium · one-edit dictionary search
- P2 LC 421 — Maximum XOR of Two Numbers in an Array — Medium · bitwise greedy trie
- P3 LC 212 — Word Search II — Hard · trie-guided grid pruning
- P3 LC 472 — Concatenated Words — Hard · word segmentation + dictionary
- P3 LC 1032 — Stream of Characters — Hard · reverse trie stream suffix
- P3 LC 642 — Design Search Autocomplete System — Hard · Premium · prefix ranked suggestions
12. Graph traversal, topology and connectivity — 35
- P1 LC 200 — Number of Islands — Medium · component flood fill
- P1 LC 133 — Clone Graph — Medium · identity-preserving clone
- P1 LC 130 — Surrounded Regions — Medium · boundary reachability
- P1 LC 994 — Rotting Oranges — Medium · multi-source BFS
- P1 LC 542 — 01 Matrix — Medium · nearest-source distances
- P1 LC 207 — Course Schedule — Medium · cycle detection / indegrees
- P1 LC 210 — Course Schedule II — Medium · topological order
- P1 LC 417 — Pacific Atlantic Water Flow — Medium · reverse-flow reachability
- P1 LC 721 — Accounts Merge — Medium · DSU identity merging
- P1 LC 684 — Redundant Connection — Medium · cycle edge with DSU
- P1 LC 785 — Is Graph Bipartite? — Medium · two-color invariant
- P2 LC 695 — Max Area of Island — Medium · component area
- P2 LC 261 — Graph Valid Tree — Medium · Premium · tree connectivity + edge count
- P2 LC 323 — Number of Connected Components in an Undirected Graph — Medium · Premium · component counting
- P2 LC 547 — Number of Provinces — Medium · adjacency-matrix connectivity
- P2 LC 399 — Evaluate Division — Medium · weighted graph ratios
- P2 LC 752 — Open the Lock — Medium · implicit-state BFS
- P2 LC 1091 — Shortest Path in Binary Matrix — Medium · eight-neighbor shortest path
- P2 LC 490 — The Maze — Medium · Premium · rolling-stop graph
- P2 LC 802 — Find Eventual Safe States — Medium · reverse topology
- P2 LC 310 — Minimum Height Trees — Medium · leaf peeling
- P2 LC 694 — Number of Distinct Islands — Medium · Premium · shape normalization
- P2 LC 1376 — Time Needed to Inform All Employees — Medium · rooted propagation
- P2 LC 1319 — Number of Operations to Make Network Connected — Medium · spare-edge connectivity
- P2 LC 1162 — As Far from Land as Possible — Medium · multi-source maximum distance
- P2 LC 1254 — Number of Closed Islands — Medium · boundary-connected exclusion
- P2 LC 1905 — Count Sub Islands — Medium · component containment
- P2 LC 737 — Sentence Similarity II — Medium · Premium · transitive synonym DSU
- P2 LC 444 — Sequence Reconstruction — Medium · Premium · unique topological order
- P3 LC 827 — Making A Large Island — Hard · label islands + deduplicate neighboring roots
- P3 LC 305 — Number of Islands II — Hard · Premium · incremental DSU
- P3 LC 269 — Alien Dictionary — Hard · Premium · lexicographic constraints + prefix invalidity
- P3 LC 815 — Bus Routes — Hard · route-stop bipartite BFS
- P3 LC 1293 — Shortest Path in a Grid with Obstacles Elimination — Hard · state BFS + dominance
- P3 LC 1192 — Critical Connections in a Network — Hard · low-link bridges
13. Weighted graphs and advanced state search — 19
- P1 LC 743 — Network Delay Time — Medium · Dijkstra relaxation
- P1 LC 127 — Word Ladder — Hard · word-neighbor BFS
- P2 LC 787 — Cheapest Flights Within K Stops — Medium · edge-budget Bellman-Ford / layered state
- P2 LC 1631 — Path With Minimum Effort — Medium · minimax Dijkstra
- P2 LC 1584 — Min Cost to Connect All Points — Medium · minimum spanning tree
- P2 LC 1514 — Path with Maximum Probability — Medium · max-product Dijkstra
- P2 LC 1135 — Connecting Cities With Minimum Cost — Medium · Premium · Kruskal edge ordering
- P2 LC 1129 — Shortest Path with Alternating Colors — Medium · color-augmented BFS
- P2 LC 1136 — Parallel Courses — Medium · Premium · topological semesters
- P2 LC 505 — The Maze II — Medium · Premium · weighted rolling distances
- P3 LC 778 — Swim in Rising Water — Hard · minimax elevation search
- P3 LC 332 — Reconstruct Itinerary — Hard · Eulerian trail
- P3 LC 2290 — Minimum Obstacle Removal to Reach Corner — Hard · 0-1 BFS
- P3 LC 1368 — Minimum Cost to Make at Least One Valid Path in a Grid — Hard · 0-1 direction cost
- P3 LC 847 — Shortest Path Visiting All Nodes — Hard · visited-subset BFS
- P3 LC 864 — Shortest Path to Get All Keys — Hard · key-mask BFS
- P3 LC 2092 — Find All People With Secret — Hard · time-batched connectivity
- P3 LC 1976 — Number of Ways to Arrive at Destination — Medium · shortest-path counting
- P3 LC 1203 — Sort Items by Groups Respecting Dependencies — Hard · two-level topological sorting
14. Dynamic programming: state, choices and knapsack — 43
- P1 LC 198 — House Robber — Medium · take/skip recurrence
- P1 LC 213 — House Robber II — Medium · circular decomposition
- P1 LC 91 — Decode Ways — Medium · valid one/two-digit transitions
- P1 LC 322 — Coin Change — Medium · min-count unbounded knapsack
- P1 LC 139 — Word Break — Medium · prefix segmentation
- P1 LC 300 — Longest Increasing Subsequence — Medium · LIS state / patience sorting
- P1 LC 416 — Partition Equal Subset Sum — Medium · 0/1 subset feasibility
- P1 LC 518 — Coin Change II — Medium · unbounded combination counts
- P1 LC 62 — Unique Paths — Medium · grid path recurrence
- P1 LC 64 — Minimum Path Sum — Medium · grid minimum cost
- P1 LC 1143 — Longest Common Subsequence — Medium · two-prefix subsequences
- P2 LC 279 — Perfect Squares — Medium · min-square decomposition
- P2 LC 377 — Combination Sum IV — Medium · ordered composition counts
- P2 LC 494 — Target Sum — Medium · sum-state / subset transform
- P2 LC 740 — Delete and Earn — Medium · aggregate values then take/skip
- P2 LC 983 — Minimum Cost For Tickets — Medium · ticket-end transitions
- P2 LC 1043 — Partition Array for Maximum Sum — Medium · last partition choice
- P2 LC 1048 — Longest String Chain — Medium · predecessor word chains
- P2 LC 368 — Largest Divisible Subset — Medium · divisibility DAG
- P2 LC 343 — Integer Break — Medium · split integer products
- P2 LC 474 — Ones and Zeroes — Medium · two-resource 0/1 knapsack
- P2 LC 63 — Unique Paths II — Medium · obstacle-state initialization
- P2 LC 120 — Triangle — Medium · triangle rolling state
- P2 LC 221 — Maximal Square — Medium · largest ending square
- P2 LC 931 — Minimum Falling Path Sum — Medium · three-predecessor minimum
- P2 LC 256 — Paint House — Medium · Premium · color-exclusion state
- P2 LC 309 — Best Time to Buy and Sell Stock with Cooldown — Medium · hold/sold/rest machine
- P2 LC 714 — Best Time to Buy and Sell Stock with Transaction Fee — Medium · stock state with fee
- P2 LC 97 — Interleaving String — Medium · two-source prefix interleaving
- P2 LC 647 — Palindromic Substrings — Medium · center expansion / palindrome DP
- P2 LC 516 — Longest Palindromic Subsequence — Medium · interval subsequence
- P2 LC 718 — Maximum Length of Repeated Subarray — Medium · common suffix lengths
- P2 LC 926 — Flip String to Monotone Increasing — Medium · monotone-string state
- P3 LC 123 — Best Time to Buy and Sell Stock III — Hard · two-transaction states
- P3 LC 188 — Best Time to Buy and Sell Stock IV — Hard · K-transaction states
- P3 LC 265 — Paint House II — Hard · Premium · best two previous colors
- P3 LC 115 — Distinct Subsequences — Hard · count distinct subsequences
- P3 LC 72 — Edit Distance — Medium · edit operations on prefixes
- P3 LC 174 — Dungeon Game — Hard · reverse required-health DP
- P3 LC 354 — Russian Doll Envelopes — Hard · sort ties + LIS
- P3 LC 1235 — Maximum Profit in Job Scheduling — Hard · weighted intervals + predecessor search
- P3 LC 140 — Word Break II — Hard · enumerate memoized sentence suffixes
- P3 LC 403 — Frog Jump — Hard · position/jump state
15. Dynamic programming: advanced composition — 16
- P2 LC 712 — Minimum ASCII Delete Sum for Two Strings — Medium · weighted prefix deletion
- P2 LC 583 — Delete Operation for Two Strings — Medium · LCS deletion reduction
- P2 LC 1140 — Stone Game II — Medium · game state and score difference
- P2 LC 1626 — Best Team With No Conflicts — Medium · sorted compatible subsequence
- P3 LC 312 — Burst Balloons — Hard · choose last balloon
- P3 LC 329 — Longest Increasing Path in a Matrix — Hard · memoized increasing DAG
- P3 LC 132 — Palindrome Partitioning II — Hard · palindrome minimum cuts
- P3 LC 10 — Regular Expression Matching — Hard · regex prefix transitions
- P3 LC 44 — Wildcard Matching — Hard · wildcard prefix transitions
- P3 LC 639 — Decode Ways II — Hard · weighted decoding cases
- P3 LC 1335 — Minimum Difficulty of a Job Schedule — Hard · day-boundary partition
- P3 LC 1216 — Valid Palindrome III — Hard · Premium · deletion budget / LPS
- P3 LC 1463 — Cherry Pickup II — Hard · two-agent row state
- P3 LC 1444 — Number of Ways of Cutting a Pizza — Hard · remaining cuts + suffix counts
- P3 LC 1039 — Minimum Score Triangulation of Polygon — Medium · last triangle partition
- P3 LC 887 — Super Egg Drop — Hard · coverage by moves/eggs
16. Design, range structures, math and bit invariants — 29
- P1 LC 146 — LRU Cache — Medium · hash map + doubly linked recency
- P1 LC 362 — Design Hit Counter — Medium · Premium · timestamp count window
- P1 LC 50 — Pow(x, n) — Medium · binary exponentiation
- P2 LC 1146 — Snapshot Array — Medium · per-index change history
- P2 LC 622 — Design Circular Queue — Medium · circular-buffer invariants
- P2 LC 1472 — Design Browser History — Medium · history cursor truncation
- P2 LC 348 — Design Tic-Tac-Toe — Medium · Premium · row/column counters
- P2 LC 1166 — Design File System — Medium · Premium · parent-path existence
- P2 LC 1570 — Dot Product of Two Sparse Vectors — Medium · Premium · sparse intersection
- P2 LC 341 — Flatten Nested List Iterator — Medium · lazy nested iterator
- P2 LC 307 — Range Sum Query - Mutable — Medium · Fenwick point-update prefix query
- P2 LC 2115 — Find All Possible Recipes from Given Supplies — Medium · dependency availability propagation
- P2 LC 7 — Reverse Integer — Medium · overflow-aware digit reversal
- P2 LC 29 — Divide Two Integers — Medium · binary long division
- P2 LC 260 — Single Number III — Medium · XOR partition
- P2 LC 204 — Count Primes — Medium · sieve
- P2 LC 223 — Rectangle Area — Medium · rectangle overlap
- P2 LC 593 — Valid Square — Medium · squared-distance geometry
- P2 LC 277 — Find the Celebrity — Medium · Premium · eliminate then verify candidate
- P2 LC 384 — Shuffle an Array — Medium · Fisher-Yates uniformity
- P2 LC 398 — Random Pick Index — Medium · reservoir sampling
- P3 LC 460 — LFU Cache — Hard · frequency + recency eviction
- P3 LC 432 — All O`one Data Structure — Hard · frequency bucket linked list
- P3 LC 2034 — Stock Price Fluctuation — Medium · latest value + lazy price heaps
- P3 LC 716 — Max Stack — Hard · Premium · stack and maximum removal
- P3 LC 315 — Count of Smaller Numbers After Self — Hard · merge-count / Fenwick compression
- P3 LC 327 — Count of Range Sum — Hard · prefix-pair range counting
- P3 LC 149 — Max Points on a Line — Hard · normalized rational slopes
- P3 LC 381 — Insert Delete GetRandom O(1) - Duplicates allowed — Hard · duplicate-aware index sets
Python coding patterns
Prefix sums + frequency map
Use for counting subarrays with a target sum (LC 560). Count earlier prefixes before inserting the current one. O(n) time and O(n) space.
def subarray_sum(nums, k):
frequency = {0: 1}
prefix = answer = 0
for value in nums:
prefix += value
answer += frequency.get(prefix - k, 0)
frequency[prefix] = frequency.get(prefix, 0) + 1
return answerSliding window
Use for a longest substring with no repeated characters (LC 3). Move the left boundary past the previous occurrence. O(n) time and O(u) space for u distinct characters.
def longest_unique_substring(s):
last_seen = {}
left = answer = 0
for right, char in enumerate(s):
left = max(left, last_seen.get(char, -1) + 1)
last_seen[char] = right
answer = max(answer, right - left + 1)
return answerBinary search: lower bound
Find the first index whose value is at least target in a sorted array (a building block for LC 34). Return len(nums) if no such index exists. Keep the search interval [left, right). O(log n) time and O(1) space.
def lower_bound(nums, target):
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return leftBFS: shortest unweighted path
Use for graphs with equal-cost edges. Mark nodes when enqueuing so each node enters the queue once. graph[node] contains its neighbors. O(V + E) time and O(V) space.
from collections import deque
def shortest_distance(graph, start, target):
queue = deque([(start, 0)])
seen = {start}
while queue:
node, distance = queue.popleft()
if node == target:
return distance
for neighbor in graph.get(node, []):
if neighbor not in seen:
seen.add(neighbor)
queue.append((neighbor, distance + 1))
return -1Dynamic programming: take or skip
Use for non-adjacent selection (LC 198). Track the best total before the previous house and through the previous house. For nonnegative house values: O(n) time and O(1) space.
def house_robber(nums):
previous_two = previous_one = 0
for value in nums:
previous_two, previous_one = (
previous_one,
max(previous_one, previous_two + value),
)
return previous_one