DSA & CS / 9. COMPLEXITY & PATTERNS
Complexity & Problem Patterns
Recognize the pattern, know the complexity — ace the interview
EXPLANATION
Pattern recognition is the real skill in DSA interviews. Most problems map to one of ~15 patterns. Once you see the pattern, the solution follows. Time Complexity Cheat Sheet: • O(1) → hash lookup, array index, stack push/pop • O(log n) → binary search, balanced BST ops, heap ops • O(n) → linear scan, two pointers, sliding window • O(n log n) → sorting, heap of n elements • O(n²) → nested loops, brute force pairs • O(2ⁿ) → subset enumeration, exponential recursion Space Complexity: • O(1) → two pointers, in-place ops • O(n) → hash map, recursion stack, output array • O(n²) → 2D DP table Pattern → Algorithm mapping (memorize this table): • "K largest/smallest" → Heap • "Subarray/substring" → Sliding Window • "Sorted array pairs" → Two Pointers • "Tree path/structure" → DFS recursion • "Shortest path" → BFS • "Count ways/combinations" → DP • "Connected components" → Union-Find or DFS • "Find duplicate/missing" → XOR or hash set
DIAGRAM
Complexity ladder: O(1) ████ constant O(log n) ████░ bisect, heap O(n) ████████░ linear scan O(n log n)████████████░ sort, heap n items O(n²) ████████████████████ nested loops O(2ⁿ) ██████████████████████████ subsets Interview pattern map: ┌─────────────────────────────────────────┐ │ Sorted array? → Two Pointers │ │ Subarray/window? → Sliding Window │ │ Find in sorted? → Binary Search │ │ Top K elements? → Heap │ │ Count ways? → DP │ │ Tree problem? → DFS/BFS │ │ Shortest path? → BFS (Dijkstra) │ │ Permutations? → Backtracking │ └─────────────────────────────────────────┘
CODE