1
Time and Space Complexity (Big-O)
★★★★★
↑ Index
Algorithm
Time complexity is how the running time grows with input size n. Space complexity is how much extra memory is used. We usually give the worst case with Big-O.
- Big-O (O) — upper bound (worst case).
- Big-Omega (Ω) — lower bound (best case).
- Big-Theta (Θ) — tight bound (both).

O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)
Recognising complexity from code · C++
x = a[5]; // O(1)
for (int i = 1; i < n; i *= 2) {} // O(log n)
for (int i = 0; i < n; i++) {} // O(n)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {} // O(n^2)
sort(a, a + n); // O(n log n)
Rule of thumb: about 108 simple operations run in ~1 second. For n = 105, O(n²) is too slow but O(n log n) is fine.
Algorithm
A function that calls itself. Every recursion needs a base case (stop condition) and a recursive case that moves toward it. Each call uses stack memory; without a base case you get a stack overflow.
C++
int power(int a, int b) { // a^b
if (b == 0) return 1; // base case
return a * power(a, b - 1); // recursive case
}
long long fastPower(long long a, int b) { // O(log b)
if (b == 0) return 1;
long long half = fastPower(a, b / 2);
return (b % 2) ? half * half * a : half * half;
}
void hanoi(int n, char from, char to, char via) { // Tower of Hanoi: 2^n - 1 moves
if (n == 0) return;
hanoi(n - 1, from, via, to);
cout << "Move disk " << n << " " << from << " -> " << to << "\n";
hanoi(n - 1, via, to, from);
}
4
BFS and DFS
★★★★★
↑ Index
Algorithm
BFS (Breadth First Search) visits level by level with a queue; it finds the shortest path in an unweighted graph. DFS (Depth First Search) goes as deep as possible with a stack / recursion; used for cycle detection, topological sort, connected components. Both are O(V + E).

BFS spreads out, DFS dives down one branch first
BFS · C++
void bfs(int start, vector<vector<int>> &adj) {
vector<bool> visited(adj.size(), false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int u = q.front(); q.pop();
cout << u << " ";
for (int v : adj[u])
if (!visited[v]) { visited[v] = true; q.push(v); }
}
}
DFS (recursive) · C++
void dfs(int u, vector<vector<int>> &adj, vector<bool> &visited) {
visited[u] = true;
cout << u << " ";
for (int v : adj[u])
if (!visited[v]) dfs(v, adj, visited);
}
5
Dijkstra's Shortest Path
↑ Index
Algorithm
Finds the shortest distance from one source to every node in a graph with non-negative weights. Greedy: always expand the closest unvisited node, using a min-heap. Complexity O((V + E) log V).
For negative weights use Bellman-Ford O(VE); for all pairs use Floyd-Warshall O(V³).
C++
vector<int> dijkstra(int src, vector<vector<pair<int,int>>> &adj) { // adj[u] = {v, w}
vector<int> dist(adj.size(), INT_MAX);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq; // {dist, node}
dist[src] = 0;
pq.push({0, src});
while (!pq.empty()) {
auto [d, u] = pq.top(); pq.pop();
if (d > dist[u]) continue; // outdated entry
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) { // relax the edge
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
6
Minimum Spanning Tree (Kruskal, Prim)
↑ Index
Algorithm
A spanning tree connects all V vertices with V − 1 edges and no cycle. The MST has the smallest total weight.
- Kruskal — sort edges by weight, add an edge if it does not form a cycle (checked with Disjoint Set Union). O(E log E).
- Prim — start from a node, repeatedly add the cheapest edge leaving the tree (min-heap). O(E log V).
Kruskal with DSU · C++
int parent[1000];
int find(int x) { return parent[x] == x ? x : parent[x] = find(parent[x]); } // path compression
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false; // same set → would make a cycle
parent[a] = b;
return true;
}
// edges = {w, u, v}
int kruskal(int n, vector<array<int,3>> edges) {
for (int i = 0; i < n; i++) parent[i] = i;
sort(edges.begin(), edges.end());
int total = 0;
for (auto [w, u, v] : edges)
if (unite(u, v)) total += w;
return total;
}
7
Dynamic Programming
★★★★★
↑ Index
Algorithm
DP solves a problem by breaking it into overlapping subproblems and storing each answer so it is computed only once. The problem must have optimal substructure.
- Memoization (top-down) — recursion + cache.
- Tabulation (bottom-up) — fill a table with loops.

Plain recursion recomputes f(3) and f(2) many times
0/1 Knapsack O(n × W) · C++
int knapsack(vector<int> &wt, vector<int> &val, int W) {
int n = wt.size();
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
for (int i = 1; i <= n; i++)
for (int w = 0; w <= W; w++) {
dp[i][w] = dp[i - 1][w]; // skip item
if (wt[i - 1] <= w)
dp[i][w] = max(dp[i][w], val[i - 1] + dp[i - 1][w - wt[i - 1]]); // take item
}
return dp[n][W];
}
Longest Common Subsequence · C++
int lcs(string a, string b) {
int n = a.size(), m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = (a[i-1] == b[j-1]) ? dp[i-1][j-1] + 1 : max(dp[i-1][j], dp[i][j-1]);
return dp[n][m]; // lcs("ABCBDAB", "BDCABA") = 4
}
Coin change · C++
int coinChange(vector<int> &coins, int amount) { // minimum coins
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int a = 1; a <= amount; a++)
for (int c : coins)
if (c <= a && dp[a - c] != INT_MAX)
dp[a] = min(dp[a], dp[a - c] + 1);
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
8
Two Pointers and Sliding Window
↑ Index
Algorithm
Replace a nested O(n²) loop with two indices that move through the array in O(n).
Two pointers · C++
// sorted array: is there a pair with sum = target?
bool pairSum(vector<int> &a, int target) {
int i = 0, j = a.size() - 1;
while (i < j) {
int s = a[i] + a[j];
if (s == target) return true;
if (s < target) i++; else j--;
}
return false;
}
Sliding window · C++
// maximum sum of any k consecutive elements
int maxWindow(vector<int> &a, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += a[i];
int best = sum;
for (int i = k; i < a.size(); i++) {
sum += a[i] - a[i - k]; // slide: add new, remove old
best = max(best, sum);
}
return best;
}
Kadane's algorithm (maximum subarray) · C++
int maxSubArray(vector<int> &a) {
int cur = a[0], best = a[0];
for (int i = 1; i < a.size(); i++) {
cur = max(a[i], cur + a[i]);
best = max(best, cur);
}
return best; // {-2,1,-3,4,-1,2,1,-5,4} → 6
}
Algorithm
Build a solution step by step; when a step cannot lead to a valid answer, undo it and try the next option.
All subsets (2^n) · C++
void subsets(vector<int> &a, int i, vector<int> &cur) {
if (i == a.size()) {
for (int x : cur) cout << x << " ";
cout << "\n";
return;
}
subsets(a, i + 1, cur); // skip a[i]
cur.push_back(a[i]); // take a[i]
subsets(a, i + 1, cur);
cur.pop_back(); // undo
}
All permutations · C++
string s = "abc";
sort(s.begin(), s.end());
do cout << s << " "; while (next_permutation(s.begin(), s.end()));
// abc acb bac bca cab cba
Algorithm › Search
Check each element one by one. Works on unsorted data. Time O(n), space O(1).
C++
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++)
if (arr[i] == key) return i; // found: return index
return -1; // not found
}
11
Binary Search
★★★★★
↑ Index
Algorithm › Search
Works only on a sorted array. Compare with the middle element and discard half of the range each time. Time O(log n), space O(1) (iterative).

Searching 23 takes only 3 steps for 10 elements
Iterative · C++
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoids overflow of (low + high)
if (arr[mid] == key) return mid;
if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
Recursive (O(log n) stack space) · C++
int binarySearch(int arr[], int low, int high, int key) {
if (low > high) return -1;
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) return binarySearch(arr, mid + 1, high, key);
return binarySearch(arr, low, mid - 1, key);
}
Q & A
- Why mid = low + (high - low) / 2?
low + high can overflow int when both are large; this form gives the same value safely.
12
lower_bound and upper_bound
↑ Index
Algorithm › Search
STL binary search helpers on sorted ranges. lower_bound → first element ≥ x. upper_bound → first element > x.
C++
vector<int> v = {1, 2, 4, 4, 4, 7, 9};
auto lo = lower_bound(v.begin(), v.end(), 4) - v.begin(); // 2
auto hi = upper_bound(v.begin(), v.end(), 4) - v.begin(); // 5
cout << hi - lo; // 3 = count of 4
cout << binary_search(v.begin(), v.end(), 7); // 1 (true)
14
Sorting Algorithms Comparison
★★★★★
↑ Index
Algorithm › Sort
| Algorithm | Best | Average | Worst | Space | Stable |
|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
Stable = equal elements keep their original order. In-place = O(1) extra memory. C++ sort() uses Introsort (quick + heap + insertion), O(n log n).
Algorithm › Sort
Repeatedly swap adjacent elements that are in the wrong order; after each pass the largest element "bubbles" to the end. Stop early if a pass makes no swap.
C++
void bubbleSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
bool swapped = false;
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
swapped = true;
}
}
if (!swapped) break; // already sorted → O(n) best case
}
}
16
Selection Sort
↑ Index
Algorithm › Sort
Find the minimum of the unsorted part and put it at the front. Always O(n²) comparisons but at most n − 1 swaps.
C++
void selectionSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[minIdx]) minIdx = j;
swap(a[i], a[minIdx]);
}
}
17
Insertion Sort
↑ Index
Algorithm › Sort
Take the next element and insert it into its correct place in the already-sorted left part, like sorting playing cards. Very fast for small or nearly-sorted arrays.
C++
void insertionSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; // shift right
j--;
}
a[j + 1] = key;
}
}
18
Merge Sort
★★★★★
↑ Index
Algorithm › Sort
Divide and conquer: split the array into halves, sort each half recursively, then merge the two sorted halves. Always O(n log n), stable, needs O(n) extra space.

Split down to single elements, then merge back in order
C++
void merge(vector<int> &a, int l, int m, int r) {
vector<int> tmp;
int i = l, j = m + 1;
while (i <= m && j <= r)
tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
while (i <= m) tmp.push_back(a[i++]);
while (j <= r) tmp.push_back(a[j++]);
for (int k = 0; k < tmp.size(); k++) a[l + k] = tmp[k];
}
void mergeSort(vector<int> &a, int l, int r) {
if (l >= r) return;
int m = l + (r - l) / 2;
mergeSort(a, l, m);
mergeSort(a, m + 1, r);
merge(a, l, m, r);
}
Recurrence: T(n) = 2T(n/2) + O(n) → O(n log n).
19
Quick Sort
★★★★★
↑ Index
Algorithm › Sort
Pick a pivot, partition the array so smaller elements are on the left and larger on the right, then sort both sides recursively. Average O(n log n), in-place. Worst case O(n²) when the pivot is always the smallest/largest (e.g. already sorted input with last-element pivot); a random pivot avoids it.

After one partition the pivot is at its final index
C++
int partition(vector<int> &a, int low, int high) { // Lomuto
int pivot = a[high];
int i = low - 1;
for (int j = low; j < high; j++)
if (a[j] < pivot) swap(a[++i], a[j]);
swap(a[i + 1], a[high]);
return i + 1;
}
void quickSort(vector<int> &a, int low, int high) {
if (low < high) {
int p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
Q & A
- Merge sort vs quick sort?
Merge sort: always O(n log n), stable, needs O(n) extra memory, good for linked lists and external sorting. Quick sort: in-place and usually faster in practice, but O(n²) in the worst case and not stable.
Algorithm › Sort
Build a max-heap, then repeatedly move the root (largest) to the end and re-heapify the rest. O(n log n) always, in-place, not stable.
C++
void heapify(vector<int> &a, int n, int i) {
int largest = i, l = 2 * i + 1, r = 2 * i + 2;
if (l < n && a[l] > a[largest]) largest = l;
if (r < n && a[r] > a[largest]) largest = r;
if (largest != i) {
swap(a[i], a[largest]);
heapify(a, n, largest);
}
}
void heapSort(vector<int> &a) {
int n = a.size();
for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i); // build heap O(n)
for (int i = n - 1; i > 0; i--) {
swap(a[0], a[i]); // largest to the end
heapify(a, i, 0);
}
}
Algorithm › Sort
Non-comparison sort for small integer ranges: count each value, then write them back in order. O(n + k) where k is the value range.
C++
void countingSort(vector<int> &a, int maxVal) {
vector<int> cnt(maxVal + 1, 0);
for (int x : a) cnt[x]++;
int idx = 0;
for (int v = 0; v <= maxVal; v++)
while (cnt[v]--) a[idx++] = v;
}