Skip to content

Repository files navigation

Leetcode for fun

One question a day to ensure a sharp mind.

Grading Criteria

  • L0: straight forward question
  • L1: variance of template
  • L2: need to think for a while / complex implementation
  • L3: need aha moment / unexpected algorithm

Roadmap

Study-order progression through all topic areas. Each entry links to the topic README with templates and notes.

Fundamentals

#TopicREADMEDescription
1StringREADMEString operations, Counter API
2Hash TableREADMECounter operations, mapping
3Linked ListREADMEReverse, fast/slow pointers
4Two PointersREADMESame/different direction templates
5Sliding WindowREADMEFixed/dynamic window, at-most trick
6Prefix SumREADME1D/2D prefix sum, difference array
7Binary SearchREADMETemplate, bisect module
8StackREADMEMonotonic stack, Eulerian path, tree traversal
9Monotonic QueueREADMESliding window max/min by deque
10HistogramREADMEHistogram model for matrices

Search and Graph

#TopicREADMEDescription
11BFSREADMEGraph BFS template
12BFS TreeREADMETree level-order traversal
13BFS/DFS GraphREADMEMatrix and graph DFS
14DijkstraREADMESingle-source shortest path
15Floyd-WarshallREADMEAll-pairs shortest path
16DFS TreeREADMETree DFS traversal templates
17LCAREADMELowest common ancestor, binary lifting
18BacktrackingREADMEPruning, array/graph templates

Dynamic Programming

#TopicREADMEDescription
19DP OverviewREADMECategories, matrix exponentiation
20KnapsackREADME0/1 and unbounded knapsack
21LISREADMEO(n^2) and O(n log n)
22Longest SubsequenceREADMELIS/LCS templates
23KadaneREADMEMaximum subarray
24Digit DPREADMEDigit DP templates with bounds

Greedy and Math

#TopicREADMEDescription
25GreedyREADMEAssign/interval problems
26MathREADMEGCD/LCM, sieve, math functions
27CombinatoricsREADMEProduct rule, C(n,k), permutations
28PrimesREADMESieve, factorization, LPF
29Bezout's LemmaREADMEExtended GCD
30Game TheoryREADMEMinimax
31ProbabilityREADMEReservoir sampling, shuffle
32Bit ManipulationREADMEBit operations, bitmask DP

Advanced Data Structures

#TopicREADMEDescription
33TrieREADMEInsert, search, prefix
34Union-FindREADMEPath compression, union by rank, Kruskal's
35Binary Indexed TreeREADMEFenwick tree
36Segment TreeREADMETree/array/ZKW, lazy propagation
37Sorted ContainersREADMESortedList complexity reference

Advanced Algorithms

#TopicREADMEDescription
38SortingREADMECycle sort
39KMPREADMEKMP pattern matching
40Z-FunctionREADMEZ-function pattern matching
41PrimREADMEMinimum spanning tree
42Majority VotingREADMEBoyer-Moore voting
43Rolling HashREADMERabin-Karp
44Greedy HeapREADMEHeap-based greedy patterns
45SQLREADMEQuery categories
46System DesignREADMEGeneral steps

Running Solutions

Solutions depend on header.py for shared imports and class definitions. Use the runner script:

python run.py path/to/solution.py

This pre-loads header.py into the namespace before executing the solution file.

Time Complexity Analysis

Row: input size(IS), column: time complexity(TC)

Input SizeO($2^n$)O($n^4$)O($n^3$)O($n^2$)O(nlogn)O(n)O(logn)O(1)
1-10
10-50
50-100
100-500
500 - $10^3$
$10^3$ - $10^4$
$10^4$ - $10^5$?
$10^5$ - $10^6$
$10^6$ - $10^9$
TCAlgorithm
O($2^n$)DFS-combination($2^n$), DFS-permutation(n!)
O($n^4$)DP
O($n^3$)DP, Floyd-Warshall
O($n^2$)DP
O(nlogn)Sorting, Heap, divide&conquer, Dijkstra-heap, QuickSort
O(n)DP, DFS-tree(V), BFS(V+E), TopologicalSorting(V+E), BucketSort(N+K), MonotonicStack
O(logn)BinarySearch, BinaryIndexTree
O(1)Math

Approach Checklist

  1. What is the data size? (check the time complexity table)
  2. Can I sort or group the elements?
  3. DP, greedy, or binary search? (optimal substructure → DP, greedy-choice property → greedy)
  4. Can I enumerate on a specific variable? (fix one dimension, solve the other)
  5. Can I use two passes / prefix-suffix decomposition?
  6. Can I solve it in reverse order?
  7. Can I convert it to a known problem?
  8. Is there monotonicity I can exploit? (binary search on answer)
  9. Can I directly simulate the process described in the problem?
  10. See the Pattern Recognition Guide for keyword-based technique selection.

Pattern Recognition Guide

When you spot these keywords or structural patterns in a problem, consider the listed techniques first.

Array and Subarray

Signal / KeywordTechniques to Consider
"subarray" (general)sliding window, monotonic stack/queue, prefix sum + hash table, Kadane's
"subarray sum equals k"prefix sum + hash table
"at most k" / "at least k" / "exactly k"at-most trick: f(k) - f(k-1)
"longest/shortest subarray with condition"sliding window (dynamic window)
"max/min subarray sum"Kadane's, prefix sum
"number of subarrays where..."sliding window counting, prefix sum + hash table
"contiguous elements"sliding window, prefix sum
"difference between elements in window"sliding window + hash/sorted structure
"range update on array"difference array (sweep line)
"range query (static)"prefix sum, 2D prefix sum
"range query (dynamic / with updates)"segment tree, BIT (Fenwick tree)
"next greater/smaller element"monotonic stack
"sliding window max/min"monotonic deque

Subsequence

Signal / KeywordTechniques to Consider
"subsequence" (general)DP (LIS/LCS), two pointers, greedy
"longest increasing subsequence"O(n log n) patience sort with bisect
"longest common subsequence"2D DP
"count subsequences"DP, combinatorics
"subsequence with constraint"DP with extra state
"two sequences / edit distance"double-sequence DP

Optimization and Search

Signal / KeywordTechniques to Consider
"minimize the maximum" / "maximize the minimum"binary search on answer
"kth smallest/largest"binary search, heap, quick select
"minimum cost / operations to..."DP, BFS (shortest path), greedy
"is it possible to..."DP, greedy, graph reachability, math
"count number of ways"DP, combinatorics
"find all / generate all"backtracking, BFS/DFS
"optimal strategy for two players"minimax, game theory DP
"buy and sell / state transitions"state machine DP or greedy

String

Signal / KeywordTechniques to Consider
"palindrome"two pointers (expand from center), Manacher's, DP
"anagram"Counter / sorting, sliding window
"substring matching"sliding window, rolling hash (Rabin-Karp), KMP, Z-function
"pattern matching"KMP, Z-function, rolling hash
"parentheses / brackets"stack, greedy
"string transformation / edit distance"DP (double-sequence)
"repeated pattern in string"KMP failure function, Z-function
"decode / parse string"stack, recursion, DP

Graph

Signal / KeywordTechniques to Consider
"connected components"Union-Find, BFS/DFS
"shortest path (unweighted)"BFS
"shortest path (weighted, non-negative)"Dijkstra
"shortest path (all pairs)"Floyd-Warshall
"shortest path (negative edges)"Bellman-Ford
"cycle detection (directed)"DFS 3-coloring (white/gray/black)
"cycle detection (undirected)"Union-Find, DFS with parent tracking
"topological order / prerequisites / dependency"topological sort (Kahn's BFS)
"bipartite / 2-colorable"BFS/DFS 2-coloring
"MST / minimum cost to connect all"Kruskal's (Union-Find), Prim's (heap)
"number of islands / flood fill"BFS/DFS, Union-Find
"word ladder / transformation sequence"BFS

Tree

Signal / KeywordTechniques to Consider
"lowest common ancestor (LCA)"binary lifting, recursive DFS
"tree diameter / longest path"two BFS, or DFS returning depth
"rerooting / answer for every node as root"tree DP with moving root
"subtree queries"DFS + Euler tour (in/out time), post-order
"path sum / path queries"LCA + prefix sums on tree, DFS
"binary tree traversal"recursive DFS, iterative with stack
"serialize / deserialize tree"pre-order + null markers, level-order

Matrix / Grid

Signal / KeywordTechniques to Consider
"2D grid traversal / islands / regions"BFS/DFS
"largest rectangle in matrix"histogram model + monotonic stack
"2D range sum / submatrix sum"2D prefix sum
"shortest path in grid"BFS (unweighted), Dijkstra (weighted cells)
"rotate / spiral / layer traversal"simulation with boundary tracking

Interval

Signal / KeywordTechniques to Consider
"merge intervals"sort by start
"non-overlapping / max intervals"sort by end, greedy
"interval scheduling / meeting rooms"sort by end (greedy), sweep line
"overlapping interval count / max overlap"sweep line, difference array
"insert interval"binary search or linear merge
"range add/set then query"difference array, segment tree + lazy propagation

Counting and Combinatorics

Signal / KeywordTechniques to Consider
"permutation"backtracking, n!, next_permutation
"combination / choose k from n"C(n,k), Pascal's triangle, backtracking
"number of ways to partition/arrange"DP, combinatorics (product rule)
"divisibility / GCD / LCM"number theory, Euclidean algorithm
"prime / factorization"sieve of Eratosthenes, LPF (least prime factor)
"modulo arithmetic / large results mod 10^9+7"modular exponentiation, Fermat's little theorem

Data Structure Selection

Signal / KeywordTechniques to Consider
"dynamic sorted data / rank queries"SortedList, segment tree, BIT
"prefix/suffix lookups with updates"BIT (Fenwick tree), segment tree
"string prefix queries / autocomplete"trie
"disjoint sets / union / merge groups"Union-Find (DSU)
"median maintenance / top-k from stream"two heaps (max-heap + min-heap), SortedList
"frequent element / majority element"Boyer-Moore voting
"merge k sorted lists/arrays"heap (priority queue)
"LRU / LFU / ordered access"hash map + doubly linked list, OrderedDict
"rearrange to avoid adjacent duplicates"greedy with max-heap

Advanced / Niche Patterns

Less frequent, but important to recognize when they show up.

State Compression and Bitmask

Signal / KeywordTechniques to Consider
"visit all nodes/cities (TSP)"bitmask DP, n ≤ 20
"subset enumeration / powerset"bitmask iteration, backtracking
n ≤ 20 with combinatorial constraintbitmask DP
"assign items to groups with constraints"bitmask DP, backtracking
"XOR of subsets"bitmask enumeration, linear algebra over GF(2)

Digit DP

Signal / KeywordTechniques to Consider
"count numbers in [L, R] with digit property"digit DP (tight/free bound)
"numbers with digit sum / digit constraint"digit DP with state for constraint
"no repeated digits / specific digit pattern"digit DP with bitmask or set tracking

Interval DP

Signal / KeywordTechniques to Consider
"merge stones / matrix chain multiplication"interval DP, O(n³)
"minimum cost to merge / burst balloons"interval DP
"palindrome partitioning (min cuts)"interval DP or DP with greedy
"optimal game (pick from ends)"interval DP (minimax on range)

Advanced DP Variants

Signal / KeywordTechniques to Consider
"recurrence with very large n (10^9+)"matrix exponentiation
"expected value / probability of state"probability DP
"tree + optimal substructure"tree DP (post-order aggregation)
"DP transitions too slow"data structure optimized DP (monotonic queue, segment tree, convex hull trick)
"DP depends on future decisions"solve in reverse, or reformulate state
"DP on permutation / arrangement"permutation DP, profile DP

Advanced Graph

Signal / KeywordTechniques to Consider
"Euler path / circuit / use every edge once"Hierholzer's algorithm
"strongly connected components"Tarjan's, Kosaraju's
"bridges / articulation points"Tarjan's DFS
"network flow / max matching"max-flow (Dinic's), Hungarian algorithm
"negative cycle detection"Bellman-Ford

Advanced String

Signal / KeywordTechniques to Consider
"longest palindromic substring"Manacher's O(n), expand around center
"string hashing / duplicate substring detection"rolling hash (Rabin-Karp)
"suffix queries / longest repeated substring"suffix array
"XOR queries on binary representations"bitwise trie

Specialized Sorting

Signal / KeywordTechniques to Consider
"place each element at its correct index"cycle sort
"sort with limited value range"counting sort, bucket sort
"find kth element without full sort"quick select, O(n) average
"count inversions / merge-based counting"merge sort

Math Niche

Signal / KeywordTechniques to Consider
"express n as sum of squares"Lagrange's four-square theorem
"linear combination of a and b"Bezout's lemma, extended GCD
"random sampling from stream"reservoir sampling
"random sampling from region"rejection sampling
"fair shuffle"Fisher-Yates shuffle
"game with optimal play (Nim, Sprague-Grundy)"Sprague-Grundy theorem, XOR of pile sizes
"cellular automaton / Game of Life"simulation with state encoding
"circular array"modulo indexing, or duplicate the array

Cheat sheet

Palindrome

Efficiently find all the palindrome numbers in a range 10**9:

pal= []
base=1whilebase<=10000:
# odd numberforiinrange(base, base*10):
x=it=i//10whilet:
x=x*10+t%10t//=10pal.append(x)
# even numberifbase<=1000:
foriinrange(base, base*10):
x=t=iwhilet:
x=x*10+t%10t//=10pal.append(x)
base*=10pal.append(1_000_000_001) # sentinel

Reference

  1. 用什么语言刷题?C++/Java/Python横向大比较
  2. Leetcode 101: A Leetcode Grinding Guide(C++ Version)
  3. Algorithms for Competitive Programming
  4. 古城算法 slides(google drive)
  5. 输入数据规模和时间复杂度的关系
  6. 0x3ff-palindrome

About

Leetcode python solutions and notes by Zhengyuan Zhu

Resources

Stars

20 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages