Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Coding Interview Patterns  Module 33 – Pattern recognition and mixed practice

Which pattern? A decision guide

Map a problem's input shape, question words and limits to the coding patterns that fit, rule the rest out, and choose top-down or bottom-up DP.

  • Intermediate
  • 20 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Map input shapes and question words to candidate patterns
  • Eliminate the patterns that the constraints rule out
  • Recognise when DP is needed and choose top-down or bottom-up
  • Check a pattern choice on small cases before writing the full solution

Before you start

A statement asks for the number of stretches of days whose profits add up to exactly zero, and some days lose money: which pattern do you try first? Choosing a pattern for a coding problem comes down to three readings of the statement: the shape of the input, the words of the question and the size of the limits. Each reading points to a few candidates. A sorted array suggests binary search or two pointers, “count the ways” suggests dynamic programming, and n up to 20 allows an exponential search over subsets. The limits then rule out whatever is too slow, and a check on a small case, by hand or against a brute force: The simplest method that is plainly correct, usually trying every possibility. Said first in a round, it confirms what the problem asks, and later it checks a faster version's answers. More in “A six-step method for any coding problem”, rules out an idea that gives wrong answers. This lesson collects those signals in one table, classifies twelve original problem sketches with the reasoning written out, runs two problems that read alike but need different patterns, and shows when a dynamic program should be written top-down or bottom-up.

Read every statement three times: shape, words, limits

Read the statement three times, each time for one kind of clue, and note what you find before you think about code.

  1. The shape of the input. A sorted array, an unsorted array, a string, a grid, a tree, a list of edges, a set of intervals, or a stream that arrives one item at a time. The shape narrows the field at once: intervals invite sorting by an end point, a list of edges invites a graph search, and a stream rules out anything that needs the whole input first.
  2. The words of the question. “Longest contiguous”, “number of ways”, “minimum cost”, “every combination”, “k-th largest”, “next greater”, “before”, “connected” and “the smallest value such that” each belong to a small family of patterns. The verb matters too: list every answer, count the answers or find the best one are three different problems, even on the same input.
  3. The limits. The largest n and the time limit give a target complexity, which the constraints lesson works out step by step. The limits on the values, the number of queries and whether numbers can be negative matter as much as n.

Say what each reading found in one sentence, for example: “a list of up to 2 × 10⁵ integers, some negative; the number of stretches with a given total”. That sentence is usually enough to pick the first candidate.

Step through the three readings of that statement, one stage at a time:

Interactive · stage by stage Three readings of one statement Step through the readings of one statement. Each stage keeps what its reading found, and the last one names the pattern to try first.
Three readings of one statement, step 5 of 5. Showing The shape of the input (integers, some negative), The question's words (count runs, exact total), The limits (O(n log n); no window), One sentence, one choice (prefix sums + hash map). In focus: One sentence, one choice.The shape of the inputintegers, some negativeThe question's wordscount runs, exact totalThe limitsO(n log n); no windowOne sentence, one choiceprefix sums + hash mapO(n log n) or better

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The statement. The statement: daily profits for up to 2 × 10⁵ days, some of them losses; count the stretches of consecutive days whose total is exactly k. Read it three times, once for each kind of clue, before you think about code.
  2. The shape. First reading, the shape: one list of integers, some of them negative, all there before the question is asked. Windows, prefix sums and hash maps all stay possible.
  3. The words. "Count" asks for a number, not a list of stretches, and "stretches of consecutive days" with "a total of exactly k" are contiguous runs with an exact total.
  4. The limits. n up to 2 × 10⁵ leaves O(n log n) or better, so checking every stretch, about 2 × 10¹⁰ of them, is out. The negative values rule out a sliding window over sums.
  5. One sentence. Said in one sentence: a list of up to 2 × 10⁵ integers, some negative; the number of stretches with a given total. That points to prefix sums with a hash map of how often each running total has occurred.

The figure ends where the summary sentence ends: on one candidate, prefix sums with a hash map, which sketch 3 below confirms.

Checkpoint

Check: Three readings of a statement

  1. Question 1 of 2 In the profits statement of the figure, which reading tells you that checking every stretch is too slow?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The limits: n up to 2 × 10⁵ allows O(n log n) or better, and there are about 2 × 10¹⁰ stretches

    Each reading answers its own question: the shape what the data is, the words what is asked for, and the limits how much work is allowed. At n = 2 × 10⁵ there are about 2 × 10¹⁰ stretches, so the limits cross out checking them all and leave O(n log n) or better.

  2. Question 2 of 2 A statement reads: 'Readings arrive one at a time from a sensor, up to 10⁶ of them; after each one, report the largest value seen so far.' What does the shape reading rule out?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Anything that needs the whole input first, such as sorting all the readings

    The shape of the input is a stream, and a stream rules out anything that needs the whole input first. One variable that keeps the largest value so far answers after every reading, in O(1) each.

A clue suggests a pattern; a property decides it

Each row pairs a clue with the pattern to try first and the property that must hold before the pattern is correct. The property matters most: a clue suggests a pattern, and the property decides it.

The statement shows Try first, and what to check before you commit
Sorted input, or “the smallest value such that” Binary search, on the array or on the answer. Check that the yes-or-no test is monotonic: A yes-or-no condition is monotonic along a sequence when it changes at most once, from no to yes, so binary search can find where it flips. More in “From brute force to optimal: the usual moves”: once it is true, it stays true for every larger value.
A contiguous run whose validity only breaks as it grows A sliding window. Check that shrinking a valid run keeps it valid, which usually means no negative values.
Totals or counts over contiguous runs, with negative values Prefix sums with a hash map. Check that the question becomes “two prefixes that differ by k”.
Pairs or triples in sorted data Two pointers. Check that each move rules a value out for good.
“Seen before?”, grouping or counting A hash map or a set. Check that equal items can be given equal keys, such as sorted letters or a tuple.
“List every combination or arrangement” Backtracking. Check that the output, or the search after pruning, is small enough to list.
“Count the ways” or “the best total”, with choices that repeat subproblems Dynamic programming. Check that you can state the subproblem in words, and that greedy has a counterexample.
A choice that never needs undoing Greedy. Check that an exchange argument: A proof that a greedy choice is safe: take any best solution, swap its first choice for the one the greedy rule makes, and show that the result is no worse, so some best solution starts with the greedy choice. holds, or at least that a brute force finds no counterexample.
Fewest steps when every step costs the same Breadth-first search. Check that edges are unweighted; weights of 0 and 1 need a 0-1 BFS.
Cheapest path with non-negative weights Dijkstra’s algorithm. Check that no weight is negative; otherwise use Bellman–Ford.
“Must come before”, “depends on” Topological sort. Check that the graph has no cycle, which the sort itself detects.
“Same group?” while connections are added Union-find. Check that connections are only added, never removed.
“The k largest”, “the k closest”, a repeated minimum A heap. Check that k is much smaller than n; otherwise sort.
“Next greater”, “previous smaller” A monotonic stack. Check that each item waits for the first item that beats it.
Overlapping time slots or ranges Sort by start or end, then sweep. Check that the ends are agreed: half-open or closed.
Many lookups by prefix A trie. Check that many words share prefixes.

Key idea

The clue in the first column only suggests a pattern. The property in the second column decides whether it is correct, so check the property before you commit.

Classify three sketches with the table, and check the property of each row you pick:

Checkpoint

Check: A clue suggests, a property decides

  1. Question 1 of 3 A log has 10⁶ lines, each with a user ID. Return the 10 users with the most lines.

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: Count with a hash map, then keep a heap of size 10

    Counting is a hash map's job, O(n). Then a min-heap of size 10 keeps the ten largest counts in O(u log 10) for u users, or you can sort the u counts when u is small. See the hashing overview and the heaps lesson.

  2. Question 2 of 3 A step log marks each day as active or rest. Find the longest run of consecutive days that contains at most two rest days.

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: A variable sliding window

    The run is contiguous, and a run with at most two rest days stays valid when you shorten it, so the validity is monotone: grow on the right, shrink on the left while the run holds three rest days. One pass, O(n). See the sliding-window lesson.

  3. Question 3 of 3 Cables are added one at a time between 10⁵ computers. After each cable, report whether every computer can now reach every other.

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: Union-find, counting the groups as cables join them

    Connections only ever get added, and the question is "same group?", which is what union-find answers in nearly constant time per cable. Keep a count of groups, lowered by one whenever a cable joins two different groups; the answer turns yes when it reaches 1. A search after every cable costs O(n) each time, 10¹⁰ steps in all. See the union-find lesson.

Cost the shortlist, then test the survivor on small cases

A flow chart: read the statement three ways, shortlist patterns, test each against the limits and a small case, then commit.Read three things:input shape,question words,limitsShortlist one tothree patternsfrom the tableFits thetime budget?Check it on asmall case or abrute forceSameanswer?Say the patternand its cost,then code ityesno: drop ityesno: next one

How a shortlist of patterns becomes one choice

Text description of the diagram

The flow chart runs from top to bottom in one column.

  1. Read three things in the statement: the shape of the input, the words of the question, and the limits.
  2. Shortlist one to three patterns from the decision table.
  3. Ask whether a candidate fits the time budget that the limits allow. If not, drop it and go back to the shortlist.
  4. If it fits, check it on a small case, by hand or against a brute force.
  5. Ask whether the answers are the same. If not, go back to the shortlist and take the next candidate.
  6. If they are, say the pattern and its cost aloud, then write the code.

The table gives a shortlist of one to three patterns; the flow above turns it into one choice. First compare each candidate’s cost with the operation budget: How many simple steps a solution may take: the time limit in seconds times the steps the language does in a second, about 10⁸ for compiled code and 10⁷ for CPython as planning figures. More in “Read constraints to pick the target complexity” that the limits allow. A pattern that is too slow is dropped, or kept only if you can name the property that would make a faster version correct. Then check the survivor on a small case. For a greedy rule or a sliding window, a brute force over every small input is the fastest way to find a counterexample, and the run later in this lesson finds one in a fraction of a second. Only then say the choice aloud, with its cost, and start writing.

Follow problem 2 of this lesson, talks that pay a fee, through the same flow, one decision at a time:

Interactive · stage by stage Problem 2 through the flow, from shortlist to code Step through one problem. The arrows back on the right are the two ways a candidate leaves the shortlist.
Problem 2 through the flow, from shortlist to code, step 8 of 8. Showing Shortlist from the table (next: the dynamic program), Fits the time budget? (DP: O(n log n), fits), Check on small cases, Same answer? (yes: every small case), Say it, then code it (DP by end, O(n log n)). In focus: Say it, then code it.no: drop itno: next oneShortlist from the tablenext: the dynamic programFits the time budget?DP: O(n log n), fitsCheck on small casesagainst a brute forceSame answer?yes: every small caseSay it, then code itDP by end, O(n log n)same answer

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. The problem. Problem 2 of this lesson: up to 10⁵ talks, each with a start, an end and a fee; staff one talk at a time and earn as much as possible. Slots that must not overlap put two candidates on the shortlist: a greedy rule and a dynamic program.
  2. The greedy rule's cost. Try the greedy rule first: sort by end and keep each talk that fits. One sort and one pass cost O(n log n), about 1.7 × 10⁶ steps at n = 10⁵, far inside the budget.
  3. The check. It fits, so check it before writing it out: compare it with a brute force that tries every set of talks, on every small input, shortest first.
  4. A counterexample. The two disagree on two talks: (0, 1) paying 1 and (0, 2) paying 2. The rule takes the first because it ends sooner and earns 1, where 2 was possible.
  5. Back to the shortlist. A wrong answer sends the candidate back. Drop the greedy rule and take the next one on the shortlist, the dynamic program over the talks sorted by end.
  6. The DP's cost. The dynamic program sorts once and makes one binary search per talk, O(n log n) again, so it fits the same budget.
  7. Checked. Against the same brute force it agrees on every small input, and on 2,000 random sets of up to nine talks as well.
  8. Say it. Only now say the choice aloud, with its cost: a dynamic program over the talks sorted by end, with a binary search for the talks that end in time, O(n log n). Then write it.

The greedy rule fits the budget but fails the check on two talks and goes back. The dynamic program fits the same budget and agrees on every small input, so it is the one said aloud.

In a 45-minute round this takes about two minutes, and it is time well spent: an interviewer can redirect a plan that you state, but not one that you keep to yourself while typing.

Checkpoint

Check: Costing and checking the shortlist

  1. Question 1 of 2 Is a string of up to 10⁶ characters from ()[]{} balanced?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A stack of the brackets still open

    Counting fails on "([)]", whose counts match, which a check on small cases shows at once. The most recent unmatched opener must close first, which is a stack: push openers, and on a closer pop and check the kind. O(n). See the stacks overview.

  2. Question 2 of 2 A greedy rule agrees with your brute force on 2,000 random inputs. What does that tell you before you commit?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Little. Check every small input, shortest first, because a rule can be right on most random inputs and still be wrong

    Random inputs rarely hit the smallest counterexample. The search over every small case, shortest first, found the two-talk and three-talk failures at once, while the highest-fee rule was right on 93 % of the random sets.

The limits cross patterns out before you start

The limits rarely tell you which pattern to use, but they often tell you which ones you cannot use. Read the largest size first and cross out what it forbids:

  • n up to about 10: trying every order is affordable, since 10! is about 3.6 × 10⁶, so a plain permutation search can be the whole answer.
  • n up to about 20: every subset, about 10⁶ of them, can be visited, so bitmask DP and backtracking stay on the list.
  • n in the hundreds: three nested loops fit, which keeps interval DP and all-pairs shortest paths possible.
  • n in the thousands: quadratic work fits, which allows a table over two prefixes.
  • n around 10⁵ to 10⁶: only O(n log n) or O(n) remain: sorting, heaps, binary search, one pass with a hash map, windows, stacks and two pointers.

The figure turns the list into times. It starts at n = 200,000 and 10⁸ simple operations a second; move n down to 2,000, then to 20, and watch which growth rates still finish within a second:

Interactive · change it and see Which growth rates fit a second at the sizes of the list Pick an input size and how many simple operations the machine does a second. Each bar is the time for that many operations, on a log scale.
Running time by growth rate: growth rate against seconds (log scale).10^-910^-710^-510^-310^-1101,000100 thousand10 million1 billion100 billion10 trillion1,000 trillion100,000 trillionseconds (log scale)growth rateO(1)10 nsO(log n)176 nsO(n)2 msO(n log n)35 msO(n²)6.7 minutesO(n³)3 yearsO(2ⁿ)forever1 second

For n = 200 thousand at 100 million operations a second: O(n log n) takes 35 ms, O(n²) 6.7 minutes and O(2ⁿ) forever. Within a second: O(1), O(log n), O(n), O(n log n).

Finishes within a second O(n log n) and faster
O(n²) takes 6.7 minutes
O(n log n) takes 35 ms
The numbers as a table
Time for n = 200 thousand
Growth rateOperationsTime
O(1)110 ns
O(log n)17.6176 ns
O(n)200 thousand2 ms
O(n log n)3.5 million35 ms
O(n²)40 billion6.7 minutes
O(n³)8,000 trillion3 years
O(2ⁿ)too many to countforever

At n = 200,000, O(n log n) takes 35 ms and O(n²) 6.7 minutes. At n = 20, even O(2ⁿ) takes only 10 ms, which is why small limits keep subsets on the list.

The other limits cross out more. Values up to 10⁹ rule out an array indexed by value, so use a hash map or sort and compress the values. Negative values rule out a sliding window over sums and Dijkstra’s algorithm on weights. Many queries on a fixed input rule out answering each query from scratch, so prepare once. A small second parameter, such as k ≤ 20 colours, suggests subsets over k even when n is large.

Checkpoint

Check: Patterns the limits cross out

  1. Question 1 of 3 A dictionary of 10⁵ words, then 10⁵ typed prefixes: for each prefix, how many dictionary words start with it?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: A trie whose nodes count the words below them

    A trie stores shared prefixes once, and a counter at each node answers a prefix in O(length of the prefix). Sorting the words and binary searching for the range of words with the prefix also works in O(L log n) per query. Scanning costs 10¹⁰ steps. See the trie lesson.

  2. Question 2 of 3 Two lists of prices, each sorted and 10⁵ long. Count the pairs, one price from each list, whose sum is at most a budget.

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: Two pointers, one at the start of one list and one at the end of the other

    With i at the cheapest price of the first list and j at the dearest of the second, if a[i] + b[j] fits, then every price b[0..j] fits with a[i]: add j + 1 and move i. Otherwise move j down. Each pointer moves at most n times, O(n), against 10¹⁰ pairs. See the two-pointers lesson.

  3. Question 3 of 3 n = 2,000, and the machine does about 10⁸ simple operations a second. Roughly how many milliseconds does a loop of n² steps take?

    Type a number.

    A hint

    Multiply n by itself, then divide by the operations a second.

    Show the answer: Question 3 of 3

    Answer: 40 ms (anything from 38 to 42 counts)

    n² = 4 × 10⁶ steps, and 4 × 10⁶ ÷ 10⁸ a second = 0.04 s = 40 ms, well inside a second. That is the lesson's "n in the thousands: quadratic work fits". Set the figure to n = 2,000 to see the same bar.

One word can move a problem to another pattern

Each sketch below is an original problem in one or two sentences, followed by the clues, the pattern and why the look-alike pattern fails.

  1. Most overlapping bookings. Given n room bookings as time slots, report the largest number in progress at once. Clues: intervals, “at once”. Pattern: sort the start and end events and sweep, counting. A sliding window does not apply because the slots are not one contiguous run of an array.
  2. The longest playlist for a commute. Song lengths are positive; find the longest run of consecutive songs that fits in 60 minutes. Clues: contiguous, a total that only grows as the run grows. Pattern: a sliding window. Prefix sums with binary search also work, but cost a log factor for nothing.
  3. Balanced trading days. Daily profit can be negative; count the stretches of days with a total of exactly zero. Clues: contiguous, negative values, “count”. Pattern: prefix sums with a hash map of how often each running total has occurred. The window fails, because with negative days neither growing nor shrinking a stretch moves its total in one direction.
  4. The quickest metro route. Stations and the travel time between neighbours; the quickest route from A to B. Clues: a graph with non-negative weights, “quickest”. Pattern: Dijkstra’s algorithm. Breadth-first search finds the fewest stops, which is a different question.
  5. A study order. Courses with prerequisites; an order that takes every course after its prerequisites, or “no order”. Clues: “after”, dependencies. Pattern: topological sort. Sorting by the number of prerequisites fails as soon as a chain is longer than two.
  6. Friend groups as requests arrive. After each accepted friend request, are users x and y in one group? Clues: connectivity, edges only added, many queries. Pattern: union-find. A fresh search for every query is too slow.
  7. The smallest truck. Parcels must leave in order within d days; find the smallest daily capacity that ships them all. Clues: “the smallest value such that”, and a capacity that works keeps working when it grows. Pattern: binary search on the capacity with a greedy check. Trying every capacity in turn costs one check per possible capacity.
  8. Seating rivals. Seat nine guests in a row so that no two rivals sit side by side, and list every seating. Clues: “list every”, n = 9. Pattern: backtracking with pruning, because 9! is only 362,880 orders to begin with and pruning cuts most of them.
  9. The ten busiest pages. A day of 10⁷ page views; the ten most viewed pages. Clues: counting, “top ten”. Pattern: a hash map of counts, then a heap of size ten. Sorting every view is wasteful when only the ten largest counts matter.
  10. Nearest taller tower. For each tower in a row, the distance to the nearest taller tower on its right. Clues: “nearest greater”. Pattern: a monotonic stack, O(n). Two nested loops cost O(n²).
  11. Change with odd coins. Coins of 1, 4 and 6 units; the fewest coins for an amount. Clues: “fewest”, choices that overlap. Pattern: dynamic programming over the amounts. The largest coin first pays 8 as 6 + 1 + 1, three coins, where 4 + 4 needs two.
  12. The longest rising trend. Daily prices; the longest sequence of days, not necessarily consecutive, on which the price keeps rising. Clues: “not necessarily consecutive” makes it a subsequence: Items taken from a sequence in their original order but not necessarily side by side: 1, 3, 4 is a subsequence of 1, 2, 3, 4. A substring or a subarray must be contiguous.. Pattern: dynamic programming, or patience sorting in O(n log n). A single pass that tracks the current rising run answers the contiguous version of the question, not this one.

Three of the sketches turn on a single word. “Positive” in sketch 2 keeps the window; with negative values the problem would need sketch 3’s prefix sums. “Quickest” in sketch 4 asks for Dijkstra; “fewest stops” would ask for breadth-first search. “Not necessarily consecutive” in sketch 12 asks for a subsequence; consecutive days would need one pass.

The table puts the three turns side by side:

Sketch The word With the word Without it
2, the commute playlist positive A sliding window Prefix sums, as in sketch 3
4, the metro route quickest Dijkstra’s algorithm Fewest stops: breadth-first search
12, the rising trend not necessarily consecutive DP or patience sorting One pass over the current run

Classify three more sketches by the words of their questions:

Checkpoint

Check: The words that point to a pattern

  1. Question 1 of 3 A robot moves one cell up, down, left or right on a 1,000 × 1,000 floor with shelves in the way. What is the fewest number of moves from the dock to the charger?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: Breadth-first search from the dock

    Every move costs 1, so breadth-first search reaches cells in order of distance and the first time it reaches the charger is the answer: O(cells), about 10⁶ steps. Dijkstra also works but adds a heap for nothing; a depth-first search finds a path, not the shortest. DP from a corner fails because the robot may need to move up or left. The graph-modelling lesson turns a floor into a graph.

  2. Question 2 of 3 A build has 5,000 tasks and 20,000 rules of the form "task A must finish before task B". Print an order that obeys every rule, or report that none exists.

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: Topological sort, which also detects a cycle

    "Must finish before" describes a directed graph of dependencies, and an order that respects every edge is a topological order. Kahn's method removes tasks with no unfinished prerequisites; if tasks remain, the rules contain a cycle and no order exists. O(tasks + rules). The graph-modelling lesson shows how to build the graph.

  3. Question 3 of 3 Buildings stand in a row. For each building, find how far away the nearest taller building on its right is.

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: A monotonic stack, scanning once

    "Nearest greater to the right" is the signature of a monotonic stack: keep the buildings still waiting for a taller one, in decreasing height, and when a taller building arrives it answers every shorter one it pops. Each building is pushed and popped once, O(n). See the stacks overview.

Two problems that read alike need different patterns

A technician staffs conference talks, one at a time; each talk is a time slot from its start to its end, and a talk may start when another ends. Problem 1: staff as many talks as possible. Problem 2: each talk pays a fee; earn as much as possible. Both read as “choose non-overlapping slots”, and a well-known greedy rule, taking the talk that ends first among those that fit, solves the first. The program below tests that rule, a second greedy rule and a dynamic program against a brute force that tries every set of talks. Each talk is written as (start, end, fee).

Greedy and DP against a brute force, on two problems Python · look_alike/look_alike.py
"""Two problems that read alike: a technician staffs one talk at a time, each talk a half-open slot [start, end).

Problem 1 asks for the most talks staffed; problem 2 pays a fee per talk and asks for the most money. One greedy
rule solves the first. The second needs dynamic programming, and a brute force over every set of talks shows why:
first on every small case, shortest first, then on random ones.
"""
import random
from bisect import bisect_right
from itertools import combinations, product


def fits(chosen):
    """No two chosen talks overlap (a talk may start when another ends)."""
    ordered = sorted(chosen, key=lambda t: t[0])
    return all(a[1] <= b[0] for a, b in zip(ordered, ordered[1:]))


def brute_force(talks, value):
    """The best total of value(talk) over every set of talks that fit: 2^n sets."""
    best = 0
    for r in range(1, len(talks) + 1):
        for chosen in combinations(talks, r):
            if fits(chosen):
                best = max(best, sum(value(t) for t in chosen))
    return best


def greedy(talks, value, key):
    """Takes talks in the order of `key`, keeping each one that fits with those kept."""
    kept = []
    for t in sorted(talks, key=key):
        if fits(kept + [t]):
            kept.append(t)
    return sum(value(t) for t in kept)


def dynamic_program(talks, value):
    """best[i] = the most from the first i talks by end time: skip talk i, or take it after the talks that end in time.

    O(n log n): one sort, then one binary search per talk.
    """
    by_end = sorted(talks, key=lambda t: t[1])
    ends = [t[1] for t in by_end]
    best = [0] * (len(by_end) + 1)
    for i, (start, end, fee) in enumerate(by_end, 1):
        before = bisect_right(ends, start, 0, i - 1)  # talks that end by this one's start
        best[i] = max(best[i - 1], value((start, end, fee)) + best[before])
    return best[-1]


COUNT = lambda t: 1  # problem 1: every talk counts once
FEE = lambda t: t[2]  # problem 2: a talk is worth its fee
EARLIEST_END = lambda t: (t[1], t[0])
HIGHEST_FEE = lambda t: (-t[2], t[1])

SLOTS = [(s, e) for s in range(4) for e in range(s + 1, 5)]


def small_cases(max_talks, fees):
    """Every set of up to max_talks talks with slots inside [0, 4) and the given fees, fewest talks first."""
    for n in range(1, max_talks + 1):
        for slots in combinations(SLOTS, n):
            for paid in product(fees, repeat=n):
                yield [(s, e, f) for (s, e), f in zip(slots, paid)]


def first_disagreement(method, value, fees):
    for talks in small_cases(3, fees):
        if method(talks, value) != brute_force(talks, value):
            return talks
    return None


def random_agreement(method, value, rng, trials=2000):
    right = 0
    for _ in range(trials):
        talks = []
        for _ in range(rng.randint(1, 9)):
            start = rng.randint(0, 20)
            talks.append((start, start + rng.randint(1, 6), rng.randint(1, 9)))
        right += method(talks, value) == brute_force(talks, value)
    return right


rng = random.Random(7)
by_end = lambda talks, value: greedy(talks, value, EARLIEST_END)
by_fee = lambda talks, value: greedy(talks, value, HIGHEST_FEE)

print("Problem 1: the most talks staffed")
print(f"  earliest end first: first disagreement with the brute force: {first_disagreement(by_end, COUNT, [1])}")
print(f"  earliest end first: right on {random_agreement(by_end, COUNT, rng):,} of 2,000 random sets")
print()
print("Problem 2: the most fees earned")
for name, method in (("earliest end first", by_end), ("highest fee first", by_fee)):
    talks = first_disagreement(method, FEE, [1, 2, 3])
    print(f"  {name}: first disagreement: {talks}")
    print(f"    brute force {brute_force(talks, FEE)}, {name} {method(talks, FEE)}, dynamic program {dynamic_program(talks, FEE)}")
    print(f"  {name}: right on {random_agreement(method, FEE, rng):,} of 2,000 random sets")
print(f"  dynamic program: first disagreement: {first_disagreement(dynamic_program, FEE, [1, 2, 3])}")
print(f"  dynamic program: right on {random_agreement(dynamic_program, FEE, rng):,} of 2,000 random sets")

Output

Problem 1: the most talks staffed
  earliest end first: first disagreement with the brute force: None
  earliest end first: right on 2,000 of 2,000 random sets

Problem 2: the most fees earned
  earliest end first: first disagreement: [(0, 1, 1), (0, 2, 2)]
    brute force 2, earliest end first 1, dynamic program 2
  earliest end first: right on 1,130 of 2,000 random sets
  highest fee first: first disagreement: [(0, 1, 1), (0, 2, 2), (1, 2, 2)]
    brute force 3, highest fee first 2, dynamic program 3
  highest fee first: right on 1,856 of 2,000 random sets
  dynamic program: first disagreement: None
  dynamic program: right on 2,000 of 2,000 random sets

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 look_alike.py

For problem 1, the earliest-ending rule agrees with the brute force on every set of up to three talks in a small grid of slots and on 2,000 random sets. For problem 2 it fails on two talks: (0, 1) paying 1 and (0, 2) paying 2. It takes the first because it ends sooner and earns 1, where the brute force earns 2. Taking the highest fee first fails too, on three talks. The dynamic program sorts the talks by end and, for each talk, takes the better of skipping it or taking it after the talks that end in time, which a binary search finds; it agrees with the brute force everywhere.

Notice how often the broken rules look right on random data: the highest-fee rule is right on 1,856 of 2,000 random sets, 93 %. A few random tests prove little; an exhaustive search over small cases, sorted shortest first, finds the smallest counterexample. The word that moved the problem was “fee”: once choices carry different values, a choice that looks best now can cost more later, and that is the signal for dynamic programming.

Step through the dynamic program on the three talks on which taking the highest fee first fails:

Interactive · stage by stage The dynamic program on three talks, one row at a time Step through the table. Each talk compares skipping it with taking it after the talks that end by its start.
The dynamic program on three talks, one row at a time, step 5 of 5. Showing best[0] (best[0] = 0), Talk 1: (0, 1), fee 1 (max(0, 1 + 0) = 1), Talk 2: (0, 2), fee 2 (max(1, 2 + 0) = 2), Talk 3: (1, 2), fee 2 (best[3] = 3: talks 1 and 3). In focus: Talk 3: (1, 2), fee 2.best[0]best[0] = 0Talk 1: (0, 1), fee 1max(0, 1 + 0) = 1Talk 2: (0, 2), fee 2max(1, 2 + 0) = 2Talk 3: (1, 2), fee 2best[3] = 3: talks 1 and 3

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Sorted by end. Sort the talks by end: (0, 1) paying 1, then (0, 2) and (1, 2), each paying 2. best[i] holds the most money from the first i of them, so with no talks best[0] = 0.
  2. Talk 1. Talk 1 starts at 0, and no talk before it ends by 0, so taking it earns 1 + best[0] = 1. Skipping it keeps best[0] = 0, so best[1] = 1.
  3. Talk 2. Talk 2 also starts at 0, so taking it earns 2 + best[0] = 2, while skipping it keeps best[1] = 1. best[2] = 2.
  4. Talk 3. Talk 3 starts at 1. The binary search over the ends before it, 1 and 2, finds one talk that ends by 1, talk 1, so taking it earns 2 + best[1] = 3. Skipping keeps best[2] = 2, so best[3] = 3.
  5. The answer. best[3] = 3, from talks 1 and 3, the brute force's answer in the run above. Taking the highest fee first grabs (0, 2), which overlaps both others, and earns 2.

The program below solves both problems in 14 languages, the earliest-end rule and the dynamic program, on the two-talk counterexample and on a conference day of six talks. Every language printed the same lines:

One program · 14 languages The earliest-end rule and the dynamic program on two days of talks O(n log n): a sort, then a binary search per talk

Python 3.14 · main.py

from bisect import bisect_right

Talk = tuple[int, int, int]  # (start, end, fee); a talk may start when another ends

DAYS: list[list[Talk]] = [
    [(0, 1, 1), (0, 2, 2)],
    [(9, 10, 2), (9, 12, 9), (10, 11, 3), (11, 13, 4), (12, 15, 8), (13, 14, 2)],
]


def earliest_end_first(ordered: list[Talk]) -> tuple[int, int]:
    """Problem 1, greedy: take each talk that fits after the last one taken."""
    count = fees = 0
    free_from = 0  # no talk starts before 0
    for start, end, fee in ordered:
        if start >= free_from:
            count, fees, free_from = count + 1, fees + fee, end
    return count, fees


def most_fees(ordered: list[Talk]) -> int:
    """Problem 2, DP: best[i] is the most from the first i talks by end."""
    ends = [end for _, end, _ in ordered]
    best = [0] * (len(ordered) + 1)
    for i, (start, _, fee) in enumerate(ordered, 1):
        before = bisect_right(ends, start, 0, i - 1)  # talks that end by this start
        best[i] = max(best[i - 1], fee + best[before])
    return best[-1]


for talks in DAYS:
    print(" ".join(f"({s}, {e}, {f})" for s, e, f in talks))
    ordered = sorted(talks, key=lambda t: (t[1], t[0]))
    count, fees = earliest_end_first(ordered)
    print(f"  earliest end first: staffs {count}, earns {fees}")
    print(f"  dynamic program: earns {most_fees(ordered)}")

In Python: bisect_right(ends, start, 0, i - 1) counts the talks that end by the time this one starts, the binary search the other tabs write as a loop.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

// Each talk is [start, end, fee]; a talk may start when another ends.
const DAYS = [
  [
    [0, 1, 1],
    [0, 2, 2],
  ],
  [
    [9, 10, 2],
    [9, 12, 9],
    [10, 11, 3],
    [11, 13, 4],
    [12, 15, 8],
    [13, 14, 2],
  ],
];

// Problem 1, greedy: take each talk that fits after the last one taken.
function earliestEndFirst(ordered) {
  let count = 0;
  let fees = 0;
  let freeFrom = 0; // no talk starts before 0
  for (const [start, end, fee] of ordered) {
    if (start >= freeFrom) {
      [count, fees, freeFrom] = [count + 1, fees + fee, end];
    }
  }
  return { count, fees };
}

// How many of sorted[0], ..., sorted[hi - 1] are at most x.
function countAtMost(sorted, x, hi) {
  let lo = 0;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (sorted[mid] <= x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

// Problem 2, DP: best[i] is the most from the first i talks by end.
function mostFees(ordered) {
  const ends = ordered.map((talk) => talk[1]);
  const best = [0];
  for (const [i, [start, , fee]] of ordered.entries()) {
    const before = countAtMost(ends, start, i); // talks that end by this start
    best.push(Math.max(best[i], fee + best[before]));
  }
  return best[ordered.length];
}

for (const talks of DAYS) {
  console.log(talks.map(([s, e, f]) => `(${s}, ${e}, ${f})`).join(" "));
  const ordered = [...talks].sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  const { count, fees } = earliestEndFirst(ordered);
  console.log(`  earliest end first: staffs ${count}, earns ${fees}`);
  console.log(`  dynamic program: earns ${mostFees(ordered)}`);
}

In JavaScript: The comparator chains the two keys with ||, so a difference of 0 in the end falls through to the start.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
  // A talk may start when another ends.
  record Talk(int start, int end, int fee) {}

  static final int[][][] DAYS = {
    {{0, 1, 1}, {0, 2, 2}},
    {{9, 10, 2}, {9, 12, 9}, {10, 11, 3}, {11, 13, 4}, {12, 15, 8}, {13, 14, 2}}
  };

  // Problem 1, greedy: take each talk that fits after the last one taken.
  static int[] earliestEndFirst(List<Talk> ordered) {
    int count = 0;
    int fees = 0;
    int freeFrom = 0; // no talk starts before 0
    for (Talk talk : ordered) {
      if (talk.start() >= freeFrom) {
        count++;
        fees += talk.fee();
        freeFrom = talk.end();
      }
    }
    return new int[] {count, fees};
  }

  // How many of the first hi talks end by x.
  static int countAtMost(List<Talk> ordered, int x, int hi) {
    int lo = 0;
    while (lo < hi) {
      int mid = (lo + hi) >>> 1;
      if (ordered.get(mid).end() <= x) {
        lo = mid + 1;
      } else {
        hi = mid;
      }
    }
    return lo;
  }

  // Problem 2, DP: best[i] is the most from the first i talks by end.
  static int mostFees(List<Talk> ordered) {
    int[] best = new int[ordered.size() + 1];
    for (int i = 1; i <= ordered.size(); i++) {
      Talk talk = ordered.get(i - 1);
      int before = countAtMost(ordered, talk.start(), i - 1); // talks that end by this start
      best[i] = Math.max(best[i - 1], talk.fee() + best[before]);
    }
    return best[ordered.size()];
  }

  public static void main(String[] args) {
    for (int[][] day : DAYS) {
      List<Talk> ordered = new ArrayList<>();
      StringBuilder shown = new StringBuilder();
      for (int[] t : day) {
        ordered.add(new Talk(t[0], t[1], t[2]));
        shown
            .append(shown.length() == 0 ? "" : " ")
            .append("(" + t[0] + ", " + t[1] + ", " + t[2] + ")");
      }
      System.out.println(shown);
      ordered.sort(Comparator.comparingInt(Talk::end).thenComparingInt(Talk::start));
      int[] staffed = earliestEndFirst(ordered);
      System.out.println("  earliest end first: staffs " + staffed[0] + ", earns " + staffed[1]);
      System.out.println("  dynamic program: earns " + mostFees(ordered));
    }
  }
}

In Java: Each talk is a record, and Comparator.comparingInt(Talk::end).thenComparingInt(Talk::start) sorts by end, then start.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <algorithm>
#include <format>
#include <print>
#include <string>
#include <utility>
#include <vector>

// A talk may start when another ends.
struct Talk {
  int start;
  int end;
  int fee;
};

const std::vector<std::vector<Talk>> days = {
    {{0, 1, 1}, {0, 2, 2}},
    {{9, 10, 2},
     {9, 12, 9},
     {10, 11, 3},
     {11, 13, 4},
     {12, 15, 8},
     {13, 14, 2}},
};

// Problem 1's greedy rule: keep each talk that starts once the last kept one
// ends.
std::pair<int, int> earliest_end_first(const std::vector<Talk> &ordered) {
  int count = 0;
  int fees = 0;
  int free_from = 0; // no talk starts before 0
  for (const Talk &t : ordered) {
    if (t.start >= free_from) {
      ++count;
      fees += t.fee;
      free_from = t.end;
    }
  }
  return {count, fees};
}

// Problem 2's dynamic program: best[i] is the most from the first i talks by
// end.
int most_fees(const std::vector<Talk> &ordered) {
  std::vector<int> best{0};
  for (std::size_t i = 0; i < ordered.size(); ++i) {
    // talks that end by this start
    const auto before =
        std::ranges::upper_bound(ordered.begin(), ordered.begin() + i,
                                 ordered[i].start, {}, &Talk::end) -
        ordered.begin();
    best.push_back(std::max(best[i], ordered[i].fee + best[before]));
  }
  return best.back();
}

int main() {
  for (std::vector<Talk> talks : days) {
    std::string shown;
    for (const Talk &t : talks) {
      shown += std::format("{}({}, {}, {})", shown.empty() ? "" : " ", t.start,
                           t.end, t.fee);
    }
    std::println("{}", shown);
    std::ranges::sort(talks, {},
                      [](const Talk &t) { return std::pair(t.end, t.start); });
    const auto [count, fees] = earliest_end_first(talks);
    std::println("  earliest end first: staffs {}, earns {}", count, fees);
    std::println("  dynamic program: earns {}", most_fees(talks));
  }
}

In C++: std::ranges::upper_bound with the projection &Talk::end counts the first i talks that end by this start; std::ranges::sort with a projection to a pair sorts by end, then start.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

Talk[][] days =
[
    [new(0, 1, 1), new(0, 2, 2)],
    [new(9, 10, 2), new(9, 12, 9), new(10, 11, 3), new(11, 13, 4), new(12, 15, 8), new(13, 14, 2)],
];

foreach (var talks in days)
{
    Console.WriteLine(string.Join(" ", talks.Select(t => $"({t.Start}, {t.End}, {t.Fee})")));
    Talk[] ordered = [.. talks.OrderBy(t => t.End).ThenBy(t => t.Start)];
    var (count, fees) = EarliestEndFirst(ordered);
    Console.WriteLine($"  earliest end first: staffs {count}, earns {fees}");
    Console.WriteLine($"  dynamic program: earns {MostFees(ordered)}");
}

// Problem 1, greedy: take each talk that fits after the last one taken.
static (int Count, int Fees) EarliestEndFirst(Talk[] ordered)
{
    int count = 0;
    int fees = 0;
    int freeFrom = 0; // no talk starts before 0
    foreach (var (start, end, fee) in ordered)
    {
        if (start >= freeFrom)
        {
            (count, fees, freeFrom) = (count + 1, fees + fee, end);
        }
    }
    return (count, fees);
}

// How many of the first hi talks end by x.
static int CountAtMost(Talk[] ordered, int x, int hi)
{
    int lo = 0;
    while (lo < hi)
    {
        int mid = (lo + hi) / 2;
        if (ordered[mid].End <= x)
        {
            lo = mid + 1;
        }
        else
        {
            hi = mid;
        }
    }
    return lo;
}

// Problem 2, DP: best[i] is the most from the first i talks by end.
static int MostFees(Talk[] ordered)
{
    var best = new int[ordered.Length + 1];
    for (int i = 1; i <= ordered.Length; i++)
    {
        var (start, _, fee) = ordered[i - 1];
        int before = CountAtMost(ordered, start, i - 1); // talks that end by this start
        best[i] = Math.Max(best[i - 1], fee + best[before]);
    }
    return best[ordered.Length];
}

// A talk may start when another ends.
record struct Talk(int Start, int End, int Fee);

In C#: Each talk is a positional record struct, which deconstructs in foreach; LINQ's OrderBy and ThenBy sort by end, then start.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

// A talk may start when another ends.
typedef struct {
  int start;
  int end;
  int fee;
} Talk;

enum { MAX_TALKS = 8 };

static Talk day1[] = {{0, 1, 1}, {0, 2, 2}};
static Talk day2[] = {{9, 10, 2},  {9, 12, 9},  {10, 11, 3},
                      {11, 13, 4}, {12, 15, 8}, {13, 14, 2}};

static int by_end(const void *a, const void *b) {
  const Talk *x = a;
  const Talk *y = b;
  if (x->end != y->end) {
    return (x->end > y->end) - (x->end < y->end);
  }
  return (x->start > y->start) - (x->start < y->start);
}

// Problem 1, greedy: take each talk that fits after the last one taken.
static void earliest_end_first(const Talk *ordered, size_t n, int *count,
                               int *fees) {
  int free_from = 0; // no talk starts before 0
  *count = *fees = 0;
  for (size_t i = 0; i < n; i++) {
    if (ordered[i].start >= free_from) {
      ++*count;
      *fees += ordered[i].fee;
      free_from = ordered[i].end;
    }
  }
}

// Problem 2, DP: best[i] is the most from the first i talks by end.
static int most_fees(const Talk *ordered, size_t n) {
  int best[MAX_TALKS + 1] = {0};
  for (size_t i = 1; i <= n; i++) {
    size_t lo = 0; // talks that end by this start
    size_t hi = i - 1;
    while (lo < hi) {
      const size_t mid = lo + (hi - lo) / 2;
      if (ordered[mid].end <= ordered[i - 1].start) {
        lo = mid + 1;
      } else {
        hi = mid;
      }
    }
    const int take = ordered[i - 1].fee + best[lo];
    best[i] = take > best[i - 1] ? take : best[i - 1];
  }
  return best[n];
}

int main(void) {
  Talk *days[] = {day1, day2};
  const size_t sizes[] = {2, 6};
  for (size_t d = 0; d < 2; d++) {
    for (size_t i = 0; i < sizes[d]; i++) {
      const Talk *t = &days[d][i];
      printf("%s(%d, %d, %d)", i ? " " : "", t->start, t->end, t->fee);
    }
    printf("\n");
    qsort(days[d], sizes[d], sizeof(Talk), by_end);
    int count = 0;
    int fees = 0;
    earliest_end_first(days[d], sizes[d], &count, &fees);
    printf("  earliest end first: staffs %d, earns %d\n", count, fees);
    printf("  dynamic program: earns %d\n", most_fees(days[d], sizes[d]));
  }
  return 0;
}

In C: main sorts each day in place with qsort, whose comparator returns a negative, zero or positive int, and best is a fixed array sized for the longest day.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

// Each talk is [start, end, fee]; a talk may start when another ends.
const DAYS = [
    [[0, 1, 1], [0, 2, 2]],
    [[9, 10, 2], [9, 12, 9], [10, 11, 3], [11, 13, 4], [12, 15, 8], [13, 14, 2]],
];

/**
 * Problem 1, greedy: take each talk that fits after the last one taken.
 *
 * @param list<array{int, int, int}> $ordered
 * @return array{int, int}
 */
function earliestEndFirst(array $ordered): array
{
    $count = $fees = 0;
    $freeFrom = 0; // no talk starts before 0
    foreach ($ordered as [$start, $end, $fee]) {
        if ($start >= $freeFrom) {
            [$count, $fees, $freeFrom] = [$count + 1, $fees + $fee, $end];
        }
    }
    return [$count, $fees];
}

/**
 * Problem 2, DP: best[i] is the most from the first i talks by end.
 *
 * @param list<array{int, int, int}> $ordered
 */
function mostFees(array $ordered): int
{
    $best = [0];
    foreach ($ordered as $i => [$start, , $fee]) {
        [$lo, $hi] = [0, $i]; // talks that end by this start
        while ($lo < $hi) {
            $mid = intdiv($lo + $hi, 2);
            if ($ordered[$mid][1] <= $start) {
                $lo = $mid + 1;
            } else {
                $hi = $mid;
            }
        }
        $best[] = max($best[$i], $fee + $best[$lo]);
    }
    return $best[count($ordered)];
}

foreach (DAYS as $talks) {
    $shown = array_map(fn(array $t): string => "({$t[0]}, {$t[1]}, {$t[2]})", $talks);
    echo implode(' ', $shown), "\n";
    usort($talks, fn(array $a, array $b): int => [$a[1], $a[0]] <=> [$b[1], $b[0]]);
    [$count, $fees] = earliestEndFirst($talks);
    echo "  earliest end first: staffs {$count}, earns {$fees}\n";
    echo '  dynamic program: earns ', mostFees($talks), "\n";
}

In PHP: usort compares two arrays with <=>, element by element, so [end, start] sorts by both keys in one expression.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

/// A talk may start when another ends.
struct Talk {
    start: u32,
    end: u32,
    fee: u32,
}

const fn talk(start: u32, end: u32, fee: u32) -> Talk {
    Talk { start, end, fee }
}

/// Problem 1, greedy: take each talk that fits after the last one taken.
fn earliest_end_first(ordered: &[Talk]) -> (u32, u32) {
    let (mut count, mut fees) = (0, 0);
    let mut free_from = 0; // no talk starts before 0
    for t in ordered {
        if t.start >= free_from {
            (count, fees, free_from) = (count + 1, fees + t.fee, t.end);
        }
    }
    (count, fees)
}

/// Problem 2, DP: best[i] is the most from the first i talks by end.
fn most_fees(ordered: &[Talk]) -> u32 {
    let mut best = vec![0];
    for (i, t) in ordered.iter().enumerate() {
        // talks that end by this start
        let before = ordered[..i].partition_point(|e| e.end <= t.start);
        best.push(best[i].max(t.fee + best[before]));
    }
    best[ordered.len()]
}

fn main() {
    let days = [
        vec![talk(0, 1, 1), talk(0, 2, 2)],
        vec![
            talk(9, 10, 2),
            talk(9, 12, 9),
            talk(10, 11, 3),
            talk(11, 13, 4),
            talk(12, 15, 8),
            talk(13, 14, 2),
        ],
    ];
    for mut talks in days {
        let shown: Vec<String> = talks
            .iter()
            .map(|t| format!("({}, {}, {})", t.start, t.end, t.fee))
            .collect();
        println!("{}", shown.join(" "));
        talks.sort_by_key(|t| (t.end, t.start));
        let (count, fees) = earliest_end_first(&talks);
        println!("  earliest end first: staffs {count}, earns {fees}");
        println!("  dynamic program: earns {}", most_fees(&talks));
    }
}

In Rust: partition_point counts the leading talks whose end is at most this start, the upper bound the other tabs write as a loop; sort_by_key on a tuple sorts by end, then start.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

// A talk may start when another ends.
type Talk = [start: number, end: number, fee: number];

const DAYS: Talk[][] = [
  [
    [0, 1, 1],
    [0, 2, 2],
  ],
  [
    [9, 10, 2],
    [9, 12, 9],
    [10, 11, 3],
    [11, 13, 4],
    [12, 15, 8],
    [13, 14, 2],
  ],
];

// Problem 1, greedy: take each talk that fits after the last one taken.
function earliestEndFirst(ordered: Talk[]): { count: number; fees: number } {
  let count = 0;
  let fees = 0;
  let freeFrom = 0; // no talk starts before 0
  for (const [start, end, fee] of ordered) {
    if (start >= freeFrom) {
      [count, fees, freeFrom] = [count + 1, fees + fee, end];
    }
  }
  return { count, fees };
}

// How many of sorted[0], ..., sorted[hi - 1] are at most x.
function countAtMost(sorted: number[], x: number, hi: number): number {
  let lo = 0;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (sorted[mid] <= x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

// Problem 2, DP: best[i] is the most from the first i talks by end.
function mostFees(ordered: Talk[]): number {
  const ends = ordered.map((talk) => talk[1]);
  const best = [0];
  for (const [i, [start, , fee]] of ordered.entries()) {
    const before = countAtMost(ends, start, i); // talks that end by this start
    best.push(Math.max(best[i], fee + best[before]));
  }
  return best[ordered.length];
}

for (const talks of DAYS) {
  console.log(talks.map(([s, e, f]) => `(${s}, ${e}, ${f})`).join(" "));
  const ordered = [...talks].sort((a, b) => a[1] - b[1] || a[0] - b[0]);
  const { count, fees } = earliestEndFirst(ordered);
  console.log(`  earliest end first: staffs ${count}, earns ${fees}`);
  console.log(`  dynamic program: earns ${mostFees(ordered)}`);
}

In TypeScript: A labelled tuple type names the three fields while each talk stays a plain array, so the program is the JavaScript one with types.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import (
	"cmp"
	"fmt"
	"slices"
	"sort"
	"strings"
)

// Talk is one talk; a talk may start when another ends.
type Talk struct{ start, end, fee int }

var days = [][]Talk{
	{{0, 1, 1}, {0, 2, 2}},
	{{9, 10, 2}, {9, 12, 9}, {10, 11, 3}, {11, 13, 4}, {12, 15, 8}, {13, 14, 2}},
}

// earliestEndFirst is problem 1, greedy: take each talk that fits after the last one taken.
func earliestEndFirst(ordered []Talk) (count, fees int) {
	freeFrom := 0 // no talk starts before 0
	for _, t := range ordered {
		if t.start >= freeFrom {
			count, fees, freeFrom = count+1, fees+t.fee, t.end
		}
	}
	return count, fees
}

// mostFees is problem 2, DP: best[i] is the most from the first i talks by end.
func mostFees(ordered []Talk) int {
	best := []int{0}
	for i, t := range ordered {
		// talks that end by this start
		before := sort.Search(i, func(k int) bool { return ordered[k].end > t.start })
		best = append(best, max(best[i], t.fee+best[before]))
	}
	return best[len(ordered)]
}

func main() {
	for _, talks := range days {
		shown := make([]string, len(talks))
		for i, t := range talks {
			shown[i] = fmt.Sprintf("(%d, %d, %d)", t.start, t.end, t.fee)
		}
		fmt.Println(strings.Join(shown, " "))
		ordered := slices.Clone(talks)
		slices.SortFunc(ordered, func(a, b Talk) int {
			return cmp.Or(cmp.Compare(a.end, b.end), cmp.Compare(a.start, b.start))
		})
		count, fees := earliestEndFirst(ordered)
		fmt.Printf("  earliest end first: staffs %d, earns %d\n", count, fees)
		fmt.Printf("  dynamic program: earns %d\n", mostFees(ordered))
	}
}

In Go: sort.Search returns the first talk whose end comes after this start, and cmp.Or with cmp.Compare chains the two sort keys.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

/// A talk may start when another ends.
struct Talk {
  let start: Int
  let end: Int
  let fee: Int
}

let days: [[(Int, Int, Int)]] = [
  [(0, 1, 1), (0, 2, 2)],
  [(9, 10, 2), (9, 12, 9), (10, 11, 3), (11, 13, 4), (12, 15, 8), (13, 14, 2)],
]

/// Problem 1, greedy: take each talk that fits after the last one taken.
func earliestEndFirst(_ ordered: [Talk]) -> (count: Int, fees: Int) {
  var count = 0
  var fees = 0
  var freeFrom = 0  // no talk starts before 0
  for talk in ordered where talk.start >= freeFrom {
    (count, fees, freeFrom) = (count + 1, fees + talk.fee, talk.end)
  }
  return (count, fees)
}

/// Problem 2, DP: best[i] is the most from the first i talks by end.
func mostFees(_ ordered: [Talk]) -> Int {
  var best = [0]
  for (i, talk) in ordered.enumerated() {
    var lo = 0  // talks that end by this start
    var hi = i
    while lo < hi {
      let mid = (lo + hi) / 2
      if ordered[mid].end <= talk.start { lo = mid + 1 } else { hi = mid }
    }
    best.append(max(best[i], talk.fee + best[lo]))
  }
  return best[ordered.count]
}

for day in days {
  let talks = day.map { Talk(start: $0.0, end: $0.1, fee: $0.2) }
  print(talks.map { "(\($0.start), \($0.end), \($0.fee))" }.joined(separator: " "))
  let ordered = talks.sorted { ($0.end, $0.start) < ($1.end, $1.start) }
  let staffed = earliestEndFirst(ordered)
  print("  earliest end first: staffs \(staffed.count), earns \(staffed.fees)")
  print("  dynamic program: earns \(mostFees(ordered))")
}

In Swift: Tuples of comparable values compare element by element with <, so one closure sorts by end, then start.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

# Each talk is [start, end, fee]; a talk may start when another ends.
DAYS = [
  [[0, 1, 1], [0, 2, 2]],
  [[9, 10, 2], [9, 12, 9], [10, 11, 3], [11, 13, 4], [12, 15, 8], [13, 14, 2]]
].freeze

# Problem 1, greedy: take each talk that fits after the last one taken.
def earliest_end_first(ordered)
  count = fees = 0
  free_from = 0 # no talk starts before 0
  ordered.each do |start, finish, fee|
    next if start < free_from

    count += 1
    fees += fee
    free_from = finish
  end
  [count, fees]
end

# Problem 2, DP: best[i] is the most from the first i talks by end.
def most_fees(ordered)
  best = [0]
  ordered.each_with_index do |(start, _finish, fee), i|
    # talks that end by this start
    before = (0...i).bsearch { |k| ordered[k][1] > start } || i
    best << [best[i], fee + best[before]].max
  end
  best.last
end

DAYS.each do |talks|
  puts(talks.map { |start, finish, fee| "(#{start}, #{finish}, #{fee})" }.join(' '))
  ordered = talks.sort_by { |start, finish, _fee| [finish, start] }
  count, fees = earliest_end_first(ordered)
  puts "  earliest end first: staffs #{count}, earns #{fees}"
  puts "  dynamic program: earns #{most_fees(ordered)}"
end

In Ruby: Range#bsearch in find-minimum mode returns the first index whose end comes after this start, or nil when there is none, and best grows by one entry per talk.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

// A talk may start when another ends.
data class Talk(
    val start: Int,
    val end: Int,
    val fee: Int,
)

val days =
    listOf(
        listOf(Talk(0, 1, 1), Talk(0, 2, 2)),
        listOf(
            Talk(9, 10, 2),
            Talk(9, 12, 9),
            Talk(10, 11, 3),
            Talk(11, 13, 4),
            Talk(12, 15, 8),
            Talk(13, 14, 2),
        ),
    )

// Problem 1, greedy: take each talk that fits after the last one taken.
fun earliestEndFirst(ordered: List<Talk>): Pair<Int, Int> {
    var count = 0
    var fees = 0
    var freeFrom = 0 // no talk starts before 0
    for (talk in ordered) {
        if (talk.start >= freeFrom) {
            count++
            fees += talk.fee
            freeFrom = talk.end
        }
    }
    return count to fees
}

// Problem 2, DP: best[i] is the most from the first i talks by end.
fun mostFees(ordered: List<Talk>): Int {
    val best = mutableListOf(0)
    for ((i, talk) in ordered.withIndex()) {
        var lo = 0 // talks that end by this start
        var hi = i
        while (lo < hi) {
            val mid = (lo + hi) / 2
            if (ordered[mid].end <= talk.start) lo = mid + 1 else hi = mid
        }
        best.add(maxOf(best[i], talk.fee + best[lo]))
    }
    return best.last()
}

fun main() {
    for (talks in days) {
        println(talks.joinToString(" ") { "(${it.start}, ${it.end}, ${it.fee})" })
        val ordered = talks.sortedWith(compareBy({ it.end }, { it.start }))
        val (count, fees) = earliestEndFirst(ordered)
        println("  earliest end first: staffs $count, earns $fees")
        println("  dynamic program: earns ${mostFees(ordered)}")
    }
}

In Kotlin: compareBy with two selectors sorts by end, then start, and withIndex() gives each talk with its position for the table.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

import 'dart:math';

/// A talk may start when another ends.
typedef Talk = ({int start, int end, int fee});

const days = [
  [(0, 1, 1), (0, 2, 2)],
  [(9, 10, 2), (9, 12, 9), (10, 11, 3), (11, 13, 4), (12, 15, 8), (13, 14, 2)],
];

/// Problem 1, greedy: take each talk that fits after the last one taken.
({int count, int fees}) earliestEndFirst(List<Talk> ordered) {
  var (count, fees) = (0, 0);
  var freeFrom = 0; // no talk starts before 0
  for (final talk in ordered) {
    if (talk.start >= freeFrom) {
      (count, fees, freeFrom) = (count + 1, fees + talk.fee, talk.end);
    }
  }
  return (count: count, fees: fees);
}

/// Problem 2, DP: best[i] is the most from the first i talks by end.
int mostFees(List<Talk> ordered) {
  final best = [0];
  for (var i = 0; i < ordered.length; i++) {
    var (lo, hi) = (0, i); // talks that end by this start
    while (lo < hi) {
      final mid = (lo + hi) ~/ 2;
      if (ordered[mid].end <= ordered[i].start) {
        lo = mid + 1;
      } else {
        hi = mid;
      }
    }
    best.add(max(best[i], ordered[i].fee + best[lo]));
  }
  return best.last;
}

void main() {
  for (final day in days) {
    final talks = [for (final (s, e, f) in day) (start: s, end: e, fee: f)];
    print(talks.map((t) => '(${t.start}, ${t.end}, ${t.fee})').join(' '));
    final ordered = [...talks]
      ..sort((a, b) => a.end != b.end ? a.end - b.end : a.start - b.start);
    final staffed = earliestEndFirst(ordered);
    print(
      '  earliest end first: staffs ${staffed.count}, earns ${staffed.fees}',
    );
    print('  dynamic program: earns ${mostFees(ordered)}');
  }
}

In Dart: Each talk is a record with named fields, and [...talks]..sort sorts a copy, so the list of the day keeps its order.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

(0, 1, 1) (0, 2, 2)
  earliest end first: staffs 1, earns 1
  dynamic program: earns 2
(9, 10, 2) (9, 12, 9) (10, 11, 3) (11, 13, 4) (12, 15, 8) (13, 14, 2)
  earliest end first: staffs 4, earns 11
  dynamic program: earns 17

On the conference day the earliest-end rule staffs four talks, the most possible, and earns 11; the dynamic program earns 17 from two long talks, (9, 12) and (12, 15).

Key idea

Once the choices carry different values, the same slots sorted the same way need a table instead of a greedy rule: the earliest-end rule still staffs the most talks, but it no longer earns the most.

Checkpoint

Check: Greedy or DP for look-alike problems

  1. Question 1 of 2 Given the start and end times of n meetings, what is the fewest rooms that can hold them all?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Sort by start time and keep a min-heap of end times

    Sort the meetings by start; a min-heap holds the end times of the rooms in use, so each new meeting reuses the room that frees up first, or opens a room. The heap's largest size is the answer, O(n log n). Sorting the starts and ends as one list of events and counting gives the same number. See the interval conventions lesson.

  2. Question 2 of 2 In the table of the three talks, talk 3, (1, 2) paying 2, is taken after the talks that end by its start. Which entry does it add its fee to?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: best[1]

    Talk 3 starts at 1. Of the ends before it, 1 and 2, only talk 1's is at most 1, so before = 1 and taking talk 3 earns 2 + best[1] = 3, which beats skipping it, best[2] = 2.

Is it DP, and which way to write it?

Dynamic programming fits when three things hold. The problem is made of choices (take or skip, which coin, which split). The best or the count for the whole is built from the best or the count of smaller instances of the same problem. And those smaller instances repeat, so that remembering them saves work. Richard Bellman, who developed the method, called the second property the principle of optimality: Bellman's name for the property that a best solution is made of best solutions to smaller instances of the same problem, so the best for the whole can be built from the best for its parts.. If you can say the subproblem in one sentence (“the most money from the first i talks”), you have a state; if a greedy rule has a counterexample, you need the state.

There are two ways to write the same recurrence. Top-down is the memoisation: Storing the answer to each subproblem the first time a recursive function computes it, so a later call with the same arguments returns it at once. Top-down dynamic programming is recursion with memoisation.: it is quick to write from the recurrence and computes only the states it reaches. Bottom-up fills a table in an order that has every smaller state ready: it needs no recursion and can often keep only the last row or two. The program below writes two recurrences both ways in Python:

Top-down against bottom-up, on two recurrences Python · dp_styles/dp_styles.py
"""Top-down or bottom-up: the same two recurrences written both ways.

1. Bit strings of length n with no two 1s side by side, counted modulo 10**9 + 7. Every state from n down to 0 is
   needed, and the top-down version recurses n levels deep.
2. g(0) = 1 and g(n) = g(n // 2) + g(n // 3). From one large n, only a few values of n are ever reached.
"""
import sys
from functools import cache

MOD = 10**9 + 7


def ways_top_down(n, memo):
    """The recursion with a cache: one dictionary entry per length already counted."""
    if n <= 1:
        return n + 1  # "" for n = 0; "0" and "1" for n = 1
    if n not in memo:
        memo[n] = (ways_top_down(n - 1, memo) + ways_top_down(n - 2, memo)) % MOD
    return memo[n]


def ways_bottom_up(n):
    a, b = 1, 2  # ways for lengths 0 and 1; two variables are the whole table this recurrence needs
    for _ in range(n):
        a, b = b, (a + b) % MOD
    return a


print("1. Bit strings with no two 1s side by side")
print(f"   recursion limit: {sys.getrecursionlimit()}")
for n in (10, 500, 5000):
    try:
        top = ways_top_down(n, {})
    except RecursionError as e:
        top = type(e).__name__
    print(f"   n = {n:>5,}: top-down {top}, bottom-up {ways_bottom_up(n)}")


@cache
def g(n):
    return 1 if n == 0 else g(n // 2) + g(n // 3)  # functools.cache keeps one entry per n it has computed


print()
print("2. g(n) = g(n // 2) + g(n // 3), from one large n")
for n in (10**6, 10**12, 10**18):
    g.cache_clear()
    value = g(n)
    print(f"   n = 10^{len(str(n)) - 1}: g(n) = {value:,}; top-down computed {g.cache_info().currsize:,} values,"
          f" a bottom-up table would hold {n + 1:,}")

Output

1. Bit strings with no two 1s side by side
   recursion limit: 1000
   n =    10: top-down 144, bottom-up 144
   n =   500: top-down 73724597, bottom-up 73724597
   n = 5,000: top-down RecursionError, bottom-up 396105780

2. g(n) = g(n // 2) + g(n // 3), from one large n
   n = 10^6: g(n) = 80,406; top-down computed 108 values, a bottom-up table would hold 1,000,001
   n = 10^12: g(n) = 4,266,563,557; top-down computed 438 values, a bottom-up table would hold 1,000,000,000,001
   n = 10^18: g(n) = 224,412,958,156,019; top-down computed 1,012 values, a bottom-up table would hold 1,000,000,000,000,000,001

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 dp_styles.py

The first recurrence counts bit strings of length n with no two 1s side by side. Its top-down version recurses n levels deep, so at n = 5,000 it passes CPython’s recursion limit: The deepest chain of nested Python calls that CPython allows before it raises RecursionError: 1,000 by default, read with sys.getrecursionlimit() and changed with sys.setrecursionlimit(). More in “Python toolkit for coding rounds” of 1,000 and stops with a RecursionError. The bottom-up loop keeps two variables, the whole table that this recurrence needs. The second recurrence, g(n) = g(n // 2) + g(n // 3), reaches only a few values from one large n: 438 of them for n = 10¹², where a bottom-up table would need more than 10¹² cells. The table sets the two ways side by side:

Writing a dynamic program top-down or bottom-up
Criterion Top-down: recursion with a cacheBottom-up: a table in order
Coding Almost a copy of the recurrenceNeeds an order in which smaller states come first
States Only those reached from the startEvery state in the table
Depth Up to the longest chain of states; Python stops at about 1,000 by defaultNone
Memory The cache holds every state reachedOften one or two rows, kept as rolling arrays
When to choose Sparse or irregular states, and a first working versionLong chains of states, tight memory, and Python or JavaScript on deep inputs

In an interview, a top-down version is often the fastest way to a correct answer. Say how deep it recurses; if the depth can reach the limits, convert it to bottom-up. Raising the limit with sys.setrecursionlimit is the other way out, but only with care: the sys documentation cautions that too high a limit can make Python crash.

Checkpoint

Check: When DP fits, and which way to write it

  1. Question 1 of 2 Which three signs together say that a problem needs dynamic programming?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Choices, a best or a count built from smaller instances of the same problem, and those instances repeat

    Dynamic programming fits when the problem is made of choices, the best or the count for the whole is built from the best or the count of smaller instances, and those instances repeat, so remembering them saves work.

  2. Question 2 of 2 A top-down recurrence calls itself n levels deep, n can be 10⁵, and you are writing Python. What do you do?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Write it bottom-up, filling the states in order, so no recursion is needed

    The lesson's run stopped the top-down version at n = 5,000 with RecursionError, while the bottom-up loop of two variables answered at once. Say how deep a top-down version recurses; if the depth can reach the limits, convert it to bottom-up.

Practise: classify more sketches

The practice below mixes ten more original sketches, unlabeled and in no particular order, with questions on each idea of the lesson. It starts with the idea you know least and gets harder as your answers come out right. Choose the pattern you would try first; each explanation says why and links to the lesson that teaches the pattern.

Practice that adapts to you

Practise this lesson

20 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 20 Which of the three readings gives you the target complexity before you design anything?

    Choose one answer.

    Show the answer: Question 1 of 20

    Answer: The limits

    The shape and the words point to candidates, and the limits say which of them is fast enough. With n up to 2 × 10⁵, only O(n log n) or better remains.

  2. Question 2 of 20 Your three readings: 'an unsorted list of up to 10⁵ positive integers; the length of the shortest contiguous run with a total of at least S'. Which pattern do you try first?

    Choose one answer.

    Show the answer: Question 2 of 20

    Answer: A sliding window

    Contiguous runs, positive values and a threshold on the total point to a sliding window, and with positive values the property a window needs holds. Each end of the window moves at most n times, so it runs in O(n).

  3. Question 3 of 20 The table's first row suggests binary search on the answer. What must be true before it is correct?

    Choose one answer.

    Show the answer: Question 3 of 20

    Answer: The yes-or-no test is monotone: once it is true for a value, it stays true for every larger value

    A clue suggests a pattern, and its property decides it. For binary search on the answer the property is a monotone test: if a capacity of 30 works, so does every capacity above 30, so one test rules out half the range.

  4. Question 4 of 20 A sorted list of 10⁶ timestamps, then 10⁵ queries: how many timestamps fall between a and b? Which pattern do you try first?

    Choose one answer.

    Show the answer: Question 4 of 20

    Answer: Two binary searches per query, one for each end

    The input is sorted and the questions are many, so each query should cost O(log n): the position of the first timestamp ≥ a and the position of the first timestamp > b differ by the count. That is 10⁵ × 2 × 20 steps, about 4 million. The binary search lesson writes both searches.

  5. Question 5 of 20 Parcels must be delivered in the given order within d days. What is the smallest daily weight limit that makes this possible?

    Choose one answer.

    Show the answer: Question 5 of 20

    Answer: Binary search on the limit, with a greedy check for each guess

    "The smallest value such that it works" is the signal for searching on the answer: if a limit works, every larger limit works, so the yes/no answer is monotone. Each check packs parcels in order, one pass, so the total cost is O(n log W) for a weight range W. See the binary search lesson.

  6. Question 6 of 20 In the flow from a shortlist to one choice, what comes right after the shortlist?

    Choose one answer.

    Show the answer: Question 6 of 20

    Answer: Compare each candidate's cost with the budget that the limits allow

    The flow runs shortlist, budget, small-case check, then the choice said aloud with its cost. Costing first keeps the check for the candidates that could be fast enough.

  7. Question 7 of 20 Your check finds that the earliest-end rule earns 1 on two talks where the brute force earns 2. What does the flow say to do next?

    Choose one answer.

    Show the answer: Question 7 of 20

    Answer: Drop the rule and take the next candidate on the shortlist

    In the flow, a candidate that gives a different answer from the brute force goes back to the shortlist. The dynamic program is next: it fits the same O(n log n) budget and agrees on every small input.

  8. Question 8 of 20 The values go up to 10⁹. Which plan does that rule out before anything else?

    Choose one answer.

    Show the answer: Question 8 of 20

    Answer: An array indexed by value

    The other limits cross out more than n does. Values up to 10⁹ rule out an array indexed by value, so use a hash map, or sort and compress the values to their ranks.

  9. Question 9 of 20 There are 15 cities with travel costs between every pair. What is the cheapest tour that starts at city 1 and visits every city once?

    Choose one answer.

    Show the answer: Question 9 of 20

    Answer: Dynamic programming over subsets of visited cities, stored as bitmasks

    n = 15 is the clue: 2¹⁵ × 15 = 491,520 states (a set of visited cities and the city you are in), each with 15 moves, about 7 million steps. Trying every order would be 14!, about 8.7 × 10¹⁰. The nearest-city rule gives a tour but not the cheapest. The constraints lesson reads n ≤ 20 as a hint for subsets.

  10. Question 10 of 20 Ten players have skill ratings. List every way to split them into two teams of five with equal total skill.

    Choose one answer.

    Show the answer: Question 10 of 20

    Answer: Backtracking that builds one team and checks the totals

    "List every way" asks for the arrangements themselves, and there are only C(10, 5) = 252 ways to pick the first team, so building them one choice at a time and pruning when the total is already too high is fast. The greedy rule returns one split, which may not even be equal. See the backtracking lesson.

  11. Question 11 of 20 Decide whether a singly linked list loops back on itself, using O(1) extra memory.

    Choose one answer.

    Show the answer: Question 11 of 20

    Answer: A slow pointer and a fast pointer

    A hash set works but costs O(n) memory, which the statement forbids. A pointer that moves one step and another that moves two meet inside the loop if there is one, and the fast pointer reaches the end if there is not. See the linked-list toolkit.

  12. Question 12 of 20 A trader logs daily profit or loss, which can be negative. Count the stretches of consecutive days whose total is exactly zero.

    Choose one answer.

    Show the answer: Question 12 of 20

    Answer: Prefix sums, counting equal prefix values in a hash map

    A stretch from day i to day j totals zero exactly when the running totals before i and after j are equal, so count how often each running total has appeared. Negative values break the window's monotone validity, and sorting destroys the order the stretches depend on. See the prefix-sum lesson.

  13. Question 13 of 20 A rail map lists 2,000 stations and 10,000 direct tickets, each with a price. What is the cheapest way from station 1 to station 2,000?

    Choose one answer.

    Show the answer: Question 13 of 20

    Answer: Dijkstra's algorithm, because every price is non-negative

    Tickets have different prices, so the fewest tickets is not the cheapest trip and plain breadth-first search answers the wrong question. Prices are never negative, which is the condition Dijkstra's algorithm needs: O(E log V) with a heap. Taking the cheapest next ticket can walk into an expensive dead end. The graph-modelling lesson compares the searches.

  14. Question 14 of 20 Two gene strings, each 5,000 letters long. What is the length of the longest sequence of letters that appears in both, in order but not necessarily side by side?

    Choose one answer.

    Show the answer: Question 14 of 20

    Answer: Two-dimensional dynamic programming over prefixes of both strings

    "In order but not side by side" means a subsequence, not a substring, so windows and substring sets answer a different question. The state is a pair of prefix lengths: 5,000 × 5,000 = 2.5 × 10⁷ cells, each O(1), and two rows of the table are enough memory. See DP from recursion.

  15. Question 15 of 20 Sketch 4 asked for the quickest metro route. Now the question is 'the route with the fewest changes between lines'. Which plan fits?

    Choose one answer.

    Show the answer: Question 15 of 20

    Answer: A breadth-first search with weights of 0 and 1: riding on costs 0, changing lines costs 1

    One word moved the problem again. "Fewest changes" makes a ride along a line cost 0 and a change cost 1, so the search tracks the station and the line, and a 0-1 BFS settles states in order of changes with a deque.

  16. Question 16 of 20 Coins come in values 1, 7 and 10. What is the fewest number of coins that pays an amount of up to 10⁵ exactly?

    Choose one answer.

    Show the answer: Question 16 of 20

    Answer: Dynamic programming over the amounts from 0 upwards

    The largest coin first fails on 14: it pays 10 + 1 + 1 + 1 + 1, five coins, where 7 + 7 needs two. The choices overlap (the best for 14 builds on the best for 7), which is the DP signal: best[a] = 1 + min(best[a − c]) over the coins, O(amount × coins). See DP from recursion and the greedy proofs lesson.

  17. Question 17 of 20 Talks have start and end times, and you can attend one talk at a time. What is the largest number of talks you can attend?

    Choose one answer.

    Show the answer: Question 17 of 20

    Answer: Greedy, always taking the talk that ends first among those that fit

    Taking the earliest-ending talk leaves the most time for the rest, and an exchange argument proves it is never worse than any other first choice. The shortest-talk rule fails: a short talk can overlap two long ones that fit together. With a fee per talk the greedy rule breaks, as this lesson's run shows. See the greedy proofs lesson.

  18. Question 18 of 20 A statement: 'jobs with a start, an end and a profit; choose jobs that do not overlap, for the most profit.' Your partner suggests the earliest-end rule because it solved 'the most talks'. What do you answer?

    Choose one answer.

    Show the answer: Question 18 of 20

    Answer: That the word 'profit' moves it to dynamic programming: the rule earns 1 on (0, 1) paying 1 and (0, 2) paying 2, where 2 is possible

    Once choices carry different values, a choice that looks best now can cost more later. The dynamic program over jobs sorted by end, best[i] = max(best[i − 1], profit + best[before]), is right on every input.

  19. Question 19 of 20 What does the bottom-up count of bit strings with no two 1s side by side keep in memory?

    Choose one answer.

    Show the answer: Question 19 of 20

    Answer: Two variables, the counts for the last two lengths

    Bottom-up fills the states in an order that has every smaller state ready, and it can often keep only the last row or two. Here the count for length n needs only the counts for n − 1 and n − 2.

  20. Question 20 of 20 g(0) = 1 and g(n) = g(n // 2) + g(n // 3), asked for one n = 10¹². Which way do you write it?

    Choose one answer.

    Show the answer: Question 20 of 20

    Answer: Top-down with a cache, because from 10¹² it reaches only 438 values

    Top-down computes only the states it reaches from the start: 438 for n = 10¹², where a bottom-up table would need more than 10¹² cells. Its depth is only about 40 calls, since each call at least halves n.

Python Online Compiler Paste look_alike.py, add a talk of your own to the small cases, and watch which rule breaks first.

Interview questions

What tells you that a problem needs dynamic programming rather than a greedy rule? (warm-up)

Three signs together. The problem is a sequence of choices; the answer for the whole is built from answers to smaller versions of the same problem; and those smaller versions repeat. A greedy rule commits to one choice and never looks back, so it is only right when some argument, such as an exchange argument, shows that the choice it makes is never worse than any other. The quickest test is a counterexample hunt: write a brute force for small inputs and compare. If greedy fails, for example the largest coin first with coins 1, 4 and 6 on an amount of 8, give each subproblem a name in words and write the recurrence. “Count the ways” almost always means dynamic programming, since a greedy rule produces one answer, not a count.

The warm-up rarely ends the exchange. Here are three questions an interviewer might ask next, each with four replies; settle on yours before you open the feedback on the others:

Checkpoint

Interview round: three follow-up questions

  1. Question 1 of 3 The interviewer asks how you would convince yourself that taking the earliest-ending talk is right for problem 1. Which answer is strongest?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: Compare it with a brute force on every small input, then argue by exchange: a best schedule can swap its first talk for the earliest-ending one and lose nothing

    The check against a brute force finds a counterexample if a small one exists, and the exchange argument covers every input: the talk that ends first leaves at least as much time for the rest as any other first choice.

  2. Question 2 of 3 The follow-up: 'Count the ways to pay 8 with coins of 1, 4 and 6.' Why can no greedy rule answer it?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: A greedy rule builds one way to pay, and a count needs every way, which a table over the amounts adds up

    A greedy rule commits to one choice at each step and ends with one way to pay. Counting needs every way, which a table over the amounts builds from the counts for smaller amounts.

  3. Question 3 of 3 Halfway through your earliest-end solution, the interviewer says each talk now pays a fee and asks for the most money. What survives from your code?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: Sorting by end survives; the greedy choice does not, and a dynamic program over the sorted talks replaces it

    The fee is the word that moves the problem to dynamic programming. The talks are still taken in order of their ends, best[i] = max(best[i − 1], fee + best[before]), with a binary search for the talks that end in time.

Two harder questions of this module start from this lesson:

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    Twenty minutes are left in a round. For a problem with n up to 10⁵ you have two ideas: a greedy rule you cannot prove and an O(n log n) dynamic program you have not written yet. What do you do in the next three minutes, and what do you say?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    You are writing a breadth-first search for the fewest moves across a 500 × 500 grid. The interviewer adds a rule: entering a mud cell costs 5 and entering any other cell costs 1. What changes in your solution, and what does each option cost?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Read every statement three times: the shape of the input, the words of the question and the limits.
  • A clue suggests a pattern; the property to check, in the table’s second column, decides whether it is correct.
  • The limits cross out patterns before you start: n ≤ 20 keeps subsets on the list, n ≥ 10⁵ leaves only O(n log n) or better, and negative values rule out windows over sums and Dijkstra’s algorithm.
  • Check a greedy rule or a window against a brute force on every small input: in the run, a rule that was right on 93 % of random sets failed on three talks.
  • Write a dynamic program top-down for sparse states and a quick first version, bottom-up for deep chains and tight memory.

Terms in this lesson

exchange argument
A proof that a greedy choice is safe: take any best solution, swap its first choice for the one the greedy rule makes, and show that the result is no worse, so some best solution starts with the greedy choice.
memoisation
Storing the answer to each subproblem the first time a recursive function computes it, so a later call with the same arguments returns it at once. Top-down dynamic programming is recursion with memoisation.
principle of optimality
Bellman's name for the property that a best solution is made of best solutions to smaller instances of the same problem, so the best for the whole can be built from the best for its parts.
subsequence
Items taken from a sequence in their original order but not necessarily side by side: 1, 3, 4 is a subsequence of 1, 2, 3, 4. A substring or a subarray must be contiguous.

Corrections

  • The practice section now says that ten of the twenty sketches sit in the checkpoints beside the sections they check and ten in the practice.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.