Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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.

  1. What are the input, the output and the objective? Restate the problem in one sentence with symbols: "given a[0..n−1]a[0..n-1], find the largest a[l]+⋯+a[r]a[l] + \dots + a[r] over all l≤rl \le r". Many wrong answers solve a misread problem.
  2. 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.
  3. 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.
  4. What does the budget allow? The constraints, at about 10810^8 simple steps per second, cap the complexity.
  5. Which candidates survive? List the techniques the structure licenses and the budget allows, and run each on your tiny examples, especially the awkward ones.
  6. 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 n≤2×105n \le 2 \times 10^5 array elements and q≤2×105q \le 2 \times 10^5 queries. What total cost should you aim for, and what does that say about each query?

About (n+q)log⁡n≈4×105×18≈7×106(n + q)\log n \approx 4 \times 10^5 \times 18 \approx 7 \times 10^6 steps. Answering each query by scanning the array costs O(nq)=4×1010O(nq) = 4 \times 10^{10}, far too slow, so each query must cost O(1)O(1) or O(log⁡n)O(\log n) 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 n≤2×105n \le 2 \times 10^5 meetings, each a half-open interval [si,fi)[s_i, f_i), so that a meeting ending at 6 does not clash with one starting at 6:

QuestionKindTechniqueCost
Can one person attend all of them?decisionsort by start time, compare neighborsO(nlog⁡n)O(n \log n)
The most meetings one person can attendoptimizationgreedy: earliest finish first, proved by an exchange argumentO(nlog⁡n)O(n \log n)
The fewest rooms that host them alloptimizationsweep line over sorted endpoints (or a heap of end times): the answer is the largest number of meetings in progress at onceO(nlog⁡n)O(n \log n)
Meetings have values: the largest total value one person can attendoptimizationDP over meetings sorted by finish, with binary search for the last compatible oneO(nlog⁡n)O(n \log n)
How many sets of pairwise compatible meetings exist, modulo 109+710^9 + 7?countingthe same DP, adding instead of maximizingO(nlog⁡n)O(n \log n)
Five questions about one input. Greedy, a sweep and dynamic programming each win somewhere.

The last two rows share a recurrence. Sort the meetings by finish time and let p(j)p(j) be the number of meetings, among the first j−1j - 1, that finish by sjs_j: because the list is sorted by finish, they are exactly a prefix, found by binary search. Meeting jj is either left out or taken together with a compatible set from that prefix:

OPT(j)=max⁡(OPT(j−1), vj+OPT(p(j))),W(j)=W(j−1)+W(p(j)),\mathrm{OPT}(j) = \max\big(\mathrm{OPT}(j-1),\ v_j + \mathrm{OPT}(p(j))\big), \qquad W(j) = W(j-1) + W(p(j)),

with OPT(0)=0\mathrm{OPT}(0) = 0 and W(0)=1W(0) = 1 (the empty set counts). Both recurrences agree with brute force on thousands of random instances.

Check your understanding

For the weighted question, a friend proposes: take the most valuable meeting, discard everything that overlaps it, and repeat. Is that right?

  1. Yes: an exchange argument shows the most valuable meeting is always safe
  2. Yes, provided ties are broken by earliest finish
  3. No: with [0,10)[0, 10) worth 10 and [0,5)[0, 5), [5,10)[5, 10) worth 6 each, it takes 10 while 12 is possible; use the DP
  4. No, but taking meetings by earliest finish instead fixes it
Show the answer

C. No: with [0,10)[0, 10) worth 10 and [0,5)[0, 5), [5,10)[5, 10) 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: OPT=max⁡(10,6+6)=12\mathrm{OPT} = \max(10, 6 + 6) = 12 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 problemLicensesWhy it works
sorted data, or data you may sort without losing the answertwo pointers; binary searchone comparison rules out a whole row of pairs, or half the range
a yes/no question that flips once as a value growsbinary search on the answerthe answer is the boundary of a monotone predicate
contiguity, with a condition closed under shrinkingsliding windowthe left end never moves back (proved below)
an operation with an inverse: sums, XOR, countsprefix sumsa range is the difference of two prefixes
an associative operation, with updatessegment tree, Fenwick treeevery range splits into O(log⁡n)O(\log n) stored pieces
optimal substructure and overlapping subproblemsdynamic programmingeach subproblem is solved once, in an order that respects its dependencies
the greedy-choice propertygreedyan exchange argument turns any optimum into one containing the greedy choice
unit edge costs; nonnegative costs; no cyclesBFS; Dijkstra; DP in topological orderlayers by distance; settled distances never improve; every edge points forward
one small parameter kk, such as k≤20k \le 20exponential in kk only: bitmasks, meet in the middle2k2^k or 2k/22^{k/2} times a polynomial in nn
Each row has its own lesson in this course, with the proof.
DerivationProof
  1. L(r)  ≤  L(r+1)for every rL(r) \;\le\; L(r+1) \qquad \text{for every } r

    LL never decreases. If a[l..r+1]a[l..r+1] has QQ, so does its sub-window a[l..r]a[l..r]. Apply this with l=L(r+1)l = L(r+1):

  2. lafter r  =  L(r)l_{\text{after } r} \;=\; L(r)

    The loop stops exactly at L(r)L(r). Suppose the left pointer arrives at rr holding L(r−1)≤L(r)L(r-1) \le L(r). For every l<L(r)l < L(r) the window lacks QQ, by the minimality of L(r)L(r), so the loop advances; at l=L(r)l = L(r) the window has QQ, so it stops. By induction on rr:

  3. #moves  ≤  2n,answer  =  max⁡r (r−L(r)+1)\#\text{moves} \;\le\; 2n, \qquad \text{answer} \;=\; \max_{r}\,\big(r - L(r) + 1\big)

    At most 2n2n moves. The right end moves nn times; the left end never moves back and never passes nn. With an O(1)O(1) update of the window's state per move (a running sum, a table of counts), the whole scan is linear:

  4. ∑[−3,5,−3]=−1≤0,∑[5,−3]=2>0\textstyle\sum [-3, 5, -3] = -1 \le 0, \qquad \sum [5, -3] = 2 > 0

    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 SS", closure holds when every value is nonnegative, since shrinking only lowers the sum. With negatives it fails: for S=0S = 0, the window [−3,5,−3][-3, 5, -3] has sum −1-1, but its sub-window [5,−3][5, -3] sums to 2.

When closure fails, a different structure takes over. For the longest subarray with sum at most SS and negative values allowed, write the condition on prefix sums, P[i]≥P[j]−SP[i] \ge P[j] - S with i<ji < j: only the start positions where PP reaches a new maximum can be the best start, those running maxima are sorted, and a binary search over them answers each jj, for O(nlog⁡n)O(n \log n) 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 briefSignalTechniqueCost
Two values in a sorted array with sum TTsorted; a pairtwo pointers from both endsO(n)O(n)
Longest substring with no repeated charactercontiguous; the condition survives shrinkingsliding window with last-seen positionsO(n)O(n)
Count subarrays with sum exactly kk, negatives allowedcontiguous; an exact sum; negativesprefix sums and a hash map of their countsO(n)O(n) expected
Range sums, with point updates in betweenranges plus updatesFenwick tree or segment treeO((n+q)log⁡n)O((n + q) \log n)
Maximum of every window of length kka window, but a maximum cannot be subtractedmonotonic dequeO(n)O(n)
For each day, the next warmer daynearest greatermonotonic stackO(n)O(n)
Least daily capacity that ships packages, in order, within DD days"least xx such that"; a check that flips oncebinary search on the answer, with a greedy checkO(nlog⁡∑w)O(n \log \sum w)
The kk largest values of a long streamtop kk; memory for kk values onlymin-heap of size kkO(nlog⁡k)O(n \log k)
Two values with sum TT, unsortedlook up each complementhash setO(n)O(n) expected
Longest substring that occurs at least twicerepeated substringssuffix array and LCP array, or binary search with a rolling hashO(nlog⁡n)O(n \log n)
Count pairs i<ji < j with a[i]>a[j]a[i] > a[j]pairs defined by ordermerge sort, counting while mergingO(nlog⁡n)O(n \log n)
Fewest knight moves between two squaresequal-cost moves on an implicit graphBFSO(squares)O(\text{squares})
Cheapest route, with nonnegative faresweighted shortest pathDijkstra's algorithm with a binary heapO((V+E)log⁡V)O((V + E) \log V)
An order of courses that respects prerequisitesprecedence constraintstopological sortO(V+E)O(V + E)
Number of friend groups as friendships are announcedconnectivity under merges onlyunion-findO(m α(n))O(m\,\alpha(n))
Cheapest cables connecting all buildingsconnect everything, minimum totalKruskal's or Prim's algorithmO(Elog⁡E)O(E \log E)
Every placement of nn non-attacking queens, n≤12n \le 12enumerate; tiny nnbacktracking with pruningexponential, fine at this size
Edit distance of two strings of length up to 5,000two sequences; overlapping choicesa DP tableO(nm)O(nm)
Shortest route through all of n≤16n \le 16 pointssubsets as stateHeld–Karp bitmask DPO(2nn2)O(2^n n^2)
Most meetings one person can attenda provably safe choicegreedy by earliest finishO(nlog⁡n)O(n \log n)
Costs are worst case unless marked expected; α\alpha is the inverse Ackermann function, at most 4 for any practical nn.
Check your understanding

In a 1000×10001000 \times 1000 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?

  1. Plain BFS, counting moves
  2. BFS with a deque: free steps go to the front, wall breaks to the back
  3. DFS that tries every path
  4. 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, O(V+E)O(V + E) for 10610^6 cells. This is 0-1 BFS; Dijkstra's algorithm also works, with an extra log⁡\log 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 kk:

python
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
        break

The third random test already fails: in [2,0,3,−2][2, 0, 3, -2] two subarrays sum to 1, [3,−2][3, -2] and [0,3,−2][0, 3, -2], and the window finds neither, because it dropped the 2, the 0 and the 3 before the −2-2 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 [2,−1][2, -1] with k=1k = 1. Zeros break the window too: in [0,1][0, 1] with k=1k = 1, both [0,1][0, 1] and [1][1] sum to 1, but the window counts at most one subarray per right end. The code comment "every a[i]>0a[i] > 0" 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.

Question 1

Which property makes the variable sliding window correct for "the longest subarray with property QQ"?

  1. The array is sorted
  2. QQ is closed under shrinking: every sub-window of a valid window is valid
  3. QQ can be checked in O(1)O(1) time
  4. All elements are distinct
Show the answer

B. QQ is closed under shrinking: every sub-window of a valid window is valid

Closure makes the smallest valid left end L(r)L(r) non-decreasing in rr, so the left pointer never has to move back, and at most 2n2n moves find the answer.

Question 2

Coins of 1, 3 and 4: pay amounts up to 10510^5 with as few coins as possible. What should you use?

  1. Greedy: always take the largest coin that fits
  2. Dynamic programming: best[a]=1+min⁡c≤abest[a−c]\mathrm{best}[a] = 1 + \min_{c \le a} \mathrm{best}[a - c]
  3. Two pointers over the sorted coin values
  4. Binary search on the number of coins
Show the answer

B. Dynamic programming: best[a]=1+min⁡c≤abest[a−c]\mathrm{best}[a] = 1 + \min_{c \le a} \mathrm{best}[a - c]

Greedy pays 6 as 4+1+14 + 1 + 1, but 3+33 + 3 uses two coins, so the largest coin is not a safe choice for this coin system. The DP over amounts costs O(amount×coins)O(\text{amount} \times \text{coins}), here 3×1053 \times 10^5 steps.

Question 3

You must find a heaviest path from ss to tt in a directed acyclic graph with 10510^5 vertices and 10510^5 edges. Which approach is correct and fits in a second?

  1. None: longest path is NP-hard
  2. DP in topological order: best[v]=max⁡(u,v)(best[u]+w(u,v))\mathrm{best}[v] = \max_{(u,v)} \big(\mathrm{best}[u] + w(u, v)\big)
  3. Dijkstra's algorithm with every weight negated
  4. Bellman–Ford with every weight negated, since there are no cycles
Show the answer

B. DP in topological order: best[v]=max⁡(u,v)(best[u]+w(u,v))\mathrm{best}[v] = \max_{(u,v)} \big(\mathrm{best}[u] + w(u, v)\big)

In a DAG every edge points forward in a topological order, so processing vertices in that order sees every predecessor first: O(V+E)O(V + E). Longest path is NP-hard only in general graphs, where it would find Hamiltonian paths.

Question 4

Given n≤40n \le 40 integers up to 101210^{12}, decide whether some subset sums to exactly SS. Which approach fits the budget?

  1. DP over all sums from 0 to SS
  2. Try all 2402^{40} subsets
  3. Split the numbers into two halves, list each half's 2202^{20} subset sums, sort one list, and binary search it for each sum of the other
  4. Greedily take the largest number that still fits
Show the answer

C. Split the numbers into two halves, list each half's 2202^{20} subset sums, sort one list, and binary search it for each sum of the other

Meet in the middle: two lists of 220≈1062^{20} \approx 10^6 sums, one sort and 10610^6 binary searches, roughly 4×1074 \times 10^7 steps in all. The small nn with huge values is the signal.

Go deeper

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).