Divide & Conquer
Split the problem into independent subproblems, solve recursively, combine results.
Examples: Merge sort, quicksort, binary search, Strassen matrix multiply
Understand how algorithms are defined, designed, and analyzed—then explore classic paradigms (greedy, DP, backtracking, divide and conquer) and the ideas behind P vs NP. Built for students, competitive programming, and interview prep.
An algorithm is a finite, step-by-step procedure to solve a problem or perform a computation. It takes input, follows unambiguous instructions, and produces output that terminates in a reasonable amount of time.
Algorithms are independent of programming language—you can express the same logic in C, Python, or Java. What matters is correctness (does it solve the problem?) and efficiency (how much time and memory does it use?).
Whether you are writing pseudocode on paper or implementing in C, follow a repeatable design process:
An algorithm is the abstract idea; pseudocode is a human-readable draft of that idea. Source code is the machine-executable version.
| Aspect | Algorithm (concept) | Pseudocode | Program (code) |
|---|---|---|---|
| Purpose | Problem-solving strategy | Readable blueprint | Runnable implementation |
| Language | Language-neutral | Structured English + math | C, C++, Java, Python, etc. |
| Syntax | Informal description | Loose (IF, FOR, WHILE) | Strict compiler rules |
| Audience | Anyone learning the idea | Students, interview whiteboards | Computers / IDEs |
Algorithm idea: Scan the array left to right; return the index when the target is found, else return −1.
Algorithm LinearSearch(A, n, target)
for i ← 0 to n − 1
if A[i] = target
return i
return −1
The same logic becomes a C for loop with array indexing—pseudocode bridges concept and code.
Choosing the right algorithm often matters more than micro-optimizing code. Two programs that solve the same task can differ by orders of magnitude in runtime.
Time complexity counts how the number of basic operations grows with input size n. Space complexity counts extra memory beyond the input. We use Big O for worst-case upper bounds in interview and course contexts.
| Notation | Name | Example |
|---|---|---|
| O(1) | Constant | Array index access, hash lookup (average) |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Single pass through array |
| O(n log n) | Linearithmic | Merge sort, heap sort |
| O(n²) | Quadratic | Nested loops, naive bubble sort |
| O(2ⁿ) | Exponential | Naive recursive Fibonacci, subset generation |
| O(n!) | Factorial | Generating all permutations |
| Notation | Meaning | Example |
|---|---|---|
| Θ (Theta) | Tight bound | Θ(n²) means exactly quadratic growth rate |
| O (Big O) | Upper bound | O(n²) means at most quadratic |
| Ω (Omega) | Lower bound | Ω(n) means at least linear |
| o (Little o) | Strict upper bound | o(n²) means less than quadratic |
| ω (Little omega) | Strict lower bound | ω(n) means more than linear |
Used to analyze recursive algorithms. Common recurrence solutions:
| Case | Condition | Solution |
|---|---|---|
| Case 1 | f(n) = O(nlogb(a) − ε) | T(n) = Θ(nlogb(a)) |
| Case 2 | f(n) = Θ(nlogb(a)) | T(n) = Θ(nlogb(a) · log n) |
| Case 3 | f(n) = Ω(nlogb(a) + ε) | T(n) = Θ(f(n)) |
| Algorithm | Time Complexity | When to Use |
|---|---|---|
| Linear search | O(n) | Unsorted data, small n |
| Binary search | O(log n) | Sorted data, large n |
| Hash table | O(1) average | Frequent lookups, key-value pairs |
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| QuickSort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Different problem shapes call for different strategies. Below are the core paradigms covered across this hub and the Problem Solving Hub.
Split the problem into independent subproblems, solve recursively, combine results.
Examples: Merge sort, quicksort, binary search, Strassen matrix multiply
Break into overlapping subproblems; cache optimal answers (memoization or tabulation).
Examples: Knapsack, LCS, edit distance, coin change
Start DP tutorialMake the locally best choice at each step; requires proof that it yields a global optimum.
Examples: Activity selection, Huffman coding, Dijkstra (non-negative weights)
Start Greedy tutorialBuild candidates incrementally; abandon paths that violate constraints (prune the search tree).
Examples: N-Queens, Sudoku, permutations/combinations, graph coloring
Start Backtracking tutorialTry all possibilities; simple to code but often exponential—baseline before optimizing.
Examples: All subsets, all pairs, password crack (small space)
Foundational techniques: linear/binary search, sorting networks, two pointers, sliding window.
Examples: Binary search, merge sort, lower bound, two-sum sorted array
Build the solution step by step, maintaining a partial solution that grows until completion.
Examples: Insertion sort, selection sort, Dijkstra's shortest path
Key idea: Maintain an invariant that the partial solution is correct and extend it.
Reduce the problem to a smaller instance of the same problem, solve recursively, then extend the solution.
Examples: Binary search, insertion sort, topological sorting
Variations:
Transform the problem into a different form that is easier to solve, solve it, then transform the solution back.
Examples: Heapsort (transform array to heap), Gaussian elimination, Horner's rule
Benefits: Can simplify complex problems by changing representation.
Systematic enumeration of candidate solutions using pruning to eliminate suboptimal branches.
Examples: Integer programming, traveling salesman (exact), knapsack (optimal)
Key difference from backtracking: Uses lower/upper bounds to prune, not just constraints.
Use random choices to guide the algorithm toward a solution, often providing probabilistic guarantees.
Examples: QuickSort (random pivot), Monte Carlo methods, randomized selection
Advantages: Often simpler and faster than deterministic counterparts.
Find near-optimal solutions for NP-hard problems with guaranteed performance bounds.
Examples: Vertex cover (2-approximation), traveling salesman (Christofides algorithm), set cover (logarithmic approximation)
When to use: When exact solutions are computationally infeasible.
| Class | Meaning | Example |
|---|---|---|
| P | Solvable in polynomial time O(nk) by a deterministic machine | Sorting, shortest path (Dijkstra), linear search |
| NP | Solution can be verified in polynomial time (may be hard to find) | Boolean satisfiability (SAT), Hamiltonian cycle |
| NP-Complete | In NP and every NP problem reduces to it; no known poly-time algorithm | Traveling Salesman (decision), graph coloring, subset sum |
| NP-Hard | At least as hard as NP-complete; not necessarily in NP | Halting problem, optimization TSP |
The famous P vs NP question asks: can every problem whose solution is quickly verified also be quickly solved? It remains unsolved; practically, NP-complete problems are handled with approximation algorithms, heuristics, or exponential algorithms on small inputs.
How to choose the right algorithm for a given problem:
| Problem Type | Best Paradigm | Example |
|---|---|---|
| Optimization with overlapping states | Dynamic Programming | Knapsack, LCS |
| Optimal substructure, no overlap | Divide & Conquer | Merge sort |
| Locally optimal → globally optimal | Greedy | Activity selection |
| Constraint satisfaction | Backtracking | N-Queens |
| Search in sorted data | Binary Search | Searching |
| Graph traversal | BFS/DFS | Shortest path |
| Multiple constraints, large space | Approximation | TSP |
Analyzing the average time per operation over a sequence of operations.
Examples: Dynamic arrays (array list) — O(1) amortized per insertion; splay trees; disjoint set union (Union-Find)
Techniques: Aggregate method, accounting method, potential method
Algorithms designed to run on multiple processors simultaneously.
Key concepts: Work (total operations), span (longest dependency chain), speedup (sequential time / parallel time)
Examples: Parallel prefix sum, parallel merge sort, MapReduce patterns
Process input piece by piece without knowledge of future input.
Examples: Page replacement algorithms, online load balancing, cache algorithms
Performance metric: Competitive ratio (performance relative to offline optimal)
Process data that arrives in a stream, using limited memory.
Examples: Counting distinct elements (HyperLogLog), frequent elements (Boyer-Moore majority vote), reservoir sampling
Key constraints: Single pass, O(1) or O(log n) memory
High-level strategies for solving complex optimization problems.
Examples: Genetic algorithms, simulated annealing, ant colony optimization, particle swarm optimization
When to use: When exact solutions are too expensive and heuristics are acceptable.
Practice tutorials: Greedy, Backtracking, Dynamic Programming, and C programs in the Problem Solving Hub.
Continue learning with structured tutorials and practice material on Nikhil Learn Hub:
Memoization, tabulation, knapsack, LIS, edit distance, and interview patterns.
Introduction to DP Memoization vs Tabulation Common DP PatternsLocally optimal choices, activity selection, knapsack, Huffman coding, and coin change.
Introduction to Greedy Activity Selection Coin ChangeChoose, explore, unchoose — N-Queens, Sudoku, permutations, maze, and word search.
Introduction to Backtracking N-Queens Word SearchGreedy, DP, backtracking, sorting, graphs—notes, MCQs, and programs.
Problem Solving Hub Greedy Notes Backtracking NotesArrays, lists, stacks, queues, trees, and graphs—the building blocks algorithms run on.
Data Structures Hub Stack Tutorial Graph Tutorial