sagelearnai

DSA Patterns

Learn each pattern once, then solve problems right here with a built-in JavaScript and Python runner.

1. Two Pointers

Walk two indices toward (or along) each other to exploit sorted order or symmetry.

2. Sliding Window

Maintain a contiguous window and its state incrementally instead of recomputing.

3. Prefix Sum

Precompute running totals to answer any range question in O(1).

4. Hashing

Trade memory for speed: hash maps and sets turn O(n²) searches into O(n) lookups.

5. Stack & Monotonic Stack

LIFO for matching and nesting; monotonic stacks for 'next greater' questions.

6. Binary Search

Halve the search space using a monotonic condition — on arrays or on the answer itself.

7. Linked List

Pointer surgery, dummy heads, reversal and merging.

8. Trees & BST

Recursion with the right return value, BST ordering, and level-by-level BFS.

9. Tries

Prefix trees for fast word and prefix lookups.

10. Heap & Priority Queue

Always grab the min or max fast: top-k, k-way merge, scheduling, streaming medians.

11. Graphs (BFS / DFS)

Grids and networks: traversal, shortest paths, topological order, MSTs.

12. Backtracking

Choose, explore, un-choose — systematically enumerate subsets, permutations and boards.

13. Greedy

Make the locally optimal choice — when you can prove it's globally optimal.

14. Intervals

Sort by start or end, then sweep and merge.

15. 1-D Dynamic Programming

Define the state, the recurrence and the base case — then fill a table.

16. 2-D Dynamic Programming

Grids and pairs of strings: dp[i][j] from its neighbors.

17. Bit Manipulation

XOR tricks, masks and counting bits.

18. Fast & Slow Pointers

Two speeds through a sequence: cycles, middles and duplicates in O(1) space.

19. Matrix

2-D array traversal, in-place transforms and grid simulation.

20. Union-Find

Track connected components under merges in near-constant time.