LeetCode Master 150: Ordered LeetCode Study Plan by Topic with Python Solutions
A free, ordered LeetCode study plan of 150 problems grouped into 17 topics, from arrays and hashing to dynamic programming and graphs. Every problem has a tested Python solution and a one-line key insight so you learn the pattern, not just the answer. It is built for people preparing for coding interviews (FAANG and everyone else) who want a clear order to follow instead of a random problem list.
Last reviewed: December 2026
Table of Contents
- How to use this plan
- Suggested schedules
- The study loop for one problem
- Pattern recognition cheat sheet
- The 150 problems
- Stage 1: Arrays and Hashing
- Stage 2: Two Pointers
- Stage 3: Sliding Window
- Stage 4: Prefix Sums
- Stage 5: Stack and Monotonic Stack
- Stage 6: Binary Search
- Stage 7: Linked List
- Stage 8: Trees
- Stage 9: Heap / Priority Queue
- Stage 10: Backtracking
- Stage 11: Tries
- Stage 12: Graphs
- Stage 13: Advanced Graphs
- Stage 14: 1-D Dynamic Programming
- Stage 15: 2-D Dynamic Programming
- Stage 16: Greedy and Intervals
- Stage 17: Bit Manipulation and Math
- Python interview toolkit
- Complexity cheat sheet
- Running the solutions and tests
- How this plan compares to other popular lists
- Mistakes that cost people offers
- FAQ
- Where to go next
- Contributing
- More free resources
How to use this plan
- Go in order. Each stage reuses ideas from the stages before it. Sliding window builds on two pointers; graphs build on trees; 2-D DP builds on 1-D DP.
- Try each problem for 20-40 minutes before reading the solution. If you are stuck, read only the key insight in the table, then try again.
- Write the solution yourself, then compare with the file in
solutions/. The code is short on purpose so the idea is visible. - Track what you got wrong, not what you solved. Mark a problem “redo” if you needed the insight. Redo those after 3 days and after 2 weeks.
- Say the complexity out loud for every solution. Interviewers ask, and it forces you to understand the loop structure.
The difficulty column uses LeetCode’s labels: E (Easy), M (Medium), H (Hard). The split is 29 Easy, 103 Medium and 18 Hard, which matches how heavily real interviews lean on Medium problems.
Suggested schedules
| Plan | Pace | Good for |
|---|---|---|
| 4 weeks | ~5-6 problems a day | You already know the patterns and want a refresher |
| 8 weeks | ~3 problems a day | Most people with a full-time job |
| 12 weeks | ~2 problems a day plus weekly review | First serious interview prep |
An 8-week split that keeps related topics together:
| Week | Stages | Problems |
|---|---|---|
| 1 | Arrays and Hashing, Two Pointers | 1-20 |
| 2 | Sliding Window, Prefix Sums, Stack | 21-43 |
| 3 | Binary Search, Linked List | 44-64 |
| 4 | Trees | 65-80 |
| 5 | Heap, Backtracking, Tries | 81-100 |
| 6 | Graphs, Advanced Graphs | 101-118 |
| 7 | 1-D DP, 2-D DP | 119-139 |
| 8 | Greedy, Intervals, Bit Manipulation, full review | 140-150 + redo list |
Use the last two days of every week to redo problems you marked, without looking at the code.
The study loop for one problem
A repeatable loop works better than willpower:
- Read and restate. Write the input, output and constraints in one sentence. Constraints tell you the target complexity:
n <= 10^5means O(n log n) or better;n <= 20hints at exponential search or bitmasks;n <= 500allows O(n^2) or O(n^3) DP. - Work two small examples by hand, including an edge case (empty input, one element, all duplicates, negative numbers).
- Name the pattern using the cheat sheet below. If two patterns fit, pick the simpler one first.
- Write a brute force in your head and state its complexity. The optimal solution usually removes a repeated piece of work from it.
- Code it, then trace one example through the code line by line.
- Test edge cases before you submit.
- Write the key insight in one line in your own notes. If you cannot, you have not learned the pattern yet.
Pattern recognition cheat sheet
| If the problem says… | Think about | Example in this plan |
|---|---|---|
| “find a pair / complement / seen before” | Hash map | #1 Two Sum |
| “sorted array” + pair or triplet | Two pointers | #14, #15 |
| “longest / shortest contiguous substring or subarray” | Sliding window | #22, #25 |
| “sum of a subarray equals k”, negatives allowed | Prefix sum + hash map | #30 |
| “next greater / smaller element”, “span”, “histogram” | Monotonic stack | #38, #40 |
| “sorted” or “minimum value that works” | Binary search (on index or on the answer) | #46, #53 |
| “k largest / smallest / closest”, “stream” | Heap | #81, #87 |
| “all combinations / permutations / subsets” | Backtracking | #88-#97 |
| “prefix”, “dictionary of words” | Trie | #98-#100 |
| “grid”, “islands”, “connected” | BFS / DFS flood fill | #101, #102 |
| “shortest path, unweighted” | BFS | #110 |
| “shortest path, weighted, non-negative” | Dijkstra | #113 |
| “dependencies”, “ordering”, “prerequisites” | Topological sort | #107, #108 |
| “connect / merge groups”, “redundant edge” | Union-find | #109 |
| “number of ways”, “min / max cost”, overlapping subproblems | Dynamic programming | Stages 14-15 |
| “intervals”, “meetings”, “schedule” | Sort by start or end, then sweep | #144-#146 |
| “appears once / twice”, “without extra space” | XOR or bit tricks | #148 |
The 150 problems
Each row links to the problem on LeetCode and to the Python file that contains the solution. Function names in the code match the problem titles in snake_case.
Stage 1: Arrays and Hashing
Code: solutions/arrays_hashing.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 1 | 1. Two Sum | E | Store value -> index; look up target - x before inserting x. |
| 2 | 217. Contains Duplicate | E | A set is smaller than the list only if something repeats. |
| 3 | 242. Valid Anagram | E | Equal character counts; a 26-slot array beats sorting. |
| 4 | 49. Group Anagrams | M | Use the count tuple (or sorted string) as the dictionary key. |
| 5 | 347. Top K Frequent Elements | M | Bucket by frequency (index = count) for O(n) instead of a heap. |
| 6 | 238. Product of Array Except Self | M | Answer = prefix product times suffix product, two passes, no division. |
| 7 | 36. Valid Sudoku | M | One seen-set keyed by row, column and box (r//3, c//3). |
| 8 | 128. Longest Consecutive Sequence | M | Only start counting at x when x - 1 is missing; total work stays O(n). |
| 9 | 169. Majority Element | E | Boyer-Moore voting: the majority survives pairwise cancellation. |
| 10 | 41. First Missing Positive | H | Use the array as its own hash table: put value v at index v - 1. |
| 11 | 380. Insert Delete GetRandom O(1) | M | List + index map; delete by swapping with the last element. |
| 12 | 205. Isomorphic Strings | E | The mapping must be one-to-one, so check both directions. |
Stage 2: Two Pointers
Code: solutions/two_pointers.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 13 | 125. Valid Palindrome | E | Move inward from both ends, skipping non-alphanumeric characters. |
| 14 | 167. Two Sum II - Input Array Is Sorted | M | Sum too small: move left up. Too big: move right down. |
| 15 | 15. 3Sum | M | Sort, fix one number, run sorted two-sum on the rest, skip duplicates. |
| 16 | 11. Container With Most Water | M | Always move the shorter wall; the taller one cannot do better with less width. |
| 17 | 42. Trapping Rain Water | H | Water at i = min(maxLeft, maxRight) - height; process the side with the lower max. |
| 18 | 26. Remove Duplicates from Sorted Array | E | A slow write pointer marks the end of the unique prefix. |
| 19 | 283. Move Zeroes | E | Swap each non-zero into the next write slot; order is preserved. |
| 20 | 75. Sort Colors | M | Dutch national flag: three regions (0s, 1s, 2s) in one pass. |
Stage 3: Sliding Window
Code: solutions/sliding_window.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 21 | 121. Best Time to Buy and Sell Stock | E | Track the cheapest price so far; profit = today minus that. |
| 22 | 3. Longest Substring Without Repeating Characters | M | Store last index of each char; jump the left edge past a repeat. |
| 23 | 424. Longest Repeating Character Replacement | M | Window is valid while length - mostCommonCount <= k. |
| 24 | 567. Permutation in String | M | Fixed-size window; compare two 26-count arrays as it slides. |
| 25 | 76. Minimum Window Substring | H | Grow right until everything is covered, then shrink left while still covered. |
| 26 | 239. Sliding Window Maximum | H | Deque of indices with decreasing values; the front is the max. |
| 27 | 209. Minimum Size Subarray Sum | M | Positive numbers only, so shrinking from the left always lowers the sum. |
| 28 | 438. Find All Anagrams in a String | M | Same window as #24, but record every matching start. |
Stage 4: Prefix Sums
Code: solutions/prefix_sum.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 29 | 303. Range Sum Query - Immutable | E | prefix[r + 1] - prefix[l] answers any range in O(1). |
| 30 | 560. Subarray Sum Equals K | M | Count earlier prefixes equal to current - k; works with negatives where a window fails. |
| 31 | 724. Find Pivot Index | E | Left sum equals total minus left sum minus the pivot. |
| 32 | 304. Range Sum Query 2D - Immutable | M | 2-D prefix sums with inclusion-exclusion of four corners. |
| 33 | 523. Continuous Subarray Sum | M | Two equal prefix remainders mod k, at least 2 apart, mean a multiple of k. |
| 34 | 974. Subarray Sums Divisible by K | M | Count pairs of equal prefix remainders; normalise negative remainders. |
Stage 5: Stack and Monotonic Stack
Code: solutions/stack.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 35 | 20. Valid Parentheses | E | Push openers; each closer must match the top; stack must end empty. |
| 36 | 155. Min Stack | M | Store (value, min so far) pairs so the minimum survives pops. |
| 37 | 150. Evaluate Reverse Polish Notation | M | Pop two operands per operator; division truncates toward zero. |
| 38 | 739. Daily Temperatures | M | Stack holds days still waiting for a warmer one; pop when it arrives. |
| 39 | 853. Car Fleet | M | Sort by position descending; a car arriving no later than the fleet ahead joins it. |
| 40 | 84. Largest Rectangle in Histogram | H | Increasing stack; a popped bar’s width ends at the current index. |
| 41 | 496. Next Greater Element I | E | Precompute next greater for every value in nums2 with one stack pass. |
| 42 | 394. Decode String | M | On [ push (string so far, count); on ] pop and repeat. |
| 43 | 71. Simplify Path | M | Split on /; .. pops, . and empty parts are skipped. |
Stage 6: Binary Search
Code: solutions/binary_search.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 44 | 704. Binary Search | E | Closed interval [lo, hi], loop while lo <= hi. Pick one template and keep it. |
| 45 | 74. Search a 2D Matrix | M | Treat the matrix as one sorted array: index -> (i // cols, i % cols). |
| 46 | 875. Koko Eating Bananas | M | Binary search on the answer: the smallest speed whose hours fit. |
| 47 | 153. Find Minimum in Rotated Sorted Array | M | Compare mid with the right end to find which half holds the drop. |
| 48 | 33. Search in Rotated Sorted Array | M | One half around mid is always sorted; check if the target is inside it. |
| 49 | 981. Time Based Key-Value Store | M | Timestamps arrive sorted; bisect for the latest time <= query. |
| 50 | 4. Median of Two Sorted Arrays | H | Binary search a cut in the shorter array so both left halves hold half the items. |
| 51 | 34. Find First and Last Position of Element in Sorted Array | M | Two lower-bound searches: for target and for target + 1. |
| 52 | 162. Find Peak Element | M | If the right neighbour is higher, a peak exists on the right; walk uphill. |
| 53 | 1011. Capacity To Ship Packages Within D Days | M | Answer lies in [max(w), sum(w)]; greedy day count is monotonic. |
Stage 7: Linked List
Code: solutions/linked_list.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 54 | 206. Reverse Linked List | E | Three pointers: prev, current, next. Draw it once and you will never forget it. |
| 55 | 21. Merge Two Sorted Lists | E | A dummy head removes every empty-list special case. |
| 56 | 141. Linked List Cycle | E | Floyd: a fast pointer laps a slow one only if there is a cycle. |
| 57 | 143. Reorder List | M | Find the middle, reverse the second half, weave the halves. |
| 58 | 19. Remove Nth Node From End of List | M | Give the lead pointer an n-step head start. |
| 59 | 138. Copy List with Random Pointer | M | Map old node to new node first; wire next and random in a second pass. |
| 60 | 2. Add Two Numbers | M | Digits are reversed, so add like on paper and keep the carry. |
| 61 | 287. Find the Duplicate Number | M | i -> nums[i] forms a linked list; the duplicate is the cycle entrance. |
| 62 | 146. LRU Cache | M | Hash map + doubly linked list; in Python, OrderedDict provides both. |
| 63 | 23. Merge k Sorted Lists | H | Min-heap of list heads; add an index to break ties between equal values. |
| 64 | 25. Reverse Nodes in k-Group | H | Check that k nodes exist, reverse them, reconnect, repeat. |
Stage 8: Trees
Code: solutions/trees.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 65 | 226. Invert Binary Tree | E | Swap the children at every node. |
| 66 | 104. Maximum Depth of Binary Tree | E | Depth = 1 + the deeper child. The base case is the whole trick. |
| 67 | 543. Diameter of Binary Tree | E | Return height upward; update the answer with left + right height. |
| 68 | 110. Balanced Binary Tree | E | Return -1 as an “unbalanced” signal so each node is visited once. |
| 69 | 100. Same Tree | E | Same value and both pairs of subtrees the same. |
| 70 | 572. Subtree of Another Tree | E | Run Same Tree from every node of the big tree. |
| 71 | 235. Lowest Common Ancestor of a Binary Search Tree | M | Walk down until p and q fall on different sides. |
| 72 | 102. Binary Tree Level Order Traversal | M | BFS; process exactly len(queue) nodes per level. |
| 73 | 199. Binary Tree Right Side View | M | The last node of each BFS level. |
| 74 | 1448. Count Good Nodes in Binary Tree | M | Pass the max value on the path down to each child. |
| 75 | 98. Validate Binary Search Tree | M | Pass an allowed (low, high) range down; checking only children is wrong. |
| 76 | 230. Kth Smallest Element in a BST | M | In-order traversal of a BST is sorted; stop at the k-th visit. |
| 77 | 105. Construct Binary Tree from Preorder and Inorder Traversal | M | Preorder gives the root; its inorder position splits left from right. |
| 78 | 124. Binary Tree Maximum Path Sum | H | Return the best one-sided gain; update the answer with the two-sided path. |
| 79 | 297. Serialize and Deserialize Binary Tree | H | Preorder with a null marker is enough to rebuild the exact tree. |
| 80 | 236. Lowest Common Ancestor of a Binary Tree | M | If p and q come back from different subtrees, the current node is the answer. |
Stage 9: Heap / Priority Queue
Code: solutions/heap.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 81 | 703. Kth Largest Element in a Stream | E | Keep a min-heap of size k; its top is the k-th largest. |
| 82 | 1046. Last Stone Weight | E | Python’s heapq is a min-heap, so store negated values. |
| 83 | 973. K Closest Points to Origin | M | Compare squared distances; no square root needed. |
| 84 | 215. Kth Largest Element in an Array | M | Size-k min-heap is O(n log k); quickselect is O(n) on average. |
| 85 | 621. Task Scheduler | M | Frame by the most frequent task: (max - 1) * (n + 1) + countOfMax. |
| 86 | 355. Design Twitter | M | k-way merge of followees’ newest tweets with a heap; stop at 10. |
| 87 | 295. Find Median from Data Stream | H | Max-heap for the low half, min-heap for the high half, balanced sizes. |
Stage 10: Backtracking
Code: solutions/backtracking.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 88 | 78. Subsets | M | Record the path at every node of the recursion tree, not only at leaves. |
| 89 | 39. Combination Sum | M | Reuse allowed: recurse with the same start index. Sort to break early. |
| 90 | 46. Permutations | M | Track used elements; a full-length path is one permutation. |
| 91 | 90. Subsets II | M | Sort, then skip a value equal to its left neighbour at the same depth. |
| 92 | 40. Combination Sum II | M | Each number once (i + 1) plus the same-depth duplicate skip. |
| 93 | 79. Word Search | M | Mark a cell visited by overwriting it, restore it on the way back. |
| 94 | 131. Palindrome Partitioning | M | Cut off each palindromic prefix and recurse on the rest. |
| 95 | 17. Letter Combinations of a Phone Number | M | A Cartesian product; build it level by level. |
| 96 | 51. N-Queens | H | One queen per row; sets for columns, r - c and r + c diagonals. |
| 97 | 22. Generate Parentheses | M | Add ( while opens < n, add ) while closes < opens. |
Stage 11: Tries
Code: solutions/tries.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 98 | 208. Implement Trie (Prefix Tree) | M | Nested dicts with an end-of-word marker. |
| 99 | 211. Design Add and Search Words Data Structure | M | On ., branch into every child with DFS. |
| 100 | 212. Word Search II | H | Put all words in one trie and DFS the board once; prune found branches. |
Stage 12: Graphs
Code: solutions/graphs.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 101 | 200. Number of Islands | M | Each unvisited land cell starts a flood fill that sinks its island. |
| 102 | 695. Max Area of Island | M | Same flood fill, but count cells. |
| 103 | 133. Clone Graph | M | The old -> new map is also your visited set. |
| 104 | 994. Rotting Oranges | M | Multi-source BFS from every rotten orange; minutes = BFS layers. |
| 105 | 417. Pacific Atlantic Water Flow | M | Reverse the flow: climb uphill from each ocean, intersect the results. |
| 106 | 130. Surrounded Regions | M | Protect Os connected to the border; flip everything else. |
| 107 | 207. Course Schedule | M | Kahn’s algorithm: a cycle leaves nodes that never reach indegree 0. |
| 108 | 210. Course Schedule II | M | The order Kahn’s algorithm removes nodes is a valid order. |
| 109 | 684. Redundant Connection | M | Union-find: the first edge joining two already-connected nodes is the answer. |
| 110 | 127. Word Ladder | H | BFS over words; wildcard keys like h*t find neighbours fast. |
| 111 | 547. Number of Provinces | M | Count connected components of an adjacency matrix. |
| 112 | 785. Is Graph Bipartite? | M | Two-colour every component; an edge inside one colour fails. |
Stage 13: Advanced Graphs
Code: solutions/advanced_graphs.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 113 | 743. Network Delay Time | M | Dijkstra from the source; the answer is the largest shortest distance. |
| 114 | 1584. Min Cost to Connect All Points | M | Minimum spanning tree; on a dense graph O(n^2) Prim’s is simplest. |
| 115 | 778. Swim in Rising Water | H | Dijkstra where a path costs its maximum cell, not its sum. |
| 116 | 787. Cheapest Flights Within K Stops | M | Bellman-Ford for k + 1 rounds, copying the array so a round adds one edge. |
| 117 | 332. Reconstruct Itinerary | H | Hierholzer’s Eulerian path: post-order DFS on sorted edges, then reverse. |
| 118 | 1631. Path With Minimum Effort | M | Dijkstra with cost = the largest single step on the path. |
Stage 14: 1-D Dynamic Programming
Code: solutions/dp_1d.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 119 | 70. Climbing Stairs | E | ways(n) = ways(n-1) + ways(n-2); two variables are enough. |
| 120 | 746. Min Cost Climbing Stairs | E | Cost to stand on step i = its cost + the cheaper of the two below. |
| 121 | 198. House Robber | M | best(i) = max(best(i-1), best(i-2) + nums[i]). |
| 122 | 213. House Robber II | M | First and last cannot both be taken: solve two linear ranges. |
| 123 | 5. Longest Palindromic Substring | M | Expand around each of the 2n - 1 centres. |
| 124 | 647. Palindromic Substrings | M | Same expansion; every successful step counts one palindrome. |
| 125 | 91. Decode Ways | M | One-digit step if not 0, two-digit step if 10-26. Zeros are the trap. |
| 126 | 322. Coin Change | M | best[a] = 1 + min(best[a - c]); infinity marks unreachable amounts. |
| 127 | 152. Maximum Product Subarray | M | Track both max and min ending here; a negative number swaps them. |
| 128 | 139. Word Break | M | ok[i] is true if a word ends at i and ok[start] is true. |
| 129 | 300. Longest Increasing Subsequence | M | Patience sorting with bisect gives O(n log n). |
| 130 | 416. Partition Equal Subset Sum | M | Subset sum to total / 2; a Python int works as a bitset of reachable sums. |
Stage 15: 2-D Dynamic Programming
Code: solutions/dp_2d.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 131 | 62. Unique Paths | M | Paths = from above + from the left; one row of memory is enough. |
| 132 | 1143. Longest Common Subsequence | M | Match: diagonal + 1. No match: max of up and left. |
| 133 | 309. Best Time to Buy and Sell Stock with Cooldown | M | A small state machine: holding, just sold, resting. |
| 134 | 518. Coin Change II | M | Coins in the outer loop count combinations, not orderings. |
| 135 | 494. Target Sum | M | The plus-set must sum to (total + target) / 2; count those subsets. |
| 136 | 97. Interleaving String | M | ok[i][j]: can s1[:i] and s2[:j] build s3[:i+j]? |
| 137 | 72. Edit Distance | M | Insert, delete, replace map to left, up and diagonal cells. |
| 138 | 312. Burst Balloons | H | Choose the LAST balloon in a range; its neighbours are then fixed. |
| 139 | 10. Regular Expression Matching | H | For x*: skip the pair, or consume one matching char and stay. |
Stage 16: Greedy and Intervals
Code: solutions/greedy_intervals.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 140 | 53. Maximum Subarray | M | Kadane: restart the running sum when it would only hurt. |
| 141 | 55. Jump Game | M | Track the farthest reachable index; fail if you stand past it. |
| 142 | 45. Jump Game II | M | BFS by ranges: each jump covers up to the farthest reach seen so far. |
| 143 | 134. Gas Station | M | If total gas >= total cost an answer exists; restart after any negative tank. |
| 144 | 56. Merge Intervals | M | Sort by start; extend the last interval while they overlap. |
| 145 | 57. Insert Interval | M | Copy the ones before, merge the overlapping run, copy the rest. |
| 146 | 435. Non-overlapping Intervals | M | Keep the interval that ends first (activity selection). |
| 147 | 763. Partition Labels | M | A part must reach the last occurrence of every letter inside it. |
Stage 17: Bit Manipulation and Math
Code: solutions/bit_math.py
| # | Problem | Diff | Key insight |
|---|---|---|---|
| 148 | 136. Single Number | E | x ^ x = 0, so XOR of everything leaves the single value. |
| 149 | 191. Number of 1 Bits | E | n & (n - 1) clears the lowest set bit. |
| 150 | 48. Rotate Image | M | Clockwise rotation = transpose, then reverse each row. |
Python interview toolkit
Most solutions here use only these standard library tools. Learn them once and you will write shorter, less buggy code.
from collections import Counter, defaultdict, deque, OrderedDict
import heapq
import bisect
from functools import lru_cache
# Counting
counts = Counter("banana") # Counter({'a': 3, 'n': 2, 'b': 1})
counts.most_common(1) # [('a', 3)]
# Grouping
groups = defaultdict(list)
groups["key"].append(1)
# Queue for BFS (O(1) pops from the left; list.pop(0) is O(n))
q = deque([start])
node = q.popleft()
# Heaps are min-heaps; negate for a max-heap
heap = []
heapq.heappush(heap, (priority, item_id))
smallest = heapq.heappop(heap)
heapq.nlargest(3, nums)
# Sorted-array search
i = bisect.bisect_left(sorted_list, x) # first index with value >= x
j = bisect.bisect_right(sorted_list, x) # first index with value > x
# Memoised recursion for top-down DP
@lru_cache(maxsize=None)
def dp(i, j):
...
# Infinity sentinels
INF = float("inf")
# 4-direction grid moves
DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))
Common Python traps in interviews:
[[0] * cols] * rowscreates rows that share one list. Use[[0] * cols for _ in range(rows)].- Python’s
%always returns a non-negative result for a positive divisor (-7 % 5 == 3), unlike C++ and Java. - Integer division
//floors toward negative infinity (-7 // 2 == -4). For “truncate toward zero” useint(a / b). - The default recursion limit is about 1000 frames. Deep DFS on a 10^4 node path can fail; use an explicit stack or
sys.setrecursionlimit. - Heaps compare tuples element by element. Add a unique counter as a tiebreaker if the payload is not comparable.
Complexity cheat sheet
| Input size n | Target complexity | Typical approach |
|---|---|---|
| n <= 12 | O(n!) | Permutations, brute force |
| n <= 20-25 | O(2^n) | Subsets, bitmask DP |
| n <= 500 | O(n^3) | Interval DP, Floyd-Warshall |
| n <= 5,000 | O(n^2) | 2-D DP, nested loops |
| n <= 10^5 - 10^6 | O(n log n) or O(n) | Sorting, heaps, binary search, two pointers, hashing |
| n > 10^8 | O(log n) or O(1) | Math, binary search on the value |
| Operation | Python cost |
|---|---|
list.append, list.pop() |
O(1) amortised |
list.pop(0), list.insert(0, x) |
O(n) |
x in list |
O(n) |
x in set, dict[key] |
O(1) average |
sorted(list) |
O(n log n) |
heapq.heappush / heappop |
O(log n) |
deque.appendleft / popleft |
O(1) |
| String concatenation in a loop | O(n^2) total; build a list and "".join it |
Running the solutions and tests
Requirements: Python 3.9 or newer. No third-party packages.
git clone https://github.com/Ralpberry-Labs/leetcode-master-150.git
cd leetcode-master-150
python3 -m unittest discover -s tests -t .
Try a single solution in a REPL:
>>> from solutions.sliding_window import min_window
>>> min_window("ADOBECODEBANC", "ABC")
'BANC'
>>> from solutions.structures import build_tree
>>> from solutions.trees import level_order
>>> level_order(build_tree([3, 9, 20, None, None, 15, 7]))
[[3], [9, 20], [15, 7]]
solutions/structures.py contains ListNode, TreeNode and helpers that convert LeetCode’s list format (for example [1, None, 2]) into real nodes, so you can test your own versions locally.
Repository layout:
solutions/
structures.py ListNode, TreeNode, GraphNode, build/convert helpers
arrays_hashing.py Stage 1
two_pointers.py Stage 2
... one file per stage
bit_math.py Stage 17
tests/
test_stages_1_to_6.py
test_stages_7_to_11.py
test_stages_12_to_17.py
FAQ
Is 150 problems enough? For most interviews, yes, if you understand each pattern well enough to solve a new problem with it. Solving 150 problems deeply beats skimming 500.
Why Python? It is short, readable and accepted at nearly every company. The insights apply to any language; only the standard-library tools differ.
What if I cannot solve Easy problems yet? Spend a week on Stage 1 and Stage 2 only, and redo each problem from memory the next day. Speed comes from repetition, not from talent.
Should I memorise solutions? Memorise patterns and templates (binary search bounds, BFS levels, backtracking skeleton, union-find). Do not memorise full answers; interviewers change details.
Do I need LeetCode Premium? No. Every problem in this list is publicly accessible on LeetCode at the time of review.
How long does the whole plan take? At three problems a day with review days, about eight weeks. Most people need 30-60 minutes per Medium problem at first and about 20 minutes once the patterns click.
Easy problems feel fine but Mediums are impossible. What now? That is normal. Mediums usually combine two ideas (for example sorting + two pointers, or BFS + a visited set). Read only the key insight, close the page and try again; if it still fails, read the solution, wait a day and solve it from scratch.
Should I use Python in the interview if I use Java at work? Use the language you are fastest and most accurate in. Python saves time on syntax, but switching a month before interviews is risky if you will forget standard-library details.
Do companies still ask LeetCode-style questions? Many still do for software engineering roles, alongside system design and behavioural rounds. Some companies use practical coding or take-home tasks instead, so check each company’s interview guide.
How do I know I am ready? When you can solve an unseen Medium from a topic you studied within about 30 minutes while explaining your reasoning, in most topics.
How this plan compares to other popular lists
There are several well-known interview lists. They overlap heavily; what differs is size, order and how much explanation you get.
| List | Size | Order | Solutions included | Best for |
|---|---|---|---|---|
| This plan | 150 | 17 topic stages, easy ideas first | Tested Python + one-line insight | Learning patterns in a fixed order |
| LeetCode 75 | 75 | Grouped by topic on LeetCode | LeetCode editorials (some paid) | 1-3 months of prep, no Hard problems |
| LeetCode Top Interview 150 | 150 | Grouped by topic on LeetCode | LeetCode editorials (some paid) | Broad coverage of classic questions |
| Grind 75 | 75 by default, adjustable by weeks and hours | Week-by-week schedule you can customise | Links only | People with a fixed number of weeks |
| NeetCode roadmap | 150 in its main list | Topic graph with prerequisites | Video explanations | Visual learners |
Our pick by situation:
- Two weeks or less: do Stages 1-3, 6, 8, 12 and 14 of this plan (about 80 problems), then mock interviews.
- One to three months: this plan in the 8-week schedule above, then revisit your “redo” list.
- You learn best from video: pair each stage here with the matching video topic on the NeetCode roadmap; keep this repo’s tests to check your own code.
- You already solved 300+ problems: skip lists entirely and do timed contests (LeetCode weekly contests, AtCoder Beginner Contests).
Mistakes that cost people offers
| Mistake | Better habit |
|---|---|
| Coding immediately | Restate the problem, ask about constraints and edge cases first |
| Silent thinking | Narrate your approach; interviewers grade the process |
| Only optimal solutions | State the brute force and its complexity, then improve it |
| No testing | Trace one normal and one edge case through your code before saying “done” |
| Memorised answers | Explain why the pattern applies; follow-up questions expose memorisation |
| Ignoring complexity | Give time and space for every solution without being asked |
| Never practising under time | Do at least ten 45-minute timed sessions before real interviews |
Where to go next
- More patterns: Tech Interview Handbook for algorithm cheat sheets and behavioural prep.
- Deeper theory: MIT 6.006 Introduction to Algorithms lectures and problem sets (free).
- Visualise algorithms: VisuAlgo animates sorting, trees, heaps and graph algorithms.
- Python reference: Python TimeComplexity wiki,
heapq,bisect,collections. - Harder problems: CP-Algorithms explains segment trees, string algorithms and advanced graphs used in Hard problems and contests.
- SQL rounds: many data and backend loops include SQL; LeetCode’s Top SQL 50 plan covers the common patterns.
Contributing
PRs are welcome. Keep entries accurate: every new solution needs a test, every link must point to the real LeetCode problem, and key insights should stay to one line. Run python3 -m unittest discover -s tests -t . before opening a PR. If you find a bug or a clearer explanation, open an issue.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.