Fanpilot

PatternsStart here

A map of observations

Chapter 4 of 322 min read

Use this table to come up with ideas. Before you pick a technique, check that the condition in the middle column holds.

What you notice What must be true Technique to try
You keep asking about earlier values A small key holds everything that matters Hash map or set
Many ranges redo the same addition A range's total can be worked out from two prefixes Prefix sums
One comparison rules out a whole group The ruled-out options can't satisfy or beat the answer Two pointers or binary search
Neighboring windows share most elements Updating a window is cheap, and moving each end is safe Sliding window
Only a few best options matter A dropped option can never come back into play Heap, or keep only the options that can still win
Some items wait for a later event to settle them Items get settled or beaten in a predictable order Monotonic stack or deque
Different paths lead to the same situation A small state captures every choice still to come Memoization or DP
Choices lead from state to state You can define the states and the moves exactly BFS or DFS
Some tasks must come before others The "before" rules never form a loop Topological sort
Groups keep merging Groups only grow, or you can run time backward Union-find
A local choice still allows a best answer Swapping in your choice never makes things worse Greedy
Many overlapping range queries while values change The ranges' values combine in any grouping Fenwick tree or segment tree

These ideas combine. A scheduler might sort jobs by arrival time, sweep forward through time, keep available jobs in a heap, and pick one with a greedy rule. Each part has its own job and its own reason for being correct. Calling the whole thing "a heap problem" hides that.

Patterns also overlap. A DFS that saves its answers is dynamic programming. A monotonic deque can maintain a sliding window. A shortest-path problem on a graph without cycles can be solved with DP. Learn what each technique does and why it works first; the labels just help you organize them.