Simple Algorithm
Algorithms & Data Structures · Brute Force · 18 min

Problem Solving & Hard Problems

Choosing the right technique, and recognizing problems no fast algorithm is known to solve.

You get 200,000 numbers and one second. The obvious double loop checks about 2×10102 \times 10^{10} pairs, more than three minutes of work. Almost every fast algorithm in this course began life as such a brute force: this lesson is about finding the waste in it and the technique that removes it, and about recognizing the problems where nobody knows how to remove it.

What you’ll learn

  • Apply a five-step method to an unfamiliar problem: tiny examples, a brute force and its cost, the budget set by the constraints, the waste and the technique that removes it, and a test against the brute force.
  • Read a problem's constraints and tell which running times fit in about a second.
  • Map the signals in a problem statement to the technique this course teaches for them.
  • Explain P, NP and NP-completeness in plain words, using the traveling salesman and satisfiability as examples.
  • Choose a sensible plan for an NP-hard problem: exact search for small inputs, approximation, heuristics or special structure.

From brute force to fast: a method

Every problem in this course was once solved slowly. The slow solution is not a failure: it is step two of a method that works on problems you have never seen.

  1. Understand. Work two or three tiny examples by hand, including awkward ones: empty input, one element, duplicates, negative numbers.
  2. Brute force. Write the most obvious correct algorithm and count its steps.
  3. Budget. Read the constraints: how large can the input be, and how many steps fit in the time limit?
  4. Find the waste. Ask what work the brute force repeats or could skip, and which technique removes exactly that waste.
  5. Verify. Run the fast solution against the brute force on many small random inputs.

Try it on a classic: a sorted array and a target TT. Do two of the numbers add up to TT?

The brute force checks every pair, n(n−1)/2n(n-1)/2 of them: 45 pairs for 10 numbers, about 2×10102 \times 10^{10} for n=200,000n = 200{,}000. At roughly 10810^8 simple steps per second (a rule of thumb for compiled code) that is over three minutes. The waste: it ignores that the array is sorted. If the smallest number plus the largest is already too big, then the largest number is too big with every partner, and one comparison rules out a whole row of pairs. That idea is the two-pointer technique.

The constraints set the budget

Read the constraints before you design anything. A judge, or a production system, gives you a time limit, and a computer does roughly 10810^8 simple operations per second in a compiled language such as C++ (Python is often 10 to 100 times slower). So the largest nn tells you which running times are even possible: that is your complexity budget.

Predict before you look

An O(n2)O(n^2) algorithm makes about n2n^2 simple steps. With n=105n = 10^5 and 10810^8 steps per second, about how many seconds does it run?

Show the answer

100 s

n2=1010n^2 = 10^{10} steps, and 1010/108=10010^{10} / 10^8 = 100 seconds: a hundred times over a one-second limit. An O(nlog⁡n)O(n \log n) algorithm needs about 105×17≈1.7×10610^5 \times 17 \approx 1.7 \times 10^6 steps, under 20 milliseconds. At this size the exponent decides everything.

nn up to aboutRunning time that fitsWhat it suggests
10–11O(n!)O(n!)try every ordering
20–25O(2n⋅n)O(2^n \cdot n)every subset: backtracking or DP over subsets
40O(2n/2)O(2^{n/2})split into halves: meet in the middle
500O(n3)O(n^3)three nested loops: all-pairs paths, interval DP
5,000O(n2)O(n^2)all pairs; a two-dimensional DP table
10610^6O(nlog⁡n)O(n \log n)sorting, binary search, heaps, segment trees
10810^8O(n)O(n)one pass: two pointers, windows, prefix sums, hashing
moreO(log⁡n)O(\log n) or O(1)O(1)a formula, or binary search on the answer
A rule of thumb for a 1–2 second limit. It leaves room for constant factors, which is why it is more cautious than the widget's exact counts.

Signals in the statement: arrays, strings and lookups

With the budget known, look for the structure the brute force ignores. Certain words and shapes in a statement point straight to the technique that exploits them. This table and the one in the next step summarize the whole course; every technique in them has its own lesson.

The statement mentions…Reach forTypical cost
a sorted array; a pair or triple with a given sumTwo pointersO(n)O(n) after sorting
a contiguous stretch (subarray, substring) whose condition stays true when it shrinksSliding windowO(n)O(n)
many sums over ranges of an array that does not changePrefix sumsO(1)O(1) per query after O(n)O(n)
range sums or minimums while values keep changingSegment tree or Fenwick treeO(log⁡n)O(\log n) per operation
"the next greater", "the previous smaller"Monotonic stackO(n)O(n)
"the least xx such that…", "minimize the maximum"Binary search on the answerO(log⁡(range))O(\log(\text{range})) checks
"have I seen it?", "how many of each?"Hash mapO(1)O(1) expected per operation
many words that share prefixesTrieO(word length)O(\text{word length})
"the kk largest", "repeatedly take the smallest"HeapO(log⁡n)O(\log n) per operation
a pattern to find in a long textKMP, the Z-function or a rolling hashO(n+m)O(n + m)
Signals for sequences, strings and lookups. Here nn is the input size and mm the pattern length.
Check your understanding

You have a year of daily temperatures, n≤105n \le 10^5 days. For each day you must report how many days pass until a warmer one. Which technique fits?

  1. Sort the temperatures, then binary search
  2. A monotonic stack of the days still waiting for a warmer one
  3. A sliding window of fixed length
  4. Two pointers walking in from both ends
Show the answer

B. A monotonic stack of the days still waiting for a warmer one

Scan the days in order and keep a stack of days not yet answered, their temperatures decreasing from bottom to top. Each new day pops, and answers, every waiting day that is colder. Every day is pushed once and popped at most once, so the scan takes O(n)O(n). "The next larger element" is the signature of a monotonic stack.

Check your understanding

You get n≤2×105n \le 2 \times 10^5 integers, some of them negative, and must count the contiguous subarrays whose sum is exactly kk. Which technique fits?

  1. A sliding window that shrinks from the left while the sum exceeds kk
  2. Prefix sums, with a hash map counting the prefix sums seen so far
  3. Sort the array, then two pointers
  4. Try every subarray
Show the answer

B. Prefix sums, with a hash map counting the prefix sums seen so far

With prefix sums P[0]=0P[0] = 0 and P[i+1]=P[i]+a[i]P[i+1] = P[i] + a[i], the subarray a[i..j−1]a[i..j-1] (inclusive) sums to P[j]−P[i]P[j] - P[i]. So scan once, and at each P[j]P[j] add the number of earlier prefix sums equal to P[j]−kP[j] - k, kept in a hash map: O(n)O(n) expected time.

Signals in the statement: choices and connections

Graphs hide in many statements that never say "graph": cities and roads, but also tasks and their prerequisites, people and friendships, or the positions of a puzzle and the moves between them. Choice problems hide too, whenever an answer is built from a sequence of decisions.

The statement mentions…Reach forTypical cost
the fewest moves or steps, every move costing the sameBreadth-first searchO(V+E)O(V + E)
the cheapest route, with no negative costsDijkstra's algorithmO((V+E)log⁡V)O((V + E) \log V)
"X must come before Y"Topological sortO(V+E)O(V + E)
"are these two connected?" while groups keep mergingUnion-findnearly O(1)O(1) per operation
connect every site as cheaply as possibleMinimum spanning treeO(Elog⁡E)O(E \log E)
pair people with jobs or time slotsbipartite matching, or network flowpolynomial
"list every subset, arrangement or placement"Backtrackingexponential, cut down by pruning
"how many ways", "the best total", with choices whose consequences overlapDynamic programmingstates × choices per state
a choice you can prove never hurtsGreedyoften O(nlog⁡n)O(n \log n)
Signals for graphs and choices. VV and EE count a graph's vertices and edges; the vertices may be words, board positions or schedules.

The last two rows are easy to confuse. A greedy algorithm commits to the best-looking choice and never reconsiders it; dynamic programming tries every choice but solves each subproblem only once. Greedy is faster, but it is correct only when a proof, usually an exchange argument, shows that the best-looking choice is always safe. Try it on coins.

Check your understanding

A word game: change one letter at a time, and every word along the way must be in a dictionary of 10410^4 four-letter words. What is the fewest number of changes that turns COLD into WARM? Which technique fits?

  1. Depth-first search from COLD
  2. Breadth-first search over words, joining two words when they differ in one letter
  3. Greedy: always change a letter to match WARM
  4. Dynamic programming over the four letter positions
Show the answer

B. Breadth-first search over words, joining two words when they differ in one letter

Words are vertices and one-letter changes are edges, all of the same cost, so the fewest changes is a shortest path in an unweighted graph: BFS, in O(V+E)O(V + E). The graph is never written down in advance; the neighbors of a word are generated when it is visited, an implicit graph. One shortest answer is COLD, CORD, CARD, WARD, WARM: four changes, the minimum, since all four letters differ.

When nothing fast is known

A delivery van must visit nn stops and return to the depot along the shortest possible route. This is the traveling salesman problem. The brute force fixes the depot and tries every order of the other stops. A route and its reverse have the same length, so there are (n−1)!/2(n-1)!/2 different tours to compare.

Run the method on it. The brute force is clear, its cost is not: factorials grow faster than any budget can follow.

StopsTours, (n−1)!/2(n-1)!/2Time at 10810^8 tours per second
82,52025 microseconds
10181,4402 milliseconds
154.4×10104.4 \times 10^{10}7 minutes
206.1×10166.1 \times 10^{16}19 years
253.1×10233.1 \times 10^{23}98 million years
Optimistic times: measuring each tour really costs about nn additions, not one step.

Smarter exact algorithms exist. The Held–Karp dynamic program (1962) remembers, for every set of visited cities and every last city, the shortest way to get there: about n22nn^2 2^n steps, some 4×1084 \times 10^8 for 20 cities, seconds instead of 19 years. But that is still exponential, and nobody knows an algorithm for the traveling salesman whose running time is a polynomial in nn. The problem is NP-hard.

Easy to check, hard to find

Every problem in that list shares one pattern. Checking a proposed answer is easy: add up a tour's length, or test each rule. Finding an answer seems to require search. Complexity theory makes the pattern precise:

  • P is the class of yes-or-no problems that can be solved in polynomial time, O(nk)O(n^k) for some fixed kk.
  • NP is the class of yes-or-no problems whose "yes" answers come with a certificate that a polynomial-time verifier can check. "Is there a tour of length at most LL?" is in NP: the certificate is the tour itself.
  • A problem is NP-complete if it is in NP and every problem in NP can be translated into it by a polynomial-time reduction. So a fast algorithm for any one NP-complete problem would give fast algorithms for all of NP.

This problem, satisfiability (SAT), was the first one proved NP-complete, by Stephen Cook in 1971 and independently by Leonid Levin. In 1972 Richard Karp showed that 21 more problems are NP-complete, coloring and the Hamiltonian cycle among them, and thousands are known today.

Faced with an NP-hard problem, practitioners choose one of four routes:

  1. Search exactly when the input is small. Backtracking with pruning, dynamic programming over subsets, or meet in the middle handle 20 to 40 items, and modern SAT solvers settle many industrial formulas with millions of variables.
  2. Approximate, with a guarantee. For example, a tour at most 1.5 times the optimum when the distances obey the triangle inequality.
  3. Use a heuristic. Fast methods with no guarantee that work well in practice, such as nearest neighbor followed by local improvements.
  4. Exploit special structure. The same problem may become easy on trees, on bipartite graphs, or when one parameter is small.
Optimized lessonWhat you will do there
Recognizing the Right TechniqueTurn the signals into a systematic process, and study a map of twenty problem shapes, with the look-alikes that fool people.
P, NP & NP-CompletenessDefine certificates, verifiers and reductions precisely, and prove that 3-SAT reduces to independent set.
Approximation AlgorithmsProve guarantees such as "at most twice the optimum" for vertex cover and the metric traveling salesman.
Coping with NP-HardnessBeat brute force exactly: fixed-parameter algorithms, faster exponential algorithms and SAT solvers.
In the Optimized lessons, each idea of this one gets its precise definitions, proofs and price.

Key takeaways

  • Solve new problems with a method: work tiny examples, write the brute force and count its cost, read the budget from the constraints, find the waste, and test the fast solution against the brute force.
  • About 10810^8 simple steps per second is the rule of thumb: n≤106n \le 10^6 allows O(nlog⁡n)O(n \log n), n≤5000n \le 5000 allows O(n2)O(n^2), and n≤20n \le 20 allows exponential search.
  • Signals point to techniques: sorted pairs to two pointers, a contiguous stretch with a condition that survives shrinking to a sliding window, range sums to prefix sums, "minimize the maximum" to binary search on the answer, fewest moves to BFS, overlapping choices to dynamic programming.
  • NP problems have answers that are easy to check. NP-complete problems such as SAT, 3-coloring and the traveling salesman are the hardest of them, and no polynomial-time algorithm is known for any; whether P = NP is open.
  • NP-hard is not hopeless: search exactly when the input is small, approximate with a guarantee, use heuristics, or exploit special structure.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A problem says n≤20n \le 20. Which of these running times is the slowest one that still fits in about a second?

  1. O(n3)O(n^3)
  2. O(2n⋅n)O(2^n \cdot n)
  3. O(n!)O(n!)
  4. O(nlog⁡n)O(n \log n)
Show the answer

B. O(2n⋅n)O(2^n \cdot n)

220⋅20≈2×1072^{20} \cdot 20 \approx 2 \times 10^7 steps fit easily, while 20!≈2.4×101820! \approx 2.4 \times 10^{18} steps would take about 770 years at 10810^8 per second. A bound as small as 20 is a hint that the intended solution looks at every subset, by backtracking or by dynamic programming over subsets.

Question 2

Find the length of the longest substring with no repeated character in a string of length 10510^5. Which technique solves it in O(n)O(n)?

  1. Binary search on the length
  2. A sliding window: grow it on the right, and shrink it on the left past the repeated character
  3. Dynamic programming over all pairs of positions (i,j)(i, j)
  4. Sort the characters first
Show the answer

B. A sliding window: grow it on the right, and shrink it on the left past the repeated character

"No repeated character" stays true when a window shrinks, so the window's left end only ever moves right. Each end moves at most nn times, and a table of the last position of each character makes every move O(1)O(1).

Question 3

What does it mean for a problem to be in NP?

  1. It cannot be solved in polynomial time
  2. A proposed "yes" answer can be checked in polynomial time
  3. It needs exponential time on every input
  4. It is at least as hard as every problem in P
Show the answer

B. A proposed "yes" answer can be checked in polynomial time

NP is the class of decision problems whose "yes" instances have certificates, such as a tour or a truth assignment, that a polynomial-time algorithm can check. Every problem in P is in NP too: just solve it and ignore the certificate.

Question 4

A delivery company plans a route through 2,000 stops every morning, an instance of the traveling salesman problem. What is the sensible plan?

  1. Brute force over all orders, on a faster computer
  2. Held–Karp's exact dynamic program
  3. A fast heuristic, such as nearest neighbor improved by local moves, accepting a slightly longer route
  4. Dijkstra's algorithm from the depot
Show the answer

C. A fast heuristic, such as nearest neighbor improved by local moves, accepting a slightly longer route

Exact methods are exponential here: brute force faces 1999!/21999!/2 tours, and Held–Karp about 20002⋅220002000^2 \cdot 2^{2000} steps. A heuristic produces a good route in seconds, and approximation algorithms can even guarantee how close it is: within 1.5 times the optimum when distances obey the triangle inequality, as road distances do.

Question 5

Which of these graph problems has a known polynomial-time algorithm?

  1. Is there a cycle that visits every vertex exactly once?
  2. Can the vertices be colored with 3 colors so that no edge joins two vertices of the same color?
  3. Is there a closed walk that uses every edge exactly once?
  4. What is the longest simple path between two given vertices?
Show the answer

C. Is there a closed walk that uses every edge exactly once?

That is an Euler tour. If all the edges lie in one connected piece, such a walk exists exactly when every vertex has even degree, which takes linear time to check, and Hierholzer's algorithm builds it in O(V+E)O(V + E). Its vertex version, the Hamiltonian cycle, is NP-complete: two problems can look alike and sit on opposite sides of the P vs NP line.

Go deeper

Further reading

  • S. S. Skiena, The Algorithm Design Manual, 3rd ed. (Springer, 2020).
  • A. Laaksonen, Competitive Programmer's Handbook (2018), free online.