Recognizing the Right Technique
The signals in a problem statement that point to an algorithm.
Strong competitors rarely invent a technique during a contest; they recognize one. Recognition is not a gift. It is a procedure you can practice: restate the problem precisely, classify what it asks, find the structure that licenses a technique, and let the constraints veto everything too slow.
What you’ll learn
- Restate a problem as input, output and objective, and classify it as a decision, search, optimization or counting problem.
- Name the structural property that licenses each major technique, and prove one licensing theorem: when a variable sliding window is correct.
- Map twenty classic problem shapes to their techniques and complexities, and explain why their look-alikes need something else.
- Use the brute force twice: as the baseline whose waste you remove, and as the oracle that tests the fast solution.
Six questions before any code
Faced with a new statement, ask these six questions in order. Each one narrows the candidates, and most wrong solutions skip one of them.
- What are the input, the output and the objective? Restate the problem in one sentence with symbols: "given , find the largest over all ". Many wrong answers solve a misread problem.
- What kind of question is it? A decision (yes or no), a search (find one solution), an optimization (the best value) or a counting problem (how many, often modulo a prime). Counting rules out shortcuts that find just one good answer, and an optimization problem often hides an easier decision version.
- What structure does it have? Order, contiguity, a yes/no question that flips once, a graph, overlapping subproblems, a choice that is provably safe, a small parameter.
- What does the budget allow? The constraints, at about simple steps per second, cap the complexity.
- Which candidates survive? List the techniques the structure licenses and the budget allows, and run each on your tiny examples, especially the awkward ones.
- How will you know it is right? A proof (an invariant or an exchange argument) or a stress test against the brute force.
Think first A problem has array elements and queries. What total cost should you aim for, and what does that say about each query?
About steps. Answering each query by scanning the array costs , far too slow, so each query must cost or after preprocessing. Which structure delivers that depends on the rest of the statement: prefix sums if values never change, a Fenwick or segment tree if they do, a sparse table for range minimums, binary search if the data can be sorted.
One input, five questions
The kind of question changes the technique even when the input stays the same. Take meetings, each a half-open interval , so that a meeting ending at 6 does not clash with one starting at 6:
| Question | Kind | Technique | Cost |
|---|---|---|---|
| Can one person attend all of them? | decision | sort by start time, compare neighbors | |
| The most meetings one person can attend | optimization | greedy: earliest finish first, proved by an exchange argument | |
| The fewest rooms that host them all | optimization | sweep line over sorted endpoints (or a heap of end times): the answer is the largest number of meetings in progress at once | |
| Meetings have values: the largest total value one person can attend | optimization | DP over meetings sorted by finish, with binary search for the last compatible one | |
| How many sets of pairwise compatible meetings exist, modulo ? | counting | the same DP, adding instead of maximizing |
The last two rows share a recurrence. Sort the meetings by finish time and let be the number of meetings, among the first , that finish by : because the list is sorted by finish, they are exactly a prefix, found by binary search. Meeting is either left out or taken together with a compatible set from that prefix:
with and (the empty set counts). Both recurrences agree with brute force on thousands of random instances.
For the weighted question, a friend proposes: take the most valuable meeting, discard everything that overlaps it, and repeat. Is that right?
- Yes: an exchange argument shows the most valuable meeting is always safe
- Yes, provided ties are broken by earliest finish
- No: with worth 10 and , worth 6 each, it takes 10 while 12 is possible; use the DP
- No, but taking meetings by earliest finish instead fixes it
Show the answer
C. No: with worth 10 and , worth 6 each, it takes 10 while 12 is possible; use the DP
One valuable meeting can block two that are worth more together. The DP compares both options for every meeting: here. Value is not a safe greedy key, and neither is finish time once meetings carry values.
Structure licenses technique
Behind every signal is a structural property, and behind every property a theorem that makes the technique correct. Recognizing the property is what lets you trust a technique on a problem you have never seen.
| Property of the problem | Licenses | Why it works |
|---|---|---|
| sorted data, or data you may sort without losing the answer | two pointers; binary search | one comparison rules out a whole row of pairs, or half the range |
| a yes/no question that flips once as a value grows | binary search on the answer | the answer is the boundary of a monotone predicate |
| contiguity, with a condition closed under shrinking | sliding window | the left end never moves back (proved below) |
| an operation with an inverse: sums, XOR, counts | prefix sums | a range is the difference of two prefixes |
| an associative operation, with updates | segment tree, Fenwick tree | every range splits into stored pieces |
| optimal substructure and overlapping subproblems | dynamic programming | each subproblem is solved once, in an order that respects its dependencies |
| the greedy-choice property | greedy | an exchange argument turns any optimum into one containing the greedy choice |
| unit edge costs; nonnegative costs; no cycles | BFS; Dijkstra; DP in topological order | layers by distance; settled distances never improve; every edge points forward |
| one small parameter , such as | exponential in only: bitmasks, meet in the middle | or times a polynomial in |
never decreases. If has , so does its sub-window . Apply this with :
The loop stops exactly at . Suppose the left pointer arrives at holding . For every the window lacks , by the minimality of , so the loop advances; at the window has , so it stops. By induction on :
At most moves. The right end moves times; the left end never moves back and never passes . With an update of the window's state per move (a running sum, a table of counts), the whole scan is linear:
Why closure is needed. Without it the first line fails: a later right end may need a left end the loop has already passed. For "sum at most ", closure holds when every value is nonnegative, since shrinking only lowers the sum. With negatives it fails: for , the window has sum , but its sub-window sums to 2.
When closure fails, a different structure takes over. For the longest subarray with sum at most and negative values allowed, write the condition on prefix sums, with : only the start positions where reaches a new maximum can be the best start, those running maxima are sorted, and a binary search over them answers each , for in total. The Optimal lesson Counting Subarrays with Windows catalogs where windows work and where they break.
Recognizing it: the problem map
Here is the map: twenty problem shapes, stated in our own words, one or two from every part of the course, each with the signal that gives it away. Cover the last two columns and guess before you read them.
| Problem, in brief | Signal | Technique | Cost |
|---|---|---|---|
| Two values in a sorted array with sum | sorted; a pair | two pointers from both ends | |
| Longest substring with no repeated character | contiguous; the condition survives shrinking | sliding window with last-seen positions | |
| Count subarrays with sum exactly , negatives allowed | contiguous; an exact sum; negatives | prefix sums and a hash map of their counts | expected |
| Range sums, with point updates in between | ranges plus updates | Fenwick tree or segment tree | |
| Maximum of every window of length | a window, but a maximum cannot be subtracted | monotonic deque | |
| For each day, the next warmer day | nearest greater | monotonic stack | |
| Least daily capacity that ships packages, in order, within days | "least such that"; a check that flips once | binary search on the answer, with a greedy check | |
| The largest values of a long stream | top ; memory for values only | min-heap of size | |
| Two values with sum , unsorted | look up each complement | hash set | expected |
| Longest substring that occurs at least twice | repeated substrings | suffix array and LCP array, or binary search with a rolling hash | |
| Count pairs with | pairs defined by order | merge sort, counting while merging | |
| Fewest knight moves between two squares | equal-cost moves on an implicit graph | BFS | |
| Cheapest route, with nonnegative fares | weighted shortest path | Dijkstra's algorithm with a binary heap | |
| An order of courses that respects prerequisites | precedence constraints | topological sort | |
| Number of friend groups as friendships are announced | connectivity under merges only | union-find | |
| Cheapest cables connecting all buildings | connect everything, minimum total | Kruskal's or Prim's algorithm | |
| Every placement of non-attacking queens, | enumerate; tiny | backtracking with pruning | exponential, fine at this size |
| Edit distance of two strings of length up to 5,000 | two sequences; overlapping choices | a DP table | |
| Shortest route through all of points | subsets as state | Held–Karp bitmask DP | |
| Most meetings one person can attend | a provably safe choice | greedy by earliest finish |
In a grid maze, stepping to a neighboring open cell is free and breaking through a wall cell costs 1. Find the fewest walls to break on the way from S to E. Which technique fits best?
- Plain BFS, counting moves
- BFS with a deque: free steps go to the front, wall breaks to the back
- DFS that tries every path
- DP over the rows, from top to bottom
Show the answer
B. BFS with a deque: free steps go to the front, wall breaks to the back
Edge costs are 0 or 1, so a deque keeps the frontier sorted by cost: neighbors reached for free go to the front, those that cost a wall go to the back. Every cell is settled once, for cells. This is 0-1 BFS; Dijkstra's algorithm also works, with an extra factor.
The brute force: baseline and oracle
The brute force earns its place twice. First as a baseline: its cost against the budget says how much waste must go, and the waste is usually visible in its loops, such as a sum recomputed for every window or a pair checked from both sides.
Then as an oracle: once a fast solution exists, run both on thousands of tiny random inputs and compare. The oracle only has to be obviously correct, not fast. Here it exposes the look-alike from the map, a window that counts subarrays with sum :
import random
from collections import Counter
def count_brute(a, k): # the oracle: obviously right, slow is fine
n = len(a)
return sum(sum(a[i:j]) == k for i in range(n) for j in range(i + 1, n + 1))
def count_window(a, k): # a sliding window: right only if every a[i] > 0
total = s = lo = 0
for hi in range(len(a)):
s += a[hi]
while s > k:
s -= a[lo]
lo += 1
total += s == k
return total
def count_prefix(a, k): # O(n) expected: earlier prefix sums equal to p - k
seen, p, total = Counter({0: 1}), 0, 0
for x in a:
p += x
total += seen[p - k]
seen[p] += 1
return total
random.seed(1)
for t in range(1, 1001):
a = [random.randint(-3, 3) for _ in range(random.randint(1, 6))]
k = random.randint(1, 3)
want = count_brute(a, k)
assert count_prefix(a, k) == want
if count_window(a, k) != want:
print(t, a, k, want, count_window(a, k)) # 3 [2, 0, 3, -2] 1 2 0
breakThe third random test already fails: in two subarrays sum to 1, and , and the window finds neither, because it dropped the 2, the 0 and the 3 before the arrived. The prefix-sum solution passes all 1,000 tests.
Run it on all inputs of length 2 and the smallest failures appear, such as with . Zeros break the window too: in with , both and sum to 1, but the window counts at most one subarray per right end. The code comment "every " is a precondition, and the stress test is how you discover you needed it.
In an interview, state the brute force and its cost first, then name the waste and the technique that removes it: interviewers grade the path, not just the destination. In a contest, the first problems usually reward careful implementation and a short greedy or counting argument, the middle ones the core techniques of this course, and the last ones a combination of two, such as binary search on the answer around a flow check, or a DP whose transitions need a segment tree.
Key takeaways
- Recognition is a procedure: restate the input, output and objective; classify the question as decision, search, optimization or counting; find the structure; read the budget; test the candidates on tiny cases; then prove or stress-test.
- Properties license techniques: order licenses two pointers and binary search, a question that flips once licenses binary search on the answer, closure under shrinking licenses a sliding window, overlapping subproblems license DP, and an exchange argument licenses greedy.
- Changing the question changes the technique: on one set of meetings, deciding, maximizing the count, minimizing the rooms, maximizing the value and counting the sets call for sorting, greedy, a sweep and DP.
- Look-alikes fail for reasons you can name: negative values break windows, some coin systems break greedy, cycles make longest path NP-hard, and negative edges break Dijkstra's algorithm.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which property makes the variable sliding window correct for "the longest subarray with property "?
- The array is sorted
- is closed under shrinking: every sub-window of a valid window is valid
- can be checked in time
- All elements are distinct
Show the answer
B. is closed under shrinking: every sub-window of a valid window is valid
Closure makes the smallest valid left end non-decreasing in , so the left pointer never has to move back, and at most moves find the answer.
Coins of 1, 3 and 4: pay amounts up to with as few coins as possible. What should you use?
- Greedy: always take the largest coin that fits
- Dynamic programming:
- Two pointers over the sorted coin values
- Binary search on the number of coins
Show the answer
B. Dynamic programming:
Greedy pays 6 as , but uses two coins, so the largest coin is not a safe choice for this coin system. The DP over amounts costs , here steps.
You must find a heaviest path from to in a directed acyclic graph with vertices and edges. Which approach is correct and fits in a second?
- None: longest path is NP-hard
- DP in topological order:
- Dijkstra's algorithm with every weight negated
- Bellman–Ford with every weight negated, since there are no cycles
Show the answer
B. DP in topological order:
In a DAG every edge points forward in a topological order, so processing vertices in that order sees every predecessor first: . Longest path is NP-hard only in general graphs, where it would find Hamiltonian paths.
Given integers up to , decide whether some subset sums to exactly . Which approach fits the budget?
- DP over all sums from 0 to
- Try all subsets
- Split the numbers into two halves, list each half's subset sums, sort one list, and binary search it for each sum of the other
- Greedily take the largest number that still fits
Show the answer
C. Split the numbers into two halves, list each half's subset sums, sort one list, and binary search it for each sum of the other
Meet in the middle: two lists of sums, one sort and binary searches, roughly steps in all. The small with huge values is the signal.
Go deeper
- Constraints & Complexity Budgets · Read n and the time limit, and know which complexities fit.
- Problems in Disguise: Modeling & Reductions · When a puzzle is secretly a graph, a flow or a dynamic program.
- Stress Testing & Debugging Algorithms · Brute-force oracles, random tests, edge cases and invariant checks.
Further reading
- G. Pólya, How to Solve It (Princeton University Press, 1945).
- J. Kleinberg & É. Tardos, Algorithm Design (Pearson, 2005), §4.1 (interval scheduling and partitioning) and §6.1 (weighted interval scheduling).
- S. S. Skiena, The Algorithm Design Manual, 3rd ed. (Springer, 2020).
- S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020).