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 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.
- Understand. Work two or three tiny examples by hand, including awkward ones: empty input, one element, duplicates, negative numbers.
- Brute force. Write the most obvious correct algorithm and count its steps.
- Budget. Read the constraints: how large can the input be, and how many steps fit in the time limit?
- Find the waste. Ask what work the brute force repeats or could skip, and which technique removes exactly that waste.
- 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 . Do two of the numbers add up to ?
The brute force checks every pair, of them: 45 pairs for 10 numbers, about for . At roughly 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 simple operations per second in a compiled language such as C++ (Python is often 10 to 100 times slower). So the largest tells you which running times are even possible: that is your complexity budget.
An algorithm makes about simple steps. With and steps per second, about how many seconds does it run?
Show the answer
100 s
steps, and seconds: a hundred times over a one-second limit. An algorithm needs about steps, under 20 milliseconds. At this size the exponent decides everything.
| up to about | Running time that fits | What it suggests |
|---|---|---|
| 10–11 | try every ordering | |
| 20–25 | every subset: backtracking or DP over subsets | |
| 40 | split into halves: meet in the middle | |
| 500 | three nested loops: all-pairs paths, interval DP | |
| 5,000 | all pairs; a two-dimensional DP table | |
| sorting, binary search, heaps, segment trees | ||
| one pass: two pointers, windows, prefix sums, hashing | ||
| more | or | a formula, or binary search on the answer |
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 for | Typical cost |
|---|---|---|
| a sorted array; a pair or triple with a given sum | Two pointers | after sorting |
| a contiguous stretch (subarray, substring) whose condition stays true when it shrinks | Sliding window | |
| many sums over ranges of an array that does not change | Prefix sums | per query after |
| range sums or minimums while values keep changing | Segment tree or Fenwick tree | per operation |
| "the next greater", "the previous smaller" | Monotonic stack | |
| "the least such that…", "minimize the maximum" | Binary search on the answer | checks |
| "have I seen it?", "how many of each?" | Hash map | expected per operation |
| many words that share prefixes | Trie | |
| "the largest", "repeatedly take the smallest" | Heap | per operation |
| a pattern to find in a long text | KMP, the Z-function or a rolling hash |
You have a year of daily temperatures, days. For each day you must report how many days pass until a warmer one. Which technique fits?
- Sort the temperatures, then binary search
- A monotonic stack of the days still waiting for a warmer one
- A sliding window of fixed length
- 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 . "The next larger element" is the signature of a monotonic stack.
You get integers, some of them negative, and must count the contiguous subarrays whose sum is exactly . Which technique fits?
- A sliding window that shrinks from the left while the sum exceeds
- Prefix sums, with a hash map counting the prefix sums seen so far
- Sort the array, then two pointers
- Try every subarray
Show the answer
B. Prefix sums, with a hash map counting the prefix sums seen so far
With prefix sums and , the subarray (inclusive) sums to . So scan once, and at each add the number of earlier prefix sums equal to , kept in a hash map: 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 for | Typical cost |
|---|---|---|
| the fewest moves or steps, every move costing the same | Breadth-first search | |
| the cheapest route, with no negative costs | Dijkstra's algorithm | |
| "X must come before Y" | Topological sort | |
| "are these two connected?" while groups keep merging | Union-find | nearly per operation |
| connect every site as cheaply as possible | Minimum spanning tree | |
| pair people with jobs or time slots | bipartite matching, or network flow | polynomial |
| "list every subset, arrangement or placement" | Backtracking | exponential, cut down by pruning |
| "how many ways", "the best total", with choices whose consequences overlap | Dynamic programming | states × choices per state |
| a choice you can prove never hurts | Greedy | often |
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.
A word game: change one letter at a time, and every word along the way must be in a dictionary of four-letter words. What is the fewest number of changes that turns COLD into WARM? Which technique fits?
- Depth-first search from COLD
- Breadth-first search over words, joining two words when they differ in one letter
- Greedy: always change a letter to match WARM
- 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 . 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 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 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.
| Stops | Tours, | Time at tours per second |
|---|---|---|
| 8 | 2,520 | 25 microseconds |
| 10 | 181,440 | 2 milliseconds |
| 15 | 7 minutes | |
| 20 | 19 years | |
| 25 | 98 million years |
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 steps, some 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 . 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, for some fixed .
- 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 ?" 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:
- 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.
- Approximate, with a guarantee. For example, a tour at most 1.5 times the optimum when the distances obey the triangle inequality.
- Use a heuristic. Fast methods with no guarantee that work well in practice, such as nearest neighbor followed by local improvements.
- Exploit special structure. The same problem may become easy on trees, on bipartite graphs, or when one parameter is small.
| Optimized lesson | What you will do there |
|---|---|
| Recognizing the Right Technique | Turn the signals into a systematic process, and study a map of twenty problem shapes, with the look-alikes that fool people. |
| P, NP & NP-Completeness | Define certificates, verifiers and reductions precisely, and prove that 3-SAT reduces to independent set. |
| Approximation Algorithms | Prove guarantees such as "at most twice the optimum" for vertex cover and the metric traveling salesman. |
| Coping with NP-Hardness | Beat brute force exactly: fixed-parameter algorithms, faster exponential algorithms and SAT solvers. |
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 simple steps per second is the rule of thumb: allows , allows , and 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.
A problem says . Which of these running times is the slowest one that still fits in about a second?
Show the answer
B.
steps fit easily, while steps would take about 770 years at 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.
Find the length of the longest substring with no repeated character in a string of length . Which technique solves it in ?
- Binary search on the length
- A sliding window: grow it on the right, and shrink it on the left past the repeated character
- Dynamic programming over all pairs of positions
- 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 times, and a table of the last position of each character makes every move .
What does it mean for a problem to be in NP?
- It cannot be solved in polynomial time
- A proposed "yes" answer can be checked in polynomial time
- It needs exponential time on every input
- 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.
A delivery company plans a route through 2,000 stops every morning, an instance of the traveling salesman problem. What is the sensible plan?
- Brute force over all orders, on a faster computer
- Held–Karp's exact dynamic program
- A fast heuristic, such as nearest neighbor improved by local moves, accepting a slightly longer route
- 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 tours, and Held–Karp about 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.
Which of these graph problems has a known polynomial-time algorithm?
- Is there a cycle that visits every vertex exactly once?
- Can the vertices be colored with 3 colors so that no edge joins two vertices of the same color?
- Is there a closed walk that uses every edge exactly once?
- 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 . 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
- Recognizing the Right Technique · The signals in a problem statement that point to an algorithm.
- P, NP & NP-Completeness · Easy to check, maybe hard to find: the biggest open question in computer science.
- Approximation Algorithms · Provably near-optimal answers when optimal is out of reach.
- Coping with NP-Hardness · Parameterized and exact algorithms, SAT solvers, and the fine-grained limits of polynomial time.
Further reading
- S. S. Skiena, The Algorithm Design Manual, 3rd ed. (Springer, 2020).
- A. Laaksonen, Competitive Programmer's Handbook (2018), free online.