#+ANKI_DECK: study_deck_02 #+TITLE: DSA Tricks & Patterns * Common Patterns ** Sliding Window Use when: contiguous subarray/substring, "longest/shortest/most k" Template: #+begin_src cpp int left = 0; for (int right = 0; right < n; right++) { // expand window while (/* window invalid */) { // shrink window left++; } // update answer } #+end_src ** Two Pointers Use when: sorted array, palindrome, pair sum Template: #+begin_src cpp int l = 0, r = n - 1; while (l < r) { if (/* condition */) l++; else r--; } #+end_src ** Binary Search Use when: monotonic function, "minimum maximum", "first/last" Template: #+begin_src cpp int lo = 0, hi = n; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (/* check(mid) */) hi = mid; else lo = mid + 1; } #+end_src ** 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: #+begin_src cpp stack st; for (int i = 0; i < n; i++) { while (!st.empty() && st.top() < arr[i]) { // process st.top() st.pop(); } st.push(i); } #+end_src ** 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