Sorting algorithms overview
Common sorts:
- Bubble/Insertion: simple, O(n^2)
- Merge/Quick: O(n log n) average; merge stable; quick in-place
- Counting/Radix: linear for integers in range
Binary search
Requires sorted array; halves the search space each step.
function binSearch(a, t){
let l=0, r=a.length-1;
while(l<=r){
const m=(l+r)>>1;
if(a[m]===t) return m;
if(a[m]<t) l=m+1; else r=m-1;
}
return -1;
}BFS vs DFS
BFS explores level by level (shortest path in unweighted). DFS goes deep first (cycle detection, topological sort).
Dynamic programming
Break problems into overlapping subproblems; store results (memoization/tabulation).
// Fibonacci with memo
const memo = new Map();
function fib(n){
if(n<2) return n;
if(memo.has(n)) return memo.get(n);
const v=fib(n-1)+fib(n-2);
memo.set(n,v); return v;
}Greedy algorithms
Make locally optimal choices hoping for global optimum (activity selection, coin change for canonical systems).
Recursion tips
Define base case; progress towards it; watch stack depth; convert to iteration if needed.
Two pointers
Use two indices moving towards each other or in tandem (reverse array, remove duplicates, sum pairs).
Sliding window
Maintain a window to track substring/subarray properties (max sum, longest unique substring).
Dijkstra's algorithm
Finds shortest paths in weighted graphs with non-negative edges using a priority queue (min-heap).
Topological sort
Orders DAG nodes so edges go from earlier to later nodes; implemented via DFS or Kahn's algorithm.
KMP string search
Preprocesses pattern to build LPS array for linear-time substring search; avoids redundant comparisons.
Amortized analysis
Average cost per operation over sequences, e.g., dynamic array appends or union-find path compression.
NP-Completeness
NP problems verifiable in polynomial time; NP-complete are the hardest in NP (SAT, Traveling Salesman). Use reductions and approximations.
Divide and Conquer
Break problems into subproblems, solve recursively, and combine (merge sort, quicksort, FFT).
Dynamic Programming patterns
Overlapping subproblems and optimal substructure; common patterns like knapsack, LIS, edit distance.
Greedy algorithms
Make locally optimal choices; correctness via exchange argument or matroid structure (interval scheduling, Huffman coding).
Binary search variants
Lower/upper bound, first/last occurrence, searching on answer space; careful with mid and termination conditions.
Quickselect
Find k-th smallest in average O(n) using partitioning; worst-case O(n^2), can be optimized with median-of-medians.