Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views4 pages

Dsa Patterns - One-Page Cheat Sheet

Uploaded by

dawej44137
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

Dsa Patterns - One-Page Cheat Sheet

Uploaded by

dawej44137
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

DSA Patterns — One‑Page Cheat Sheet

Compact list of common problem‑solving patterns, when to use them, complexity notes, and
1‑line problem prompts to practice.

1. Two Pointers
What: Use two indices moving from ends or same direction on sorted/linear structures. When: Sorted
arrays, pair-sum, removing duplicates, merging lists. Complexity: O(n) / O(1) extra. Try: "Find pair with
given sum (sorted)."

2. Fast & Slow Pointers


What: Two pointers at different speeds to find cycles, midpoints, or k‑th from end. When: Linked lists, cycle
detection, palindrome checks. Try: "Detect cycle in linked list (Floyd)."

3. Sliding Window (Fixed & Variable)


What: Maintain window [i..j] that satisfies a condition; expand/contract. When: Subarray/substring sums,
longest/shortest subarray with property. Complexity: O(n) typical. Try: "Longest substring without
repeating chars."

4. Prefix Sum / Cumulative Sum


What: Precompute running sums for O(1) range queries. When: Range sums, subarray equals k (with
hashmap). Try: "Subarray sum equals K."

5. Binary Search (Index & Answer)


What: Classic on sorted arrays or binary search on answer space. When: Search, minimizing/maximizing
parameter, monotonic predicate. Complexity: O(log n) × check. Try: "Aggressive cows / split arrays to
minimize largest sum."

6. Sorting + Two-Pointer / Sweep


What: Sort and then use linear pass or pointers. When: Interval merging, pair problems, scheduling. Try:
"Merge intervals."

1
7. Interval Patterns (Merge, Cover, Scheduling)
What: Sort by start/end; greedy choices (earliest finish). When: Meeting rooms, max non-overlapping
intervals. Try: "Minimum number of conference rooms."

8. Hashing (Maps/Sets)
What: Use hash tables for O(1) lookups and counting. When: Frequency, complements, deduplication,
sliding window with counts. Try: "Two-sum (unsorted)."

9. Monotonic Stack / Queue


What: Maintain monotone structure to answer next/previous greater/smaller queries. When: Sliding-
window max (deque), histogram largest rectangle, stock span. Try: "Daily temperatures (next warmer day)."

10. Heaps (Priority Queues)


What: Keep top‑k or extract min/max dynamically. When: Merge k sorted lists, streaming median (two
heaps), Dijkstra. Try: "Find k smallest elements."

11. Graph Traversals: BFS / DFS


What: BFS for shortest unweighted path / level order; DFS for components, backtracking, topological sort
helper. When: Connectivity, shortest path in unweighted graphs, tree problems. Try: "Number of connected
components."

12. Topological Sort / DAG DP


What: Order DAG nodes; perform DP along topological order. When: Scheduling with dependencies,
longest path in DAG. Try: "Course schedule / finish order."

13. Shortest Paths (Dijkstra / Bellman‑Ford)


What: Dijkstra for nonnegative weights; Bellman‑Ford for negative edges. When: Weighted shortest path
problems. Try: "Single-source shortest path with nonnegative weights."

14. Union‑Find (Disjoint Set)


What: Merge sets, detect cycles, count components (use union by size/rank + path compression). When:
Connectivity, Kruskal MST, friend circles. Try: "Number of connected components in graph."

2
15. Backtracking / Recursion
What: Explore choices with recursion + pruning. When: Permutations, subsets, combinatorics, constraint
satisfaction. Try: "Generate all subsets."

16. Dynamic Programming (DP) Patterns


Categories & Hints: - 1D DP (linear states): fib, climb stairs, dp[i] depends on previous few. - 2D DP (grid):
unique paths, edit distance. - Knapsack / DP on weights: capacity-based. - DP on sequences (LIS / LCS):
patience sorting for LIS O(n log n). - Tree DP: postorder aggregation. Try: "Longest increasing
subsequence."

17. Greedy Algorithms


What: Make local optimal choices aiming for global optimum; require proof. When: Interval scheduling,
Huffman coding, coin change (canonical systems). Try: "Activity selection (max non-overlapping intervals)."

18. Divide & Conquer (Merge Sort style)


What: Split, solve halves, merge answers. When: Sorting, inversion count, closest pair of points. Try: "Count
inversions using merge sort."

19. Bit Manipulation


What: Use bitwise ops for parity, masks, subset iteration. When: XOR problems, single-number, bit DP,
subset generation with masks. Try: "Single number (XOR)."

20. Trie (Prefix Tree)


What: Tree of characters for fast prefix queries. When: Autocomplete, longest common prefix, word search.
Try: "Implement prefix search / word dictionary."

21. Rolling Hash / Rabin‑Karp


What: Hash substrings for pattern matching with O(1) rolling update. When: String search, duplicate
substring detection. Try: "Find repeated DNA sequences."

22. Segment Tree / Fenwick (BIT)


What: Range queries + point/range updates; Fenwick simpler for sums. When: Dynamic range queries,
order statistics, offline queries. Try: "Range sum with updates."

3
23. Square‑Root Decomposition / Mo’s Algorithm
What: Block decomposition or offline reordering for query optimization. When: Many range queries with
offline processing. Try: "Answer offline distinct‑count queries."

24. Matrix Manipulation (DFS on grid)


What: 2D DFS/BFS, rotations, spirals, dynamic programming on grid. When: Islands count, path counts,
rotate image. Try: "Number of islands."

25. Misc / Math Patterns


• GCD / LCM for number theory problems.
• Sieve / Primes for primality ranges.
• Combinatorics (nCr / DP) for counting.
• Probability / Expectation when stochastic.

How to Use This Sheet


1. Identify structure: array? string? graph? tree? matrix? numbers?
2. Match pattern: sorted → two pointers/binary search; dynamic updates → segment tree/heap.
3. Check constraints: n ≤ 10⁵ → O(n log n) or better; n ≤ 20 → consider bitmask DP/backtracking.
4. Combine patterns: e.g., sliding window + hashing for anagram search.

Quick Practice Plan (30 problems)


• 6 Array/string basics: two pointers, sliding window, prefix sum.
• 6 Trees/graphs: DFS/BFS, union‑find, Dijkstra.
• 6 DP/backtracking: LIS, knapsack, subsets/permutations.
• 6 Heaps/monotonic structures: k‑largest, sliding max, stack problems.
• 6 Advanced: segment tree, trie, rolling hash, Mo’s algorithm.

Need a printable PDF, short example code templates, or curated problem list per pattern? Click the canvas title to
view and ask me to export.

You might also like