Files
cpp-flashcards/org/study_deck_02/toolkit/suggestions.org
T
2026-06-01 18:12:40 +08:00

2.5 KiB
Raw Blame History

DSA Tricks & Patterns

Common Patterns

Sliding Window

Use when: contiguous subarray/substring, "longest/shortest/most k" Template:

int left = 0;
for (int right = 0; right < n; right++) {
    // expand window
    while (/* window invalid */) {
        // shrink window
        left++;
    }
    // update answer
}

Two Pointers

Use when: sorted array, palindrome, pair sum Template:

int l = 0, r = n - 1;
while (l < r) {
    if (/* condition */) l++;
    else r--;
}

Binary Search

Use when: monotonic function, "minimum maximum", "first/last" Template:

int lo = 0, hi = n;
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (/* check(mid) */) hi = mid;
    else lo = mid + 1;
}

BFS vs DFS

  • BFS: shortest path (unweighted), level-order, queue
  • DFS: path existence, backtracking, cycle detection, stack/recursion

Union-Find

Use when: connected components, cycle detection, grouping

  • Path compression + union by rank = O(α(n))

Monotonic Stack

Use when: next greater/smaller element, stock span Template:

stack<int> st;
for (int i = 0; i < n; i++) {
    while (!st.empty() && st.top() < arr[i]) {
        // process st.top()
        st.pop();
    }
    st.push(i);
}

Topological Sort

Use when: dependency ordering, DAG, course schedule

  • Kahn's (BFS + in-degree) or DFS post-order reversal

Dijkstra's

Use when: shortest path, non-negative weights, weighted graph

  • Priority queue + relaxation

Bit Manipulation Tricks

  • ~x = -x - 1
  • x & (x - 1) clears lowest set bit
  • x & -x isolates lowest set bit
  • XOR swap: a ^= b; b ^= a; a ^= b;

KMP / Z-Algorithm

Use when: pattern matching, repeated substrings

  • KMP: O(n + m), failure function
  • Z: O(n + m), Z-array

DP State Design

  • Ask: what do I need to track? (index, remaining, previous choice)
  • State = f(index, constraint1, constraint2, …)
  • Space optimize with rolling array when only previous row needed

Graph Coloring (2-coloring / Bipartite)

Use when: odd cycle check, two groups

  • BFS/DFS alternating colors

Prefix Sum

Use when: subarray sum, range queries

  • Build once O(n), query O(1)

Trie

Use when: prefix search, autocomplete, word dictionary

  • Each node = character, path = word

Heap / Priority Queue

Use when: k-th element, merge k sorted, median maintenance

  • C++: `priority_queue` (max-heap by default)

Fast & Slow Pointers

Use when: cycle detection, linked list midpoint

  • Floyd's tortoise and hare