Show 25 50 100
PDF
21 result(s) in Algorithm Clear

Index

Showing 21 topics
  1. Time and Space Complexity (Big-O)
  2. Recursion
  3. Algorithm Design Techniques
  4. BFS and DFS
  5. Dijkstra's Shortest Path
  6. Minimum Spanning Tree (Kruskal, Prim)
  7. Dynamic Programming
  8. Two Pointers and Sliding Window
  9. Backtracking
  10. Linear Search
  11. Binary Search
  12. lower_bound and upper_bound
  13. Search Algorithms Comparison
  14. Sorting Algorithms Comparison
  15. Bubble Sort
  16. Selection Sort
  17. Insertion Sort
  18. Merge Sort
  19. Quick Sort
  20. Heap Sort
  21. Counting Sort
1 Index

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ⁿ)

O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)

Recognising complexity from code C++ 6 lines
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.

2 Index

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++ 17 lines
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);
}
3 Index
TechniqueIdeaExamples
Brute forceTry every possibilityLinear search, all pairs
Divide and ConquerSplit into independent parts, solve, combineMerge sort, quick sort, binary search
GreedyTake the best choice at each stepActivity selection, Kruskal, Prim, Dijkstra, Huffman
Dynamic ProgrammingOverlapping subproblems, store answersFibonacci, knapsack, LCS, coin change
BacktrackingBuild a solution, undo when it failsN-Queens, Sudoku, subsets, permutations
Two pointers / Sliding windowMove indices over an array instead of nested loopsPair sum, longest substring

Q & A

  1. Greedy vs DP?
    Greedy makes one local choice and never looks back, so it is fast but only correct for some problems. DP tries all choices of subproblems and reuses stored answers, so it is always correct when the problem has optimal substructure.
4 Index

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 spreads out, DFS dives down one branch first

BFS C++ 12 lines
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++ 6 lines
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 Index

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++ 17 lines
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 Index

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++ 18 lines
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 Index

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

Plain recursion recomputes f(3) and f(2) many times

0/1 Knapsack O(n × W) C++ 11 lines
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++ 8 lines
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++ 9 lines
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 Index

Replace a nested O(n²) loop with two indices that move through the array in O(n).

Two pointers C++ 10 lines
// 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++ 11 lines
// 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++ 8 lines
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
}
9 Index

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++ 11 lines
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++ 4 lines
string s = "abc";
sort(s.begin(), s.end());
do cout << s << " "; while (next_permutation(s.begin(), s.end()));
// abc acb bac bca cab cba
10 Index

Check each element one by one. Works on unsorted data. Time O(n), space O(1).

C++ 5 lines
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 Index

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

Searching 23 takes only 3 steps for 10 elements

Iterative C++ 10 lines
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++ 7 lines
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

  1. Why mid = low + (high - low) / 2?
    low + high can overflow int when both are large; this form gives the same value safely.
12 Index

STL binary search helpers on sorted ranges. lower_bound → first element ≥ x. upper_bound → first element > x.

C++ 5 lines
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 Index
AlgorithmBestAverageWorstSpaceStable
Bubble SortO(n)O(n²)O(n²)O(1)Yes
Selection SortO(n²)O(n²)O(n²)O(1)No
Insertion SortO(n)O(n²)O(n²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Counting SortO(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).

15 Index

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++ 12 lines
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 Index

Find the minimum of the unsorted part and put it at the front. Always O(n²) comparisons but at most n − 1 swaps.

C++ 8 lines
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 Index

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++ 11 lines
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 Index

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

Split down to single elements, then merge back in order

C++ 17 lines
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 Index

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

After one partition the pivot is at its final index

C++ 16 lines
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

  1. 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.
20 Index

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++ 18 lines
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);
    }
}
21 Index

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++ 7 lines
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;
}