related-skills: abl-v10-learning, abl-v12-learning
Skill: programming-algorithms
Programming Algorithms: A Comprehensive Guide for Algorithm Selection
Role: Senior Algorithm Engineer — select, implement, and optimize algorithms for problem-solving across domains.
Philosophy: Algorithmic Precision — choose the right tool for the job based on time/space trade-offs, input characteristics, and problem constraints. No fabrication — leverage established, proven algorithms.
Purpose: Why Standard Algorithms
The Problem with Fabrication:
- Reinventing algorithms introduces bugs and suboptimal solutions
- Standard algorithms have decades of academic analysis and optimization
- Edge cases are already understood and handled
- Performance characteristics are well-documented
When to Use Standard Algorithms:
- Problem matches a known pattern (sorting, shortest path, etc.)
- Input size suggests complexity constraints
- Resource limits (time/space) are known
- Industry standards exist for the domain
Key Principles:
- Trade-offs are inevitable: Time vs space, simplicity vs performance
- Context matters: Input size, distribution, and constraints dictate choices
- Proof first, optimize later: Ensure correctness before micro-optimizations
related-skills: abl-v10-learning, abl-v12-learning
Table of Contents
- Sorting Algorithms
- Searching Algorithms
- Graph Algorithms
- Dynamic Programming
- Greedy Algorithms
- String Algorithms
- Mathematical Algorithms
- Geometric Algorithms
- Backtracking Algorithms
- Numerical Algorithms
- Probabilistic Algorithms
- Streaming Algorithms
- Algorithm Selection Guide
related-skills: abl-v10-learning, abl-v12-learning
Sorting Algorithms
Quick Sort
- Alternative Names: Partition-exchange sort
- Time Complexity:
- Best: O(n log n) (balanced partitions)
- Average: O(n log n)
- Worst: O(n²) (poor pivot selection)
- Space Complexity: O(log n) (recursion stack)
- Key Use Cases:
- General-purpose sorting when cache locality matters
- In-place sorting with minimal memory overhead
- Average-case optimal for random data
- When to Choose:
- Data is randomly distributed
- Memory is constrained (in-place)
- Average performance matters more than worst-case guarantee
- Not suitable for linked lists or nearly-sorted data
- Optimizations:
- Use median-of-three pivot selection
- Switch to insertion sort for small partitions (n < 10-20)
- Iterative implementation to avoid stack overflow
Merge Sort
- Alternative Names: Mergesort
- Time Complexity:
- Best: O(n log n)
- Average: O(n log n)
- Worst: O(n log n)
- Space Complexity: O(n) (temporary arrays)
- Key Use Cases:
- Linked list sorting
- External sorting (files too large for memory)
- Stable sorting required
- Parallel processing (tasks are independent)
- When to Choose:
- Stability is required (equal elements maintain order)
- Sorting linked lists (O(1) extra space)
- External sorting with disk I/O
- Predictable performance needed
- Optimizations:
- Bottom-up (iterative) implementation
- Use insertion sort for small subarrays
- Parallel merge sort for multi-core systems
Heap Sort
- Alternative Names: Heap sorting
- Time Complexity:
- Best: O(n log n)
- Average: O(n log n)
- Worst: O(n log n)
- Space Complexity: O(1) (in-place)
- Key Use Cases:
- In-place sorting with guaranteed O(n log n) performance
- Priority queue implementation
- Finding top-k elements (use min-heap of size k)
- Memory-constrained environments
- When to Choose:
- Worst-case performance guarantee needed
- Memory is extremely constrained
- Building priority queues
- Not suitable for nearly-sorted data (no early exit)
- Optimizations:
- Build heap in O(n) time (Floyd's algorithm)
- Use binary heap for arrays, binomial heap for decreases
Radix Sort
- Alternative Names: Bucket sort (for integers), LSD radix sort
- Time Complexity:
- Best: O(nk)
- Average: O(nk)
- Worst: O(nk)
- Where k = number of digits/characters
- Space Complexity: O(n + k) (buckets)
- Key Use Cases:
- Sorting integers with fixed width
- Sorting strings by characters
- Stable sorting for digit-by-digit processing
- When k is small relative to n
- When to Choose:
- Integers with bounded range
- Strings with fixed maximum length
- Need stable sorting
- k is O(1) or very small
- Not suitable for floating-point or large k values
- Optimizations:
- MSD (Most Significant Digit) for string sorting
- LSD (Least Significant Digit) for fixed-width integers
- Use counting sort as stable subroutine
Bucket Sort
- Alternative Names: Bin sort
- Time Complexity:
- Best: O(n + k) (uniform distribution)
- Average: O(n + k)
- Worst: O(n²) (all elements in one bucket)
- Space Complexity: O(nk) (buckets)
- Key Use Cases:
- Uniformly distributed floating-point numbers
- Sorting data that can be partitioned into ranges
- Database partitioning
- Parallel processing (independent buckets)
- When to Choose:
- Input is uniformly distributed over a range
- Can create appropriate number of buckets
- Parallel sorting allowed
- Not suitable for skewed distributions
Insertion Sort
- Time Complexity:
- Best: O(n) (already sorted)
- Average: O(n²)
- Worst: O(n²)
- Space Complexity: O(1) (in-place)
- Key Use Cases:
- Nearly-sorted data
- Small datasets (n < 20)
- Online algorithms (inserting elements one at a time)
- Subroutine for hybrid algorithms
- When to Choose:
- Small input sizes (often used as base case)
- Data is already partially sorted
- Online sorting (streaming input)
- Minimal memory overhead required
Bubble Sort
- Time Complexity:
- Best: O(n) (optimized with swapped flag)
- Average: O(n²)
- Worst: O(n²)
- Space Complexity: O(1) (in-place)
- Key Use Cases:
- Educational demonstrations
- Detecting nearly-sorted data
- Small datasets with few swaps needed
- When to Choose:
- Almost never for production (except teaching)
- Detect if data is already sorted (O(n))
- Very small datasets where simplicity matters
Selection Sort
- Time Complexity:
- Best: O(n²)
- Average: O(n²)
- Worst: O(n²)
- Space Complexity: O(1) (in-place)
- Key Use Cases:
- Minimizing number of swaps
- Small datasets where swaps are expensive
- Educational demonstrations
- When to Choose:
- Memory writes are costly (minimize to n swaps)
- Small datasets
- Never for large datasets
Shell Sort
- Alternative Names: Shell's method
- Time Complexity:
- Best: O(n log² n)
- Average: O(n log² n) to O(n^(3/2))
- Worst: O(n²)
- Space Complexity: O(1) (in-place)
- Key Use Cases:
- Middle ground between O(n²) and O(n log n)
- When quick sort/merge sort are too complex
- Embedded systems with limited resources
- When to Choose:
- Need better than O(n²) without complexity of O(n log n)
- Memory-constrained but need better performance
related-skills: abl-v10-learning, abl-v12-learning
Searching Algorithms
Binary Search
- Alternative Names: Half-interval search, logarithmic search
- Time Complexity:
- Best: O(1)
- Average: O(log n)
- Worst: O(log n)
- Space Complexity: O(1) iterative, O(log n) recursive
- Key Use Cases:
- Finding elements in sorted arrays
- Finding first/last occurrence
- Finding minimum/maximum in bitonic/unimodal functions
- Floating-point binary search (precision search)
- When to Choose:
- Data is sorted or can be sorted
- Need O(log n) lookup time
- Static data (not frequently updated)
- Not suitable for unsorted or frequently changing data
- Variants:
- Lower bound / Upper bound (first ≥ / first >)
- Rotated array search
- 2D matrix search (row-wise and column-wise sorted)
- Real number binary search (for precision)
Interpolation Search
- Time Complexity:
- Best: O(log log n) (uniform distribution)
- Average: O(log log n)
- Worst: O(n) (non-uniform distribution)
- Space Complexity: O(1)
- Key Use Cases:
- Uniformly distributed sorted data
- Large datasets with known distribution
- Numeric data with continuous values
- When to Choose:
- Data is uniformly distributed
- Data is sorted and large
- Not suitable for sparse or non-uniform data
Exponential Search
- Alternative Names: Galloping search, doubling search
- Time Complexity:
- Best: O(1)
- Average: O(log i)
- Worst: O(log i)
- Where i is the position of the element
- Space Complexity: O(1)
- Key Use Cases:
- Unbounded/infinite sorted arrays
- Finding element position for binary search
- When element might be near the beginning
- When to Choose:
- Sorted array but size unknown
- Element likely near start
- As preprocessing for binary search
Linear Search
- Time Complexity:
- Best: O(1)
- Average: O(n)
- Worst: O(n)
- Space Complexity: O(1)
- Key Use Cases:
- Unsorted data
- Small datasets
- Single search (sorting not worth it)
- Linked lists
- When to Choose:
- Data is unsorted
- Small n where O(n) is acceptable
- Single search on large dataset
Ternary Search
- Time Complexity:
- Best: O(1)
- Average: O(log n)
- Worst: O(log n)
- Space Complexity: O(1)
- Key Use Cases:
- Finding minimum/maximum of unimodal function
- Convex/concave functions
- Golden section search alternative
- When to Choose:
- Optimization of unimodal functions
- When binary search doesn't apply
- Compare with golden section search
Jump Search
- Alternative Names: Block search
- Time Complexity:
- Best: O(1)
- Average: O(√n)
- Worst: O(√n)
- Space Complexity: O(1)
- Key Use Cases:
- Sorted data where jumping back is expensive
- Large datasets on disk
- Intermediate between linear and binary search
- When to Choose:
- Jumping back is costly (disk seeks)
- O(√n) is acceptable
related-skills: abl-v10-learning, abl-v12-learning
Graph Algorithms
Breadth-First Search (BFS)
- Time Complexity: O(V + E)
- Space Complexity: O(V) (queue)
- Key Use Cases:
- Shortest path in unweighted graphs
- Level-order traversal
- Connected components
- Bipartite checking
- Web crawling
- When to Choose:
- Unweighted shortest path
- Need all nodes at distance k
- Flow networks (Ford-Fulkerson)
- Social network analysis
Depth-First Search (DFS)
- Time Complexity: O(V + E)
- Space Complexity: O(V) (recursion stack)
- Key Use Cases:
- Topological sorting
- Cycle detection
- Strongly connected components
- Maze solving
- Path finding
- When to Choose:
- Need to explore all paths
- Stack-based iteration
- Topological sort
- Tarjan's SCC algorithm
- Variants:
- Iterative DFS (explicit stack)
- DFS with parent tracking
- DFS forest (multiple components)
Dijkstra's Algorithm
- Alternative Names: Dijkstra's shortest path
- Time Complexity:
- O(V²) (naive)
- O((V + E) log V) (with priority queue)
- O(V log V + E) (Fibonacci heap)
- Space Complexity: O(V)
- Key Use Cases:
- Single-source shortest path (non-negative weights)
- Routing protocols
- GPS navigation
- Network optimization
- When to Choose:
- Non-negative edge weights
- Single source to all destinations
- Need exact shortest path
- Not suitable for negative weights
- Optimizations:
- Use Fibonacci heap for O(V log V + E)
- Early termination when target reached
- Bidirectional Dijkstra for source-target
Bellman-Ford Algorithm
- Time Complexity: O(VE)
- Space Complexity: O(V)
- Key Use Cases:
- Single-source shortest path with negative weights
- Negative cycle detection
- Distributed routing
- Linear programming
- When to Choose:
- Graph may have negative edge weights
- Need negative cycle detection
- Distributed systems
- Not suitable for dense graphs (too slow)
Floyd-Warshall Algorithm
- Alternative Names: Floyd's algorithm, Roy-Warshall
- Time Complexity: O(V³)
- Space Complexity: O(V²)
- Key Use Cases:
- All-pairs shortest path
- Transitive closure
- Negative cycle detection
- Density graphs
- When to Choose:
- Need all-pairs shortest paths
- Graph is dense (V³ acceptable)
- Small V (V < 200-500)
- Transitive closure needed
- Optimizations:
- Use only when V is small
- Can detect negative cycles
Kruskal's Algorithm
- Alternative Names: Minimum spanning tree (Kruskal)
- Time Complexity: O(E log E) or O(E log V)
- Space Complexity: O(V) (disjoint set)
- Key Use Cases:
- Minimum spanning tree
- Network design
- Approximation algorithms
- Clustering
- When to Choose:
- Sparse graphs
- Need MST
- Edge-based processing
- Disjoint set data structure available
- Optimizations:
- Union by rank + path compression
- Pre-sort edges
Prim's Algorithm
- Time Complexity:
- O(V²) (naive)
- O((V + E) log V) (priority queue)
- O(E + V log V) (Fibonacci heap)
- Space Complexity: O(V)
- Key Use Cases:
- Minimum spanning tree
- Dense graphs
- Network design
- Image segmentation
- When to Choose:
- Dense graphs (more edges)
- Need MST
- Vertex-based processing
- Adjacency matrix available
- Comparison with Kruskal:
- Kruskal better for sparse
- Prim better for dense
Topological Sort
- Time Complexity: O(V + E)
- Space Complexity: O(V)
- Key Use Cases:
- Dependency resolution
- Course scheduling
- Build systems
- Job scheduling
- When to Choose:
- Directed acyclic graph (DAG)
- Need linear ordering
- Dependency ordering required
- Cycle detection (if not DAG)
- Methods:
- DFS-based (post-order)
- Kahn's algorithm (BFS with in-degrees)
A* Search Algorithm
- Time Complexity: O(b^d) worst case (where b = branching, d = depth)
- Space Complexity: O(b^d)
- Key Use Cases:
- Heuristic path finding
- Game AI
- Robotics
- Puzzle solving
- When to Choose:
- Need shortest path with heuristic
- Admissible heuristic available
- Want to reduce search space
- Not suitable without good heuristic
- Heuristic Requirements:
- Admissible (never overestimates)
- Consistent (triangle inequality)
- Variants:
-IDA* (Iterative Deepening A*)
- SMA* (Simplified Memory-Bounded A*)
Tarjan's SCC Algorithm
- Time Complexity: O(V + E)
- Space Complexity: O(V)
- Key Use Cases:
- Strongly connected components
- Graph condensation
- Dependency analysis
- Circuit simulation
- When to Choose:
- Find SCCs in directed graph
- Graph condensation needed
- Cycle analysis
- Topological sort on SCCs
Johnson's Algorithm
- Time Complexity: O(V² log V + VE)
- Space Complexity: O(V²)
- Key Use Cases:
- All-pairs shortest path (sparse graphs)
- Graphs with negative weights
- When to Choose:
- Sparse graphs, all-pairs shortest path
- Negative weights allowed
- Better than Floyd-Warshall for sparse
Chinese Postman Problem
- Time Complexity: O(V² log V + E) for undirected
- Space Complexity: O(V²)
- Key Use Cases:
- Route optimization (mail carrier)
- Circuit board inspection
- Street cleaning
- When to Choose:
- Need to traverse all edges
- Minimize total distance
- Graph may have odd-degree vertices
Traveling Salesman Problem (Approximations)
- Time Complexity: Varies by heuristic
- Space Complexity: O(V²)
- Key Use Cases:
- Route optimization
- Logistics
- Manufacturing (drill positioning)
- Heuristics:
- Nearest neighbor: O(V²)
- Christofides: O(V³) (3/2 approximation)
- Simulated annealing
- Genetic algorithms
- When to Choose:
- NP-hard problem, need approximation
- Real-world constraints
- Exact solution not required
Minimum Cut (Stoer-Wagner)
- Time Complexity: O(V³) or O(VE + V² log V)
- Space Complexity: O(V²)
- Key Use Cases:
- Network reliability
- Image segmentation
- Clustering
- When to Choose:
- Find minimum edge cut
- Graph partitioning
- No source-sink constraint
Maximum Flow (Ford-Fulkerson)
- Time Complexity: O(E * max_flow) (integer capacities)
- Space Complexity: O(V + E)
- Key Use Cases:
- Network flow
- Bipartite matching
- Image segmentation
- transportation problems
- When to Choose:
- Flow network optimization
- Matching problems
- Integer capacities
- Variants:
- Edmonds-Karp: O(VE²) (BFS)
- Dinic's: O(V²E) (level graph)
- Push-relabel: O(V²E) (more efficient in practice)
Hopcroft-Karp Algorithm
- Time Complexity: O(E * √V)
- Space Complexity: O(V)
- Key Use Cases:
- Maximum bipartite matching
- Assignment problems
- Job scheduling
- When to Choose:
- Bipartite graph matching
- Better than Ford-Fulkerson for bipartite
- Sparse graphs
Max-Flow Min-Cut Theorem Applications
- Time Complexity: Same as underlying max-flow algorithm
- Key Use Cases:
- Image segmentation (graph cuts)
- Computer vision
- Parallel computing
- VLSI design
related-skills: abl-v10-learning, abl-v12-learning
Dynamic Programming
0/1 Knapsack Problem
- Time Complexity: O(nW) where W = capacity
- Space Complexity: O(nW) or O(W) (optimized)
- Key Use Cases:
- Resource allocation
- Investment portfolio
- Container packing
- Knapsack variations
- When to Choose:
- Items can only be taken once
- Capacity constraint
- Optimal substructure exists
- Variants:
- Unbounded knapsack (unlimited items)
- Bounded knapsack (limited quantities)
- Multiple knapsack
- Fractional knapsack (greedy, not DP)
- Optimizations:
- Space optimization (1D array)
- Pruning based on bounds
- Meet-in-the-middle for large n
Longest Common Subsequence (LCS)
- Time Complexity: O(mn) where m, n = string lengths
- Space Complexity: O(mn) or O(min(m, n))
- Key Use Cases:
- Diff utilities
- Bioinformatics (DNA matching)
- Version control
- Plagiarism detection
- When to Choose:
- Two sequences common subsequence
- Order matters, continuity not required
- Not suitable for substring (use KMP/Rabin-Karp)
- Reconstruction:
- Track decisions during DP
- Backtrack to build actual LCS
- Optimizations:
- Hirschberg's algorithm: O(min(m,n)) space
- Early termination if no match
Longest Increasing Subsequence (LIS)
- Time Complexity: O(n²) (DP) or O(n log n) (patience sorting)
- Space Complexity: O(n)
- Key Use Cases:
- Pattern recognition
- Stock market analysis
- Bioinformatics
- Data smoothing
- When to Choose:
- Strictly increasing (or non-decreasing)
- Need longest monotonic subsequence
- O(n log n) Method:
- Maintain active lists
- Binary search for insertion
- Track predecessors for reconstruction
- Variants:
- Longest decreasing subsequence
- Bitonic subsequence
- Circular variant
Matrix Chain Multiplication
- Time Complexity: O(n³)
- Space Complexity: O(n²)
- Key Use Cases:
- Optimal parenthesization
- Compiler optimization
- Dynamic programming example
- When to Choose:
- Matrix multiplication order
- Minimize scalar multiplications
- All matrices compatible
- Optimizations:
- Store optimal split points
- Reconstruction for actual multiplication order
Edit Distance (Levenshtein)
- Time Complexity: O(mn)
- Space Complexity: O(mn) or O(min(m,n))
- Key Use Cases:
- Spell checking
- DNA sequence alignment
- Fuzzy string matching
- Version control
- When to Choose:
- Minimum edits to transform string A to B
- Insert, delete, replace operations
- Variants:
- Hamming distance (same length, replace only)
- Damerau-Levenshtein (adjacent swap)
- Wagner-Fischer (generalization)
- Optimizations:
- Space optimization
- Early termination for small distances
Coin Change Problem
- Time Complexity: O(n * amount) where n = coin types
- Space Complexity: O(amount)
- Key Use Cases:
- Making change (min coins)
- Combinatorial counting
- Resource allocation
- When to Choose:
- Minimize number of coins
- Count ways to make amount
- DP applies (optimal substructure)
- Variants:
- Minimum coins (0/1 or unlimited)
- Count combinations
- With limited coins
- Greedy doesn't always work
Subset Sum Problem
- Time Complexity: O(n * sum) or O(n * 2^(n/2)) (meet-in-middle)
- Space Complexity: O(n * sum)
- Key Use Cases:
- Scheduling
- Resource allocation
- Cryptography
- NP-complete problems
- When to Choose:
- Find subset with given sum
- Decision problem (existential)
- Optimization variant exists
- Optimizations:
- Meet-in-the-middle for large n
- Bitset optimization
- Pseudo-polynomial DP
Traveling Salesman Problem (Dynamic Programming)
- Time Complexity: O(n² * 2^n)
- Space Complexity: O(n * 2^n)
- Key Use Cases:
- Exact TSP for small n
- Algorithm comparison
- Benchmarking
- When to Choose:
- n < 20-25
- Need exact solution
- Not suitable for large n
- Held-Karp Algorithm:
- DP with bitmask
- Track visited set and last city
Partition Problem
- Time Complexity: O(n * sum)
- Space Complexity: O(sum)
- Key Use Cases:
- Fair division
- Load balancing
- NP-complete problems
- When to Choose:
- Split into equal-sum subsets
- Decision variant
- Optimization (minimize difference)
Longest Palindromic Subsequence
- Time Complexity: O(n²)
- Space Complexity: O(n²)
- Key Use Cases:
- Palindrome analysis
- Bioinformatics
- String algorithms
- When to Choose:
- Find longest palindromic subsequence
- Not substring (LPS can skip chars)
- Variants:
- Longest palindromic substring (manacher's O(n))
- Minimum deletions to make palindrome
Word Break Problem
- Time Complexity: O(n²) with dictionary lookup
- Space Complexity: O(n)
- Key Use Cases:
- Text segmentation
- Dictionary matching
- Natural language processing
- When to Choose:
- Can string be segmented into dictionary words?
- Count all possible segmentations
- Optimizations:
- Trie for dictionary lookup
- Memoization
- Early termination
Wildcard Pattern Matching
- Time Complexity: O(mn)
- Space Complexity: O(mn) or O(min(m,n))
- Key Use Cases:
- Regex matching
- File pattern matching
- Text processing
- When to Choose:
- Pattern with ? and * wildcards
- Match against text
- Variants:
- Regex with character classes
- Case sensitivity
- Multiline support
Unique Paths
- Time Complexity: O(mn)
- Space Complexity: O(mn) or O(min(m,n))
- Key Use Cases:
- Grid path counting
- Combinatorics
- Robot motion planning
- When to Choose:
- Grid with obstacles
- Count paths from top-left to bottom-right
- Only right/down moves allowed
- Variants:
- With obstacles (grid[i][j] = 1 blocked)
- With costs (minimum cost path)
- With forbidden cells
Egg Dropping Puzzle
- Time Complexity: O(n * k²) or O(n * log k)
- Space Complexity: O(nk)
- Key Use Cases:
- Testing/quality assurance
- Optimization under uncertainty
- Decision theory
- When to Choose:
- Minimize trials to find critical floor
- k eggs, n floors
- Binary search when 2 eggs
Catalan Numbers Applications
- Time Complexity: O(n²) for DP, O(n) for formula
- Space Complexity: O(n)
- Key Use Cases:
- Parentheses matching
- Binary tree counting
- Polygon triangulation
- Dyck paths
- When to Choose:
- Problems with Catalan structure
- Combinatorial counting
- Recursive structure
- Applications:
- n pairs of valid parentheses
- n+1 leaves in full binary tree
- n×n grid monotonic paths
- Convex polygon triangulation
Optimal Binary Search Tree
- Time Complexity: O(n³)
- Space Complexity: O(n²)
- Key Use Cases:
- Compiler design
- Database indexing
- Optimal search structure
- When to Choose:
- Given probabilities, build optimal BST
- Minimize search cost
- Static search set
- Optimizations:
- Knuth's optimization (if quadrangle inequality)
- O(n²) with Knuth optimization
Bitmask DP Applications
- Time Complexity: O(n * 2^n) or O(m * 3^(n/2))
- Space Complexity: O(2^n)
- Key Use Cases:
- Subset problems
- Graph problems (TSP, Hamiltonian)
- Set cover
- When to Choose:
- n < 20-25
- Subsets or states can be encoded as bitmask
- State space is 2^n
DP on Trees
- Time Complexity: O(V) for simple, O(V * k²) for k-state
- Space Complexity: O(V)
- Key Use Cases:
- Tree diameter
- Tree center
- Tree coloring
- Tree independence
- When to Choose:
- Tree structure
- Root the tree arbitrarily
- Combine children's results
- Common Patterns:
- Tree diameter (two DFS)
- Tree center (eccentricity)
- Tree isomorphism
- Tree knapsack
DP with Bitwise Operations
- Time Complexity: Varies
- Space Complexity: Varies
- Key Use Cases:
- Subset XOR sums
- Bit manipulation problems
- State compression
- When to Choose:
- Bitwise operations on subsets
- XOR-based problems
- Bitmask DP
related-skills: abl-v10-learning, abl-v12-learning
Greedy Algorithms
Activity Selection Problem
- Time Complexity: O(n log n) (sorting) or O(n) (if sorted)
- Space Complexity: O(1) extra
- Key Use Cases:
- Scheduling resources
- Meeting room allocation
- Single-resource scheduling
- When to Choose:
- Select maximum non-overlapping activities
- Greedy choice works (earliest finish time)
- Not for weighted activities (need DP)
Huffman Coding
- Time Complexity: O(n log n) (priority queue)
- Space Complexity: O(n)
- Key Use Cases:
- Data compression
- Prefix codes
- Optimal binary encoding
- When to Choose:
- Character frequencies known
- Minimal expected codeword length
- Prefix-free encoding needed
- Algorithm:
- Build frequency table
- Create min-heap of nodes
- Combine two smallest frequencies
- Build tree and assign codes
Kruskal's MST (Greedy)
- Time Complexity: O(E log E)
- Space Complexity: O(V)
- Key Use Cases:
- Minimum spanning tree
- Network design
- Clustering
- When to Choose:
- Sparse graphs
- Edge-based processing
- Union-find available
Prim's MST (Greedy)
- Time Complexity: O(V²) or O(E log V)
- Space Complexity: O(V)
- Key Use Cases:
- Minimum spanning tree
- Dense graphs
- Vertex-based processing
- When to Choose:
- Dense graphs
- Adjacency matrix
- Vertex expansion
Dijkstra's Algorithm (Greedy)
- Time Complexity: O((V + E) log V)
- Space Complexity: O(V)
- Key Use Cases:
- Shortest path (non-negative)
- Routing
- Network optimization
- When to Choose:
- Non-negative edge weights
- Single source
- Greedy choice (shortest known distance)
Fractional Knapsack
- Time Complexity: O(n log n) (sorting)
- Space Complexity: O(1) extra
- Key Use Cases:
- Resource allocation
- Maximizing value with weight limit
- Continuous items
- When to Choose:
- Items can be split
- Value/weight ratio matters
- Not 0/1 knapsack (needs DP)
Job Sequencing with Deadlines
- Time Complexity: O(n²) or O(n log n) with union-find
- Space Complexity: O(n)
- Key Use Cases:
- Job scheduling
- Profit maximization
- Deadline constraints
- When to Choose:
- Jobs with deadlines and profits
- One unit time per job
- Maximize total profit
Coin Change (Greedy)
- Time Complexity: O(n) where n = number of coins
- Space Complexity: O(1)
- Key Use Cases:
- Standard currency systems
- USD, EUR coin systems
- Greedy-valid denominations
- When to Choose:
- Greedy-valid currency (US, EUR)
- Not for arbitrary denominations
- Check if greedy works first
Graph Coloring (Greedy)
- Time Complexity: O(V + E)
- Space Complexity: O(V)
- Key Use Cases:
- Register allocation
- Scheduling
- Map coloring
- When to Choose:
- Approximation needed
- Order matters
- Not optimal but fast
Stable Marriage Problem (Gale-Shapley)
- Time Complexity: O(n²)
- Space Complexity: O(n²)
- Key Use Cases:
- Hospital-resident matching
- School choice
- Two-sided matching
- When to Choose:
- Two sets with preferences
- Stable matching required
- Men-optimal/women-optimal
Minimum Spanning Tree (General)
- Time Complexity: O(E log V)
- Space Complexity: O(V)
- Key Use Cases:
- Network design
- Approximation algorithms
- Clustering
- When to Choose:
- Connected, undirected graph
- Minimum total edge weight
- Greedy algorithms work
Job Scheduler (Shortest Job First)
- Time Complexity: O(n log n) (priority queue)
- Space Complexity: O(n)
- Key Use Cases:
- Process scheduling
- Batch processing
- Minimize average wait time
- When to Choose:
- Process burst times known
- Minimize average waiting time
- Non-preemptive or preemptive
Interval Scheduling (Weighted)
- Time Complexity: O(n log n) with binary search
- Space Complexity: O(n)
- Key Use Cases:
- Resource allocation with weights
- Profit maximization
- Job selection
- When to Choose:
- Weighted activities
- Non-overlapping subset
- Greedy doesn't work, use DP
related-skills: abl-v10-learning, abl-v12-learning
String Algorithms
KMP (Knuth-Morris-Pratt)
- Time Complexity: O(n + m) where n = text, m = pattern
- Space Complexity: O(m) (LPS array)
- Key Use Cases:
- Pattern matching
- DNA sequence search
- Text editors
- Security scanning
- When to Choose:
- Multiple pattern occurrences
- Pattern has repetitions
- Need linear time guarantee
- Preprocessing pattern allowed
- LPS Array:
- Longest proper prefix which is also suffix
- Avoids re-comparing characters
Rabin-Karp
- Time Complexity: O(n + m) average, O(nm) worst
- Space Complexity: O(1) (constant operations)
- Key Use Cases:
- Plagiarism detection
- Multi-pattern matching
- String hashing
- Duplicate detection
- When to Choose:
- Multiple patterns to search
- Rolling hash useful
- Average case acceptable
- Hash collisions manageable
Boyer-Moore
- Time Complexity: O(n/m * m!) worst, O(n/m) average
- Space Complexity: O(σ) where σ = alphabet size
- Key Use Cases:
- Large alphabet (ASCII, Unicode)
- Large text, small pattern
- Text editors (grep)
- Bioinformatics
- When to Choose:
- Large alphabet (letters, not just ACGT)
- Pattern near end of text
- Good heuristic behavior
- Not for small alphabet
Z-Algorithm
- Time Complexity: O(n + m)
- Space Complexity: O(n + m)
- Key Use Cases:
- Pattern matching
- String prefix matching
- String repetition detection
- Concatenation problems
- When to Choose:
- Z-array computation
- Prefix matching
- Alternative to KMP
- Suffix matching with sentinel
Manacher's Algorithm
- Time Complexity: O(n)
- Space Complexity: O(n)
- Key Use Cases:
- Longest palindromic substring
- All palindromes in string
- Palindrome density
- When to Choose:
- Linear time palindrome
-Substring (not subsequence)
- All palindromes needed
- Key Insight:
- Uses symmetry to avoid re-computation
- Expands around centers with memoization
Suffix Array
- Time Complexity: O(n log n) (sort) or O(n) (SAIS)
- Space Complexity: O(n)
- Key Use Cases:
- Pattern matching (with binary search)
- Burrows-Wheeler transform
- Data compression
- Genomics
- When to Choose:
- Multiple queries on same text
- Memory efficiency
- LCP array for additional queries
- Alternative to suffix tree
- Construction:
- Sorting all suffixes
- Radix sort for O(n)
- DC3 algorithm for O(n)
Suffix Tree (Ukkonen's)
- Time Complexity: O(n)
- Space Complexity: O(n)
- Key Use Cases:
- Fast pattern matching
- Longest repeated substring
- Substring queries
- Bioinformatics
- When to Choose:
- Single query, fast lookup
- Multiple pattern queries
- Space permits
- Complex query support
- Applications:
- Longest repeated substring
- Longest common substring
- Palindrome detection
Rolling Hash (Rabin-Karp)
- Time Complexity: O(1) per shift
- Space Complexity: O(1)
- Key Use Cases:
- Rabin-Karp
- String matching
- Duplicate detection
- Streaming
- When to Choose:
- Multiple substring hashes needed
- Window sliding
- Hash collision handling
Longest Prefix Suffix (LPS) / Failure Function
- Time Complexity: O(m)
- Space Complexity: O(m)
- Key Use Cases:
- KMP algorithm
- String border
- Periodicity detection
- When to Choose:
- KMP preprocessing
- String borders
- Pattern analysis
Boyer-Moore-Horspool
- Time Complexity: O(n) average
- Space Complexity: O(σ)
- Key Use Cases:
- Simplified Boyer-Moore
- Text search
- Binary files
- When to Choose:
- Simpler than Boyer-Moore
- Good average performance
- Fixed alphabet
Apostolico-Giancarlo
- Time Complexity: O(n) average
- Space Complexity: O(m)
- Key Use Cases:
- Speeding up KMP
- Avoiding re-comparisons
- Pattern matching
- When to Choose:
- KMP with early termination
- Memory bandwidth limited
- Large pattern
Multiple Pattern Matching (Aho-Corasick)
- Time Complexity: O(n + m + z) where z = matches
- Space Complexity: O(m * σ)
- Key Use Cases:
- Multiple keywords
- Security scanning
- Text processing
- intrusion detection
- When to Choose:
- Multiple patterns (3+)
- All occurrences needed
- Linear time in text length
- Dictionary matching
- Structure:
- Trie with failure links
- Output function
Suffix Trie
- Time Complexity: O(m) for query
- Space Complexity: O(m * σ^m) (exponential)
- Key Use Cases:
- Educational
- Small strings only
- Pattern matching
- When to Choose:
- Never for production
- Only for small m
- Understand suffix trees
Longest Repeated Substring
- Time Complexity: O(n) (suffix tree) or O(n log n) (suffix array)
- Space Complexity: O(n)
- Key Use Cases:
- Plagiarism detection
- DNA analysis
- Code duplication
- When to Choose:
- Repeat detection
- Suffix tree/array available
- Overlapping allowed or not
Longest Common Substring
- Time Complexity: O(n + m) (suffix tree) or O(nm) (DP)
- Space Complexity: O(n + m)
- Key Use Cases:
- DNA comparison
- File diff
- Code similarity
- When to Choose:
- Contiguous match
- Suffix tree/array for linear
- DP for simplicity
- DP Approach:
- Table[i][j] = length of common substring ending at i, j
- Maximum value is answer
Palindromic Tree (Eertree)
- Time Complexity: O(n)
- Space Complexity: O(n)
- Key Use Cases:
- All palindromes in string
- Palindrome counting
- Palindromic density
- When to Choose:
- All palindromes
- Online algorithm
- Memory efficient
- Structure:
- Two roots (even/odd length)
- Suffix links
- Palindromic nodes
String Matching with Wildcards
- Time Complexity: O(mn)
- Space Complexity: O(mn)
- Key Use Cases:
- Shell globbing
- File matching
- Query patterns
- When to Choose:
- Pattern with ? and *
- DP approach
- Memoization for optimization
related-skills: abl-v10-learning, abl-v12-learning
Mathematical Algorithms
Euclidean GCD
- Time Complexity: O(log min(a, b))
- Space Complexity: O(1) iterative, O(log n) recursive
- Key Use Cases:
- Simplifying fractions
- LCM calculation
- Cryptography
- Number theory
- When to Choose:
- Greatest common divisor
- Euclidean algorithm
- Binary GCD alternative for bit operations
- Extensions:
- Extended GCD (Bezout coefficients)
- Multiple number GCD
- LCM = (a * b) / GCD(a, b)
Binary Exponentiation (Fast Power)
- Time Complexity: O(log n)
- Space Complexity: O(log n) recursive, O(1) iterative
- Key Use Cases:
- Power computation
- Matrix exponentiation
- Modular exponentiation
- Fibonacci numbers
- When to Choose:
- Large exponents
- Modular arithmetic
- Matrix powers
- Exponentiation by squaring
- Variants:
- Iterative implementation
- Modular exponentiation (a^b mod m)
- Matrix exponentiation
- Fast Fibonacci (O(log n))
Sieve of Eratosthenes
- Time Complexity: O(n log log n)
- Space Complexity: O(n)
- Key Use Cases:
- Prime generation
- Primality testing
- Number theory
- Cryptography preprocessing
- When to Choose:
- Generate primes up to n
- Multiple primality tests
- Sieve is better for batch
- Optimizations:
- Sieve of Atkin (O(n / log log n))
- Segmented sieve (for large n)
- Only odd numbers
- Bitset compression
Extended Euclidean Algorithm
- Time Complexity: O(log min(a, b))
- Space Complexity: O(log n)
- Key Use Cases:
- Modular inverse
- Bezout coefficients
- Chinese Remainder Theorem
- RSA cryptography
- When to Choose:
- Find x, y such that ax + by = GCD(a, b)
- Modular inverse exists
- Linear Diophantine equations
Miller-Rabin Primality Test
- Time Complexity: O(k * log³ n) where k = iterations
- Space Complexity: O(1)
- Key Use Cases:
- Large number primality
- Cryptography
- Probabilistic testing
- BigInteger libraries
- When to Choose:
- Large numbers (100+ bits)
- Probabilistic acceptable
- Deterministic for 64-bit (specific bases)
- Deterministic:
- For n < 2^64, specific bases guarantee correctness
- Common bases: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37
Lucas-Lehmer Primality Test
- Time Complexity: O(log² p) for Mersenne number M_p
- Space Complexity: O(log p)
- Key Use Cases:
- Mersenne primes
- Large prime discovery
- GIMPS
- When to Choose:
- Mersenne numbers (2^p - 1)
- specifically for Mersenne primes
- Deterministic for Mersenne
Modular Arithmetic
- Key Operations:
- Addition: (a + b) mod m
- Multiplication: (a * b) mod m
- Division: a * mod_inverse(b, m) mod m
- Subtraction: (a - b + m) mod m
- When to Choose:
- Avoid overflow
- Cryptography
- Large number arithmetic
Fast Fourier Transform (FFT)
- Time Complexity: O(n log n)
- Space Complexity: O(n)
- Key Use Cases:
- Polynomial multiplication
- Signal processing
- Large integer multiplication
- Convolution
- When to Choose:
- Polynomial multiplication
- Convolution theorem
- Signal analysis
- Circular convolution
Karatsuba Multiplication
- Time Complexity: O(n^log₂3) ≈ O(n^1.585)
- Space Complexity: O(n)
- Key Use Cases:
- Large integer multiplication
…(truncated)
1---2name: algorithms3description: related-skills: abl-v10-learning, abl-v12-learning4---56789 related-skills: abl-v10-learning, abl-v12-learning101112# Skill: programming-algorithms1314# Programming Algorithms: A Comprehensive Guide for Algorithm Selection1516**Role:** Senior Algorithm Engineer — select, implement, and optimize algorithms for problem-solving across domains.1718**Philosophy:** Algorithmic Precision — choose the right tool for the job based on time/space trade-offs, input characteristics, and problem constraints. No fabrication — leverage established, proven algorithms.1920## Purpose: Why Standard Algorithms2122**The Problem with Fabrication:**23- Reinventing algorithms introduces bugs and suboptimal solutions24- Standard algorithms have decades of academic analysis and optimization25- Edge cases are already understood and handled26- Performance characteristics are well-documented2728**When to Use Standard Algorithms:**291. Problem matches a known pattern (sorting, shortest path, etc.)302. Input size suggests complexity constraints313. Resource limits (time/space) are known324. Industry standards exist for the domain3334**Key Principles:**35- **Trade-offs are inevitable:** Time vs space, simplicity vs performance36- **Context matters:** Input size, distribution, and constraints dictate choices37- **Proof first, optimize later:** Ensure correctness before micro-optimizations3839---40 related-skills: abl-v10-learning, abl-v12-learning4142## Table of Contents43441. [Sorting Algorithms](#sorting-algorithms)452. [Searching Algorithms](#searching-algorithms)463. [Graph Algorithms](#graph-algorithms)474. [Dynamic Programming](#dynamic-programming)485. [Greedy Algorithms](#greedy-algorithms)496. [String Algorithms](#string-algorithms)507. [Mathematical Algorithms](#mathematical-algorithms)518. [Geometric Algorithms](#geometric-algorithms)529. [Backtracking Algorithms](#backtracking-algorithms)5310. [Numerical Algorithms](#numerical-algorithms)5411. [Probabilistic Algorithms](#probabilistic-algorithms)5512. [Streaming Algorithms](#streaming-algorithms)5613. [Algorithm Selection Guide](#algorithm-selection-guide)5758---59 related-skills: abl-v10-learning, abl-v12-learning6061## Sorting Algorithms6263### Quick Sort64- **Alternative Names:** Partition-exchange sort65- **Time Complexity:** 66 - Best: O(n log n) (balanced partitions)67 - Average: O(n log n)68 - Worst: O(n²) (poor pivot selection)69- **Space Complexity:** O(log n) (recursion stack)70- **Key Use Cases:**71 - General-purpose sorting when cache locality matters72 - In-place sorting with minimal memory overhead73 - Average-case optimal for random data74- **When to Choose:**75 - Data is randomly distributed76 - Memory is constrained (in-place)77 - Average performance matters more than worst-case guarantee78 - Not suitable for linked lists or nearly-sorted data79- **Optimizations:**80 - Use median-of-three pivot selection81 - Switch to insertion sort for small partitions (n < 10-20)82 - Iterative implementation to avoid stack overflow8384### Merge Sort85- **Alternative Names:** Mergesort86- **Time Complexity:** 87 - Best: O(n log n)88 - Average: O(n log n)89 - Worst: O(n log n)90- **Space Complexity:** O(n) (temporary arrays)91- **Key Use Cases:**92 - Linked list sorting93 - External sorting (files too large for memory)94 - Stable sorting required95 - Parallel processing (tasks are independent)96- **When to Choose:**97 - Stability is required (equal elements maintain order)98 - Sorting linked lists (O(1) extra space)99 - External sorting with disk I/O100 - Predictable performance needed101- **Optimizations:**102 - Bottom-up (iterative) implementation103 - Use insertion sort for small subarrays104 - Parallel merge sort for multi-core systems105106### Heap Sort107- **Alternative Names:** Heap sorting108- **Time Complexity:** 109 - Best: O(n log n)110 - Average: O(n log n)111 - Worst: O(n log n)112- **Space Complexity:** O(1) (in-place)113- **Key Use Cases:**114 - In-place sorting with guaranteed O(n log n) performance115 - Priority queue implementation116 - Finding top-k elements (use min-heap of size k)117 - Memory-constrained environments118- **When to Choose:**119 - Worst-case performance guarantee needed120 - Memory is extremely constrained121 - Building priority queues122 - Not suitable for nearly-sorted data (no early exit)123- **Optimizations:**124 - Build heap in O(n) time (Floyd's algorithm)125 - Use binary heap for arrays, binomial heap for decreases126127### Radix Sort128- **Alternative Names:** Bucket sort (for integers), LSD radix sort129- **Time Complexity:** 130 - Best: O(nk)131 - Average: O(nk)132 - Worst: O(nk)133 - Where k = number of digits/characters134- **Space Complexity:** O(n + k) (buckets)135- **Key Use Cases:**136 - Sorting integers with fixed width137 - Sorting strings by characters138 - Stable sorting for digit-by-digit processing139 - When k is small relative to n140- **When to Choose:**141 - Integers with bounded range142 - Strings with fixed maximum length143 - Need stable sorting144 - k is O(1) or very small145 - Not suitable for floating-point or large k values146- **Optimizations:**147 - MSD (Most Significant Digit) for string sorting148 - LSD (Least Significant Digit) for fixed-width integers149 - Use counting sort as stable subroutine150151### Bucket Sort152- **Alternative Names:** Bin sort153- **Time Complexity:** 154 - Best: O(n + k) (uniform distribution)155 - Average: O(n + k)156 - Worst: O(n²) (all elements in one bucket)157- **Space Complexity:** O(nk) (buckets)158- **Key Use Cases:**159 - Uniformly distributed floating-point numbers160 - Sorting data that can be partitioned into ranges161 - Database partitioning162 - Parallel processing (independent buckets)163- **When to Choose:**164 - Input is uniformly distributed over a range165 - Can create appropriate number of buckets166 - Parallel sorting allowed167 - Not suitable for skewed distributions168169### Insertion Sort170- **Time Complexity:** 171 - Best: O(n) (already sorted)172 - Average: O(n²)173 - Worst: O(n²)174- **Space Complexity:** O(1) (in-place)175- **Key Use Cases:**176 - Nearly-sorted data177 - Small datasets (n < 20)178 - Online algorithms (inserting elements one at a time)179 - Subroutine for hybrid algorithms180- **When to Choose:**181 - Small input sizes (often used as base case)182 - Data is already partially sorted183 - Online sorting (streaming input)184 - Minimal memory overhead required185186### Bubble Sort187- **Time Complexity:** 188 - Best: O(n) (optimized with swapped flag)189 - Average: O(n²)190 - Worst: O(n²)191- **Space Complexity:** O(1) (in-place)192- **Key Use Cases:**193 - Educational demonstrations194 - Detecting nearly-sorted data195 - Small datasets with few swaps needed196- **When to Choose:**197 - Almost never for production (except teaching)198 - Detect if data is already sorted (O(n))199 - Very small datasets where simplicity matters200201### Selection Sort202- **Time Complexity:** 203 - Best: O(n²)204 - Average: O(n²)205 - Worst: O(n²)206- **Space Complexity:** O(1) (in-place)207- **Key Use Cases:**208 - Minimizing number of swaps209 - Small datasets where swaps are expensive210 - Educational demonstrations211- **When to Choose:**212 - Memory writes are costly (minimize to n swaps)213 - Small datasets214 - Never for large datasets215216### Shell Sort217- **Alternative Names:** Shell's method218- **Time Complexity:** 219 - Best: O(n log² n)220 - Average: O(n log² n) to O(n^(3/2))221 - Worst: O(n²)222- **Space Complexity:** O(1) (in-place)223- **Key Use Cases:**224 - Middle ground between O(n²) and O(n log n)225 - When quick sort/merge sort are too complex226 - Embedded systems with limited resources227- **When to Choose:**228 - Need better than O(n²) without complexity of O(n log n)229 - Memory-constrained but need better performance230231---232 related-skills: abl-v10-learning, abl-v12-learning233234## Searching Algorithms235236### Binary Search237- **Alternative Names:** Half-interval search, logarithmic search238- **Time Complexity:** 239 - Best: O(1)240 - Average: O(log n)241 - Worst: O(log n)242- **Space Complexity:** O(1) iterative, O(log n) recursive243- **Key Use Cases:**244 - Finding elements in sorted arrays245 - Finding first/last occurrence246 - Finding minimum/maximum in bitonic/unimodal functions247 - Floating-point binary search (precision search)248- **When to Choose:**249 - Data is sorted or can be sorted250 - Need O(log n) lookup time251 - Static data (not frequently updated)252 - Not suitable for unsorted or frequently changing data253- **Variants:**254 - Lower bound / Upper bound (first ≥ / first >)255 - Rotated array search256 - 2D matrix search (row-wise and column-wise sorted)257 - Real number binary search (for precision)258259### Interpolation Search260- **Time Complexity:** 261 - Best: O(log log n) (uniform distribution)262 - Average: O(log log n)263 - Worst: O(n) (non-uniform distribution)264- **Space Complexity:** O(1)265- **Key Use Cases:**266 - Uniformly distributed sorted data267 - Large datasets with known distribution268 - Numeric data with continuous values269- **When to Choose:**270 - Data is uniformly distributed271 - Data is sorted and large272 - Not suitable for sparse or non-uniform data273274### Exponential Search275- **Alternative Names:** Galloping search, doubling search276- **Time Complexity:** 277 - Best: O(1)278 - Average: O(log i)279 - Worst: O(log i)280 - Where i is the position of the element281- **Space Complexity:** O(1)282- **Key Use Cases:**283 - Unbounded/infinite sorted arrays284 - Finding element position for binary search285 - When element might be near the beginning286- **When to Choose:**287 - Sorted array but size unknown288 - Element likely near start289 - As preprocessing for binary search290291### Linear Search292- **Time Complexity:** 293 - Best: O(1)294 - Average: O(n)295 - Worst: O(n)296- **Space Complexity:** O(1)297- **Key Use Cases:**298 - Unsorted data299 - Small datasets300 - Single search (sorting not worth it)301 - Linked lists302- **When to Choose:**303 - Data is unsorted304 - Small n where O(n) is acceptable305 - Single search on large dataset306307### Ternary Search308- **Time Complexity:** 309 - Best: O(1)310 - Average: O(log n)311 - Worst: O(log n)312- **Space Complexity:** O(1)313- **Key Use Cases:**314 - Finding minimum/maximum of unimodal function315 - Convex/concave functions316 - Golden section search alternative317- **When to Choose:**318 - Optimization of unimodal functions319 - When binary search doesn't apply320 - Compare with golden section search321322### Jump Search323- **Alternative Names:** Block search324- **Time Complexity:** 325 - Best: O(1)326 - Average: O(√n)327 - Worst: O(√n)328- **Space Complexity:** O(1)329- **Key Use Cases:**330 - Sorted data where jumping back is expensive331 - Large datasets on disk332 - Intermediate between linear and binary search333- **When to Choose:**334 - Jumping back is costly (disk seeks)335 - O(√n) is acceptable336337---338 related-skills: abl-v10-learning, abl-v12-learning339340## Graph Algorithms341342### Breadth-First Search (BFS)343- **Time Complexity:** O(V + E)344- **Space Complexity:** O(V) (queue)345- **Key Use Cases:**346 - Shortest path in unweighted graphs347 - Level-order traversal348 - Connected components349 - Bipartite checking350 - Web crawling351- **When to Choose:**352 - Unweighted shortest path353 - Need all nodes at distance k354 - Flow networks (Ford-Fulkerson)355 - Social network analysis356357### Depth-First Search (DFS)358- **Time Complexity:** O(V + E)359- **Space Complexity:** O(V) (recursion stack)360- **Key Use Cases:**361 - Topological sorting362 - Cycle detection363 - Strongly connected components364 - Maze solving365 - Path finding366- **When to Choose:**367 - Need to explore all paths368 - Stack-based iteration369 - Topological sort370 - Tarjan's SCC algorithm371- **Variants:**372 - Iterative DFS (explicit stack)373 - DFS with parent tracking374 - DFS forest (multiple components)375376### Dijkstra's Algorithm377- **Alternative Names:** Dijkstra's shortest path378- **Time Complexity:** 379 - O(V²) (naive)380 - O((V + E) log V) (with priority queue)381 - O(V log V + E) (Fibonacci heap)382- **Space Complexity:** O(V)383- **Key Use Cases:**384 - Single-source shortest path (non-negative weights)385 - Routing protocols386 - GPS navigation387 - Network optimization388- **When to Choose:**389 - Non-negative edge weights390 - Single source to all destinations391 - Need exact shortest path392 - Not suitable for negative weights393- **Optimizations:**394 - Use Fibonacci heap for O(V log V + E)395 - Early termination when target reached396 - Bidirectional Dijkstra for source-target397398### Bellman-Ford Algorithm399- **Time Complexity:** O(VE)400- **Space Complexity:** O(V)401- **Key Use Cases:**402 - Single-source shortest path with negative weights403 - Negative cycle detection404 - Distributed routing405 - Linear programming406- **When to Choose:**407 - Graph may have negative edge weights408 - Need negative cycle detection409 - Distributed systems410 - Not suitable for dense graphs (too slow)411412### Floyd-Warshall Algorithm413- **Alternative Names:** Floyd's algorithm, Roy-Warshall414- **Time Complexity:** O(V³)415- **Space Complexity:** O(V²)416- **Key Use Cases:**417 - All-pairs shortest path418 - Transitive closure419 - Negative cycle detection420 - Density graphs421- **When to Choose:**422 - Need all-pairs shortest paths423 - Graph is dense (V³ acceptable)424 - Small V (V < 200-500)425 - Transitive closure needed426- **Optimizations:**427 - Use only when V is small428 - Can detect negative cycles429430### Kruskal's Algorithm431- **Alternative Names:** Minimum spanning tree (Kruskal)432- **Time Complexity:** O(E log E) or O(E log V)433- **Space Complexity:** O(V) (disjoint set)434- **Key Use Cases:**435 - Minimum spanning tree436 - Network design437 - Approximation algorithms438 - Clustering439- **When to Choose:**440 - Sparse graphs441 - Need MST442 - Edge-based processing443 - Disjoint set data structure available444- **Optimizations:**445 - Union by rank + path compression446 - Pre-sort edges447448### Prim's Algorithm449- **Time Complexity:** 450 - O(V²) (naive)451 - O((V + E) log V) (priority queue)452 - O(E + V log V) (Fibonacci heap)453- **Space Complexity:** O(V)454- **Key Use Cases:**455 - Minimum spanning tree456 - Dense graphs457 - Network design458 - Image segmentation459- **When to Choose:**460 - Dense graphs (more edges)461 - Need MST462 - Vertex-based processing463 - Adjacency matrix available464- **Comparison with Kruskal:**465 - Kruskal better for sparse466 - Prim better for dense467468### Topological Sort469- **Time Complexity:** O(V + E)470- **Space Complexity:** O(V)471- **Key Use Cases:**472 - Dependency resolution473 - Course scheduling474 - Build systems475 - Job scheduling476- **When to Choose:**477 - Directed acyclic graph (DAG)478 - Need linear ordering479 - Dependency ordering required480 - Cycle detection (if not DAG)481- **Methods:**482 - DFS-based (post-order)483 - Kahn's algorithm (BFS with in-degrees)484485### A* Search Algorithm486- **Time Complexity:** O(b^d) worst case (where b = branching, d = depth)487- **Space Complexity:** O(b^d)488- **Key Use Cases:**489 - Heuristic path finding490 - Game AI491 - Robotics492 - Puzzle solving493- **When to Choose:**494 - Need shortest path with heuristic495 - Admissible heuristic available496 - Want to reduce search space497 - Not suitable without good heuristic498- **Heuristic Requirements:**499 - Admissible (never overestimates)500 - Consistent (triangle inequality)501- **Variants:**502 -IDA* (Iterative Deepening A*)503 - SMA* (Simplified Memory-Bounded A*)504505### Tarjan's SCC Algorithm506- **Time Complexity:** O(V + E)507- **Space Complexity:** O(V)508- **Key Use Cases:**509 - Strongly connected components510 - Graph condensation511 - Dependency analysis512 - Circuit simulation513- **When to Choose:**514 - Find SCCs in directed graph515 - Graph condensation needed516 - Cycle analysis517 - Topological sort on SCCs518519### Johnson's Algorithm520- **Time Complexity:** O(V² log V + VE)521- **Space Complexity:** O(V²)522- **Key Use Cases:**523 - All-pairs shortest path (sparse graphs)524 - Graphs with negative weights525- **When to Choose:**526 - Sparse graphs, all-pairs shortest path527 - Negative weights allowed528 - Better than Floyd-Warshall for sparse529530### Chinese Postman Problem531- **Time Complexity:** O(V² log V + E) for undirected532- **Space Complexity:** O(V²)533- **Key Use Cases:**534 - Route optimization (mail carrier)535 - Circuit board inspection536 - Street cleaning537- **When to Choose:**538 - Need to traverse all edges539 - Minimize total distance540 - Graph may have odd-degree vertices541542### Traveling Salesman Problem (Approximations)543- **Time Complexity:** Varies by heuristic544- **Space Complexity:** O(V²)545- **Key Use Cases:**546 - Route optimization547 - Logistics548 - Manufacturing (drill positioning)549- **Heuristics:**550 - Nearest neighbor: O(V²)551 - Christofides: O(V³) (3/2 approximation)552 - Simulated annealing553 - Genetic algorithms554- **When to Choose:**555 - NP-hard problem, need approximation556 - Real-world constraints557 - Exact solution not required558559### Minimum Cut (Stoer-Wagner)560- **Time Complexity:** O(V³) or O(VE + V² log V)561- **Space Complexity:** O(V²)562- **Key Use Cases:**563 - Network reliability564 - Image segmentation565 - Clustering566- **When to Choose:**567 - Find minimum edge cut568 - Graph partitioning569 - No source-sink constraint570571### Maximum Flow (Ford-Fulkerson)572- **Time Complexity:** O(E * max_flow) (integer capacities)573- **Space Complexity:** O(V + E)574- **Key Use Cases:**575 - Network flow576 - Bipartite matching577 - Image segmentation578 - transportation problems579- **When to Choose:**580 - Flow network optimization581 - Matching problems582 - Integer capacities583- **Variants:**584 - Edmonds-Karp: O(VE²) (BFS)585 - Dinic's: O(V²E) (level graph)586 - Push-relabel: O(V²E) (more efficient in practice)587588### Hopcroft-Karp Algorithm589- **Time Complexity:** O(E * √V)590- **Space Complexity:** O(V)591- **Key Use Cases:**592 - Maximum bipartite matching593 - Assignment problems594 - Job scheduling595- **When to Choose:**596 - Bipartite graph matching597 - Better than Ford-Fulkerson for bipartite598 - Sparse graphs599600### Max-Flow Min-Cut Theorem Applications601- **Time Complexity:** Same as underlying max-flow algorithm602- **Key Use Cases:**603 - Image segmentation (graph cuts)604 - Computer vision605 - Parallel computing606 - VLSI design607608---609 related-skills: abl-v10-learning, abl-v12-learning610611## Dynamic Programming612613### 0/1 Knapsack Problem614- **Time Complexity:** O(nW) where W = capacity615- **Space Complexity:** O(nW) or O(W) (optimized)616- **Key Use Cases:**617 - Resource allocation618 - Investment portfolio619 - Container packing620 - Knapsack variations621- **When to Choose:**622 - Items can only be taken once623 - Capacity constraint624 - Optimal substructure exists625- **Variants:**626 - Unbounded knapsack (unlimited items)627 - Bounded knapsack (limited quantities)628 - Multiple knapsack629 - Fractional knapsack (greedy, not DP)630- **Optimizations:**631 - Space optimization (1D array)632 - Pruning based on bounds633 - Meet-in-the-middle for large n634635### Longest Common Subsequence (LCS)636- **Time Complexity:** O(mn) where m, n = string lengths637- **Space Complexity:** O(mn) or O(min(m, n))638- **Key Use Cases:**639 - Diff utilities640 - Bioinformatics (DNA matching)641 - Version control642 - Plagiarism detection643- **When to Choose:**644 - Two sequences common subsequence645 - Order matters, continuity not required646 - Not suitable for substring (use KMP/Rabin-Karp)647- **Reconstruction:**648 - Track decisions during DP649 - Backtrack to build actual LCS650- **Optimizations:**651 - Hirschberg's algorithm: O(min(m,n)) space652 - Early termination if no match653654### Longest Increasing Subsequence (LIS)655- **Time Complexity:** O(n²) (DP) or O(n log n) (patience sorting)656- **Space Complexity:** O(n)657- **Key Use Cases:**658 - Pattern recognition659 - Stock market analysis660 - Bioinformatics661 - Data smoothing662- **When to Choose:**663 - Strictly increasing (or non-decreasing)664 - Need longest monotonic subsequence665- **O(n log n) Method:**666 - Maintain active lists667 - Binary search for insertion668 - Track predecessors for reconstruction669- **Variants:**670 - Longest decreasing subsequence671 - Bitonic subsequence672 - Circular variant673674### Matrix Chain Multiplication675- **Time Complexity:** O(n³)676- **Space Complexity:** O(n²)677- **Key Use Cases:**678 - Optimal parenthesization679 - Compiler optimization680 - Dynamic programming example681- **When to Choose:**682 - Matrix multiplication order683 - Minimize scalar multiplications684 - All matrices compatible685- **Optimizations:**686 - Store optimal split points687 - Reconstruction for actual multiplication order688689### Edit Distance (Levenshtein)690- **Time Complexity:** O(mn)691- **Space Complexity:** O(mn) or O(min(m,n))692- **Key Use Cases:**693 - Spell checking694 - DNA sequence alignment695 - Fuzzy string matching696 - Version control697- **When to Choose:**698 - Minimum edits to transform string A to B699 - Insert, delete, replace operations700- **Variants:**701 - Hamming distance (same length, replace only)702 - Damerau-Levenshtein (adjacent swap)703 - Wagner-Fischer (generalization)704- **Optimizations:**705 - Space optimization706 - Early termination for small distances707708### Coin Change Problem709- **Time Complexity:** O(n * amount) where n = coin types710- **Space Complexity:** O(amount)711- **Key Use Cases:**712 - Making change (min coins)713 - Combinatorial counting714 - Resource allocation715- **When to Choose:**716 - Minimize number of coins717 - Count ways to make amount718 - DP applies (optimal substructure)719- **Variants:**720 - Minimum coins (0/1 or unlimited)721 - Count combinations722 - With limited coins723 - Greedy doesn't always work724725### Subset Sum Problem726- **Time Complexity:** O(n * sum) or O(n * 2^(n/2)) (meet-in-middle)727- **Space Complexity:** O(n * sum)728- **Key Use Cases:**729 - Scheduling730 - Resource allocation731 - Cryptography732 - NP-complete problems733- **When to Choose:**734 - Find subset with given sum735 - Decision problem (existential)736 - Optimization variant exists737- **Optimizations:**738 - Meet-in-the-middle for large n739 - Bitset optimization740 - Pseudo-polynomial DP741742### Traveling Salesman Problem (Dynamic Programming)743- **Time Complexity:** O(n² * 2^n)744- **Space Complexity:** O(n * 2^n)745- **Key Use Cases:**746 - Exact TSP for small n747 - Algorithm comparison748 - Benchmarking749- **When to Choose:**750 - n < 20-25751 - Need exact solution752 - Not suitable for large n753- **Held-Karp Algorithm:**754 - DP with bitmask755 - Track visited set and last city756757### Partition Problem758- **Time Complexity:** O(n * sum)759- **Space Complexity:** O(sum)760- **Key Use Cases:**761 - Fair division762 - Load balancing763 - NP-complete problems764- **When to Choose:**765 - Split into equal-sum subsets766 - Decision variant767 - Optimization (minimize difference)768769### Longest Palindromic Subsequence770- **Time Complexity:** O(n²)771- **Space Complexity:** O(n²)772- **Key Use Cases:**773 - Palindrome analysis774 - Bioinformatics775 - String algorithms776- **When to Choose:**777 - Find longest palindromic subsequence778 - Not substring (LPS can skip chars)779- **Variants:**780 - Longest palindromic substring (manacher's O(n))781 - Minimum deletions to make palindrome782783### Word Break Problem784- **Time Complexity:** O(n²) with dictionary lookup785- **Space Complexity:** O(n)786- **Key Use Cases:**787 - Text segmentation788 - Dictionary matching789 - Natural language processing790- **When to Choose:**791 - Can string be segmented into dictionary words?792 - Count all possible segmentations793- **Optimizations:**794 - Trie for dictionary lookup795 - Memoization796 - Early termination797798### Wildcard Pattern Matching799- **Time Complexity:** O(mn)800- **Space Complexity:** O(mn) or O(min(m,n))801- **Key Use Cases:**802 - Regex matching803 - File pattern matching804 - Text processing805- **When to Choose:**806 - Pattern with ? and * wildcards807 - Match against text808- **Variants:**809 - Regex with character classes810 - Case sensitivity811 - Multiline support812813### Unique Paths814- **Time Complexity:** O(mn)815- **Space Complexity:** O(mn) or O(min(m,n))816- **Key Use Cases:**817 - Grid path counting818 - Combinatorics819 - Robot motion planning820- **When to Choose:**821 - Grid with obstacles822 - Count paths from top-left to bottom-right823 - Only right/down moves allowed824- **Variants:**825 - With obstacles (grid[i][j] = 1 blocked)826 - With costs (minimum cost path)827 - With forbidden cells828829### Egg Dropping Puzzle830- **Time Complexity:** O(n * k²) or O(n * log k)831- **Space Complexity:** O(nk)832- **Key Use Cases:**833 - Testing/quality assurance834 - Optimization under uncertainty835 - Decision theory836- **When to Choose:**837 - Minimize trials to find critical floor838 - k eggs, n floors839 - Binary search when 2 eggs840841### Catalan Numbers Applications842- **Time Complexity:** O(n²) for DP, O(n) for formula843- **Space Complexity:** O(n)844- **Key Use Cases:**845 - Parentheses matching846 - Binary tree counting847 - Polygon triangulation848 - Dyck paths849- **When to Choose:**850 - Problems with Catalan structure851 - Combinatorial counting852 - Recursive structure853- **Applications:**854 - n pairs of valid parentheses855 - n+1 leaves in full binary tree856 - n×n grid monotonic paths857 - Convex polygon triangulation858859### Optimal Binary Search Tree860- **Time Complexity:** O(n³)861- **Space Complexity:** O(n²)862- **Key Use Cases:**863 - Compiler design864 - Database indexing865 - Optimal search structure866- **When to Choose:**867 - Given probabilities, build optimal BST868 - Minimize search cost869 - Static search set870- **Optimizations:**871 - Knuth's optimization (if quadrangle inequality)872 - O(n²) with Knuth optimization873874### Bitmask DP Applications875- **Time Complexity:** O(n * 2^n) or O(m * 3^(n/2))876- **Space Complexity:** O(2^n)877- **Key Use Cases:**878 - Subset problems879 - Graph problems (TSP, Hamiltonian)880 - Set cover881- **When to Choose:**882 - n < 20-25883 - Subsets or states can be encoded as bitmask884 - State space is 2^n885886### DP on Trees887- **Time Complexity:** O(V) for simple, O(V * k²) for k-state888- **Space Complexity:** O(V)889- **Key Use Cases:**890 - Tree diameter891 - Tree center892 - Tree coloring893 - Tree independence894- **When to Choose:**895 - Tree structure896 - Root the tree arbitrarily897 - Combine children's results898- **Common Patterns:**899 - Tree diameter (two DFS)900 - Tree center (eccentricity)901 - Tree isomorphism902 - Tree knapsack903904### DP with Bitwise Operations905- **Time Complexity:** Varies906- **Space Complexity:** Varies907- **Key Use Cases:**908 - Subset XOR sums909 - Bit manipulation problems910 - State compression911- **When to Choose:**912 - Bitwise operations on subsets913 - XOR-based problems914 - Bitmask DP915916---917 related-skills: abl-v10-learning, abl-v12-learning918919## Greedy Algorithms920921### Activity Selection Problem922- **Time Complexity:** O(n log n) (sorting) or O(n) (if sorted)923- **Space Complexity:** O(1) extra924- **Key Use Cases:**925 - Scheduling resources926 - Meeting room allocation927 - Single-resource scheduling928- **When to Choose:**929 - Select maximum non-overlapping activities930 - Greedy choice works (earliest finish time)931 - Not for weighted activities (need DP)932933### Huffman Coding934- **Time Complexity:** O(n log n) (priority queue)935- **Space Complexity:** O(n)936- **Key Use Cases:**937 - Data compression938 - Prefix codes939 - Optimal binary encoding940- **When to Choose:**941 - Character frequencies known942 - Minimal expected codeword length943 - Prefix-free encoding needed944- **Algorithm:**945 - Build frequency table946 - Create min-heap of nodes947 - Combine two smallest frequencies948 - Build tree and assign codes949950### Kruskal's MST (Greedy)951- **Time Complexity:** O(E log E)952- **Space Complexity:** O(V)953- **Key Use Cases:**954 - Minimum spanning tree955 - Network design956 - Clustering957- **When to Choose:**958 - Sparse graphs959 - Edge-based processing960 - Union-find available961962### Prim's MST (Greedy)963- **Time Complexity:** O(V²) or O(E log V)964- **Space Complexity:** O(V)965- **Key Use Cases:**966 - Minimum spanning tree967 - Dense graphs968 - Vertex-based processing969- **When to Choose:**970 - Dense graphs971 - Adjacency matrix972 - Vertex expansion973974### Dijkstra's Algorithm (Greedy)975- **Time Complexity:** O((V + E) log V)976- **Space Complexity:** O(V)977- **Key Use Cases:**978 - Shortest path (non-negative)979 - Routing980 - Network optimization981- **When to Choose:**982 - Non-negative edge weights983 - Single source984 - Greedy choice (shortest known distance)985986### Fractional Knapsack987- **Time Complexity:** O(n log n) (sorting)988- **Space Complexity:** O(1) extra989- **Key Use Cases:**990 - Resource allocation991 - Maximizing value with weight limit992 - Continuous items993- **When to Choose:**994 - Items can be split995 - Value/weight ratio matters996 - Not 0/1 knapsack (needs DP)997998### Job Sequencing with Deadlines999- **Time Complexity:** O(n²) or O(n log n) with union-find1000- **Space Complexity:** O(n)1001- **Key Use Cases:**1002 - Job scheduling1003 - Profit maximization1004 - Deadline constraints1005- **When to Choose:**1006 - Jobs with deadlines and profits1007 - One unit time per job1008 - Maximize total profit10091010### Coin Change (Greedy)1011- **Time Complexity:** O(n) where n = number of coins1012- **Space Complexity:** O(1)1013- **Key Use Cases:**1014 - Standard currency systems1015 - USD, EUR coin systems1016 - Greedy-valid denominations1017- **When to Choose:**1018 - Greedy-valid currency (US, EUR)1019 - Not for arbitrary denominations1020 - Check if greedy works first10211022### Graph Coloring (Greedy)1023- **Time Complexity:** O(V + E)1024- **Space Complexity:** O(V)1025- **Key Use Cases:**1026 - Register allocation1027 - Scheduling1028 - Map coloring1029- **When to Choose:**1030 - Approximation needed1031 - Order matters1032 - Not optimal but fast10331034### Stable Marriage Problem (Gale-Shapley)1035- **Time Complexity:** O(n²)1036- **Space Complexity:** O(n²)1037- **Key Use Cases:**1038 - Hospital-resident matching1039 - School choice1040 - Two-sided matching1041- **When to Choose:**1042 - Two sets with preferences1043 - Stable matching required1044 - Men-optimal/women-optimal10451046### Minimum Spanning Tree (General)1047- **Time Complexity:** O(E log V)1048- **Space Complexity:** O(V)1049- **Key Use Cases:**1050 - Network design1051 - Approximation algorithms1052 - Clustering1053- **When to Choose:**1054 - Connected, undirected graph1055 - Minimum total edge weight1056 - Greedy algorithms work10571058### Job Scheduler (Shortest Job First)1059- **Time Complexity:** O(n log n) (priority queue)1060- **Space Complexity:** O(n)1061- **Key Use Cases:**1062 - Process scheduling1063 - Batch processing1064 - Minimize average wait time1065- **When to Choose:**1066 - Process burst times known1067 - Minimize average waiting time1068 - Non-preemptive or preemptive10691070### Interval Scheduling (Weighted)1071- **Time Complexity:** O(n log n) with binary search1072- **Space Complexity:** O(n)1073- **Key Use Cases:**1074 - Resource allocation with weights1075 - Profit maximization1076 - Job selection1077- **When to Choose:**1078 - Weighted activities1079 - Non-overlapping subset1080 - Greedy doesn't work, use DP10811082---1083 related-skills: abl-v10-learning, abl-v12-learning10841085## String Algorithms10861087### KMP (Knuth-Morris-Pratt)1088- **Time Complexity:** O(n + m) where n = text, m = pattern1089- **Space Complexity:** O(m) (LPS array)1090- **Key Use Cases:**1091 - Pattern matching1092 - DNA sequence search1093 - Text editors1094 - Security scanning1095- **When to Choose:**1096 - Multiple pattern occurrences1097 - Pattern has repetitions1098 - Need linear time guarantee1099 - Preprocessing pattern allowed1100- **LPS Array:**1101 - Longest proper prefix which is also suffix1102 - Avoids re-comparing characters11031104### Rabin-Karp1105- **Time Complexity:** O(n + m) average, O(nm) worst1106- **Space Complexity:** O(1) (constant operations)1107- **Key Use Cases:**1108 - Plagiarism detection1109 - Multi-pattern matching1110 - String hashing1111 - Duplicate detection1112- **When to Choose:**1113 - Multiple patterns to search1114 - Rolling hash useful1115 - Average case acceptable1116 - Hash collisions manageable11171118### Boyer-Moore1119- **Time Complexity:** O(n/m * m!) worst, O(n/m) average1120- **Space Complexity:** O(σ) where σ = alphabet size1121- **Key Use Cases:**1122 - Large alphabet (ASCII, Unicode)1123 - Large text, small pattern1124 - Text editors (grep)1125 - Bioinformatics1126- **When to Choose:**1127 - Large alphabet (letters, not just ACGT)1128 - Pattern near end of text1129 - Good heuristic behavior1130 - Not for small alphabet11311132### Z-Algorithm1133- **Time Complexity:** O(n + m)1134- **Space Complexity:** O(n + m)1135- **Key Use Cases:**1136 - Pattern matching1137 - String prefix matching1138 - String repetition detection1139 - Concatenation problems1140- **When to Choose:**1141 - Z-array computation1142 - Prefix matching1143 - Alternative to KMP1144 - Suffix matching with sentinel11451146### Manacher's Algorithm1147- **Time Complexity:** O(n)1148- **Space Complexity:** O(n)1149- **Key Use Cases:**1150 - Longest palindromic substring1151 - All palindromes in string1152 - Palindrome density1153- **When to Choose:**1154 - Linear time palindrome1155 -Substring (not subsequence)1156 - All palindromes needed1157- **Key Insight:**1158 - Uses symmetry to avoid re-computation1159 - Expands around centers with memoization11601161### Suffix Array1162- **Time Complexity:** O(n log n) (sort) or O(n) (SAIS)1163- **Space Complexity:** O(n)1164- **Key Use Cases:**1165 - Pattern matching (with binary search)1166 - Burrows-Wheeler transform1167 - Data compression1168 - Genomics1169- **When to Choose:**1170 - Multiple queries on same text1171 - Memory efficiency1172 - LCP array for additional queries1173 - Alternative to suffix tree1174- **Construction:**1175 - Sorting all suffixes1176 - Radix sort for O(n)1177 - DC3 algorithm for O(n)11781179### Suffix Tree (Ukkonen's)1180- **Time Complexity:** O(n)1181- **Space Complexity:** O(n)1182- **Key Use Cases:**1183 - Fast pattern matching1184 - Longest repeated substring1185 - Substring queries1186 - Bioinformatics1187- **When to Choose:**1188 - Single query, fast lookup1189 - Multiple pattern queries1190 - Space permits1191 - Complex query support1192- **Applications:**1193 - Longest repeated substring1194 - Longest common substring1195 - Palindrome detection11961197### Rolling Hash (Rabin-Karp)1198- **Time Complexity:** O(1) per shift1199- **Space Complexity:** O(1)1200- **Key Use Cases:**1201 - Rabin-Karp1202 - String matching1203 - Duplicate detection1204 - Streaming1205- **When to Choose:**1206 - Multiple substring hashes needed1207 - Window sliding1208 - Hash collision handling12091210### Longest Prefix Suffix (LPS) / Failure Function1211- **Time Complexity:** O(m)1212- **Space Complexity:** O(m)1213- **Key Use Cases:**1214 - KMP algorithm1215 - String border1216 - Periodicity detection1217- **When to Choose:**1218 - KMP preprocessing1219 - String borders1220 - Pattern analysis12211222### Boyer-Moore-Horspool1223- **Time Complexity:** O(n) average1224- **Space Complexity:** O(σ)1225- **Key Use Cases:**1226 - Simplified Boyer-Moore1227 - Text search1228 - Binary files1229- **When to Choose:**1230 - Simpler than Boyer-Moore1231 - Good average performance1232 - Fixed alphabet12331234### Apostolico-Giancarlo1235- **Time Complexity:** O(n) average1236- **Space Complexity:** O(m)1237- **Key Use Cases:**1238 - Speeding up KMP1239 - Avoiding re-comparisons1240 - Pattern matching1241- **When to Choose:**1242 - KMP with early termination1243 - Memory bandwidth limited1244 - Large pattern12451246### Multiple Pattern Matching (Aho-Corasick)1247- **Time Complexity:** O(n + m + z) where z = matches1248- **Space Complexity:** O(m * σ)1249- **Key Use Cases:**1250 - Multiple keywords1251 - Security scanning1252 - Text processing1253 - intrusion detection1254- **When to Choose:**1255 - Multiple patterns (3+)1256 - All occurrences needed1257 - Linear time in text length1258 - Dictionary matching1259- **Structure:**1260 - Trie with failure links1261 - Output function12621263### Suffix Trie1264- **Time Complexity:** O(m) for query1265- **Space Complexity:** O(m * σ^m) (exponential)1266- **Key Use Cases:**1267 - Educational1268 - Small strings only1269 - Pattern matching1270- **When to Choose:**1271 - Never for production1272 - Only for small m1273 - Understand suffix trees12741275### Longest Repeated Substring1276- **Time Complexity:** O(n) (suffix tree) or O(n log n) (suffix array)1277- **Space Complexity:** O(n)1278- **Key Use Cases:**1279 - Plagiarism detection1280 - DNA analysis1281 - Code duplication1282- **When to Choose:**1283 - Repeat detection1284 - Suffix tree/array available1285 - Overlapping allowed or not12861287### Longest Common Substring1288- **Time Complexity:** O(n + m) (suffix tree) or O(nm) (DP)1289- **Space Complexity:** O(n + m)1290- **Key Use Cases:**1291 - DNA comparison1292 - File diff1293 - Code similarity1294- **When to Choose:**1295 - Contiguous match1296 - Suffix tree/array for linear1297 - DP for simplicity1298- **DP Approach:**1299 - Table[i][j] = length of common substring ending at i, j1300 - Maximum value is answer13011302### Palindromic Tree (Eertree)1303- **Time Complexity:** O(n)1304- **Space Complexity:** O(n)1305- **Key Use Cases:**1306 - All palindromes in string1307 - Palindrome counting1308 - Palindromic density1309- **When to Choose:**1310 - All palindromes1311 - Online algorithm1312 - Memory efficient1313- **Structure:**1314 - Two roots (even/odd length)1315 - Suffix links1316 - Palindromic nodes13171318### String Matching with Wildcards1319- **Time Complexity:** O(mn)1320- **Space Complexity:** O(mn)1321- **Key Use Cases:**1322 - Shell globbing1323 - File matching1324 - Query patterns1325- **When to Choose:**1326 - Pattern with ? and *1327 - DP approach1328 - Memoization for optimization13291330---1331 related-skills: abl-v10-learning, abl-v12-learning13321333## Mathematical Algorithms13341335### Euclidean GCD1336- **Time Complexity:** O(log min(a, b))1337- **Space Complexity:** O(1) iterative, O(log n) recursive1338- **Key Use Cases:**1339 - Simplifying fractions1340 - LCM calculation1341 - Cryptography1342 - Number theory1343- **When to Choose:**1344 - Greatest common divisor1345 - Euclidean algorithm1346 - Binary GCD alternative for bit operations1347- **Extensions:**1348 - Extended GCD (Bezout coefficients)1349 - Multiple number GCD1350 - LCM = (a * b) / GCD(a, b)13511352### Binary Exponentiation (Fast Power)1353- **Time Complexity:** O(log n)1354- **Space Complexity:** O(log n) recursive, O(1) iterative1355- **Key Use Cases:**1356 - Power computation1357 - Matrix exponentiation1358 - Modular exponentiation1359 - Fibonacci numbers1360- **When to Choose:**1361 - Large exponents1362 - Modular arithmetic1363 - Matrix powers1364 - Exponentiation by squaring1365- **Variants:**1366 - Iterative implementation1367 - Modular exponentiation (a^b mod m)1368 - Matrix exponentiation1369 - Fast Fibonacci (O(log n))13701371### Sieve of Eratosthenes1372- **Time Complexity:** O(n log log n)1373- **Space Complexity:** O(n)1374- **Key Use Cases:**1375 - Prime generation1376 - Primality testing1377 - Number theory1378 - Cryptography preprocessing1379- **When to Choose:**1380 - Generate primes up to n1381 - Multiple primality tests1382 - Sieve is better for batch1383- **Optimizations:**1384 - Sieve of Atkin (O(n / log log n))1385 - Segmented sieve (for large n)1386 - Only odd numbers1387 - Bitset compression13881389### Extended Euclidean Algorithm1390- **Time Complexity:** O(log min(a, b))1391- **Space Complexity:** O(log n)1392- **Key Use Cases:**1393 - Modular inverse1394 - Bezout coefficients1395 - Chinese Remainder Theorem1396 - RSA cryptography1397- **When to Choose:**1398 - Find x, y such that ax + by = GCD(a, b)1399 - Modular inverse exists1400 - Linear Diophantine equations14011402### Miller-Rabin Primality Test1403- **Time Complexity:** O(k * log³ n) where k = iterations1404- **Space Complexity:** O(1)1405- **Key Use Cases:**1406 - Large number primality1407 - Cryptography1408 - Probabilistic testing1409 - BigInteger libraries1410- **When to Choose:**1411 - Large numbers (100+ bits)1412 - Probabilistic acceptable1413 - Deterministic for 64-bit (specific bases)1414- **Deterministic:**1415 - For n < 2^64, specific bases guarantee correctness1416 - Common bases: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 3714171418### Lucas-Lehmer Primality Test1419- **Time Complexity:** O(log² p) for Mersenne number M_p1420- **Space Complexity:** O(log p)1421- **Key Use Cases:**1422 - Mersenne primes1423 - Large prime discovery1424 - GIMPS1425- **When to Choose:**1426 - Mersenne numbers (2^p - 1)1427 - specifically for Mersenne primes1428 - Deterministic for Mersenne14291430### Modular Arithmetic1431- **Key Operations:**1432 - Addition: (a + b) mod m1433 - Multiplication: (a * b) mod m1434 - Division: a * mod_inverse(b, m) mod m1435 - Subtraction: (a - b + m) mod m1436- **When to Choose:**1437 - Avoid overflow1438 - Cryptography1439 - Large number arithmetic14401441### Fast Fourier Transform (FFT)1442- **Time Complexity:** O(n log n)1443- **Space Complexity:** O(n)1444- **Key Use Cases:**1445 - Polynomial multiplication1446 - Signal processing1447 - Large integer multiplication1448 - Convolution1449- **When to Choose:**1450 - Polynomial multiplication1451 - Convolution theorem1452 - Signal analysis1453 - Circular convolution14541455### Karatsuba Multiplication1456- **Time Complexity:** O(n^log₂3) ≈ O(n^1.585)1457- **Space Complexity:** O(n)1458- **Key Use Cases:**1459 - Large integer multiplication1460 14611462…(truncated)