Data Structures and Algorithms, Pattern by Pattern / Module 12

Module 12: Capstone: Choosing the Pattern

Choose the pattern for a new problem: read the input limit, write the slow solution, find the work it repeats, and match its signs to a pattern.

Here are three problems about one list, [8, 3, 5, 9, 1], and a total:

  • A. The numbers are prices. Do two of them add up to the total?
  • B. They are requests per minute. Does a run of consecutive minutes add up to the total?
  • C. They are costs. Does any group of them add up to the total?

Save opening.ts, which answers all three:

// Three problems that ask "is there a total of T?" and need three different patterns: node opening.ts

// A. Two prices, at different positions, that add up to total? Hashing (Module 3): O(n) time, O(n) memory.
export function hasPairWithTotal(prices: number[], total: number): boolean {
  const seen = new Set<number>();
  for (const p of prices) {
    if (seen.has(total - p)) return true;
    seen.add(p);
  }
  return false;
}

// B. A run of consecutive minutes that adds up to total? Every count is positive, so adding a minute
// only raises the sum and dropping one only lowers it. Sliding window (Module 2): O(n) time, O(1) memory.
export function hasRunWithTotal(counts: number[], total: number): boolean {
  let left = 0;
  let sum = 0;
  for (let right = 0; right < counts.length; right++) {
    sum += counts[right];
    while (sum > total && left <= right) sum -= counts[left++];
    if (sum === total && left <= right) return true; // left <= right: the run is not empty
  }
  return false;
}

// C. Any group of costs (positive whole numbers) that adds up to total? The empty group adds up to 0.
// Dynamic programming over the totals, one row filled high to low so each cost is used once (Module 11):
// O(n * total) time, O(total) memory.
export function hasGroupWithTotal(costs: number[], total: number): boolean {
  if (total < 0) return false;
  const reachable = new Array<boolean>(total + 1).fill(false);
  reachable[0] = true;
  for (const c of costs) for (let t = total; t >= c; t--) if (reachable[t - c]) reachable[t] = true;
  return reachable[total];
}

if (process.argv[1] === import.meta.filename) {
  const xs = [8, 3, 5, 9, 1];
  for (const t of [12, 16, 22])
    console.log(`total ${t}: pair ${hasPairWithTotal(xs, t)}, run ${hasRunWithTotal(xs, t)}, group ${hasGroupWithTotal(xs, t)}`);
}

Pause and predict. For the totals 12, 16 and 22, which of the three functions return true?

Here is what node opening.ts printed:

total 12: pair true, run false, group true
total 16: pair false, run true, group true
total 22: pair false, run false, group true

Figure 1 marks the numbers that make each answer true.

index        0   1   2   3   4
value        8   3   5   9   1

total 12     .   3   .   9   .     a pair, not next to each other
total 16     8   3   5   .   .     a run of three, and no pair
total 22     8   .   5   9   .     only a group

Figure 1: the three questions sound alike, but each one allows a different shape of answer, so each needs a different pattern.

A is a partner lookup in a Set (Module 3). B is a window that grows and shrinks (Module 2), and it works only because every count is positive. C is a row of reachable totals filled from high to low (Module 11). The code is short once you know the pattern, but the problem never tells you which one it is.

This module teaches a method for choosing between the patterns of Modules 1 to 11. It adds two short tours, of tries and of bit manipulation. Then you practice the method on six problems that don’t say which pattern they need.

After this module, you can:

  • follow six steps from a problem and its input limit to a pattern and its cost
  • match the signs in a problem to the pattern from Modules 1 to 11 that fits them
  • say when a trie or a bitmask is worth its cost
  • explain a solution in an interview: the slow version first, then the cost, then tests out loud

Make a folder for the module as in Module 1, and copy bench.ts into it unchanged:

mkdir module-12 && cd module-12 && echo '{ "type": "module" }' > package.json

opening.test.ts in the module’s folder checks the three functions against brute forces on 500 random lists. A brute force is a solution that tries every possibility, here every pair, every run and every group. It’s slow, but it’s easy to trust, so it makes a good check.

A method in six steps

Each module so far started from a slow solution and named the pattern that fixed it. With a new problem, nobody names the pattern for you. These six steps get you there:

  1. Restate the problem. Write the input, the output and one small example worked by hand. Note the edge cases, the inputs at the edge of what the statement allows: an empty input, ties, repeated values.
  2. Read the input limit and get the target cost. The target cost is the slowest Big O that still finishes in time for the largest n.
  3. Write the slow solution. Write the one you’re sure is correct, and state its cost.
  4. Find the repeated work. Look for what the slow solution computes more than once.
  5. Pick the pattern that removes that work. The table of signs in the next section maps what you see to a module.
  6. Test the edge cases. Check the fast solution against the slow one on small random inputs, then on the largest input.

The rest of this section runs the steps on problem B.

Restate, then read the limit

Restated, problem B is this. The input is a list of request counts, one per minute, each a positive whole number, and a total. The output is true if one or more consecutive minutes add up to the total. On Figure 1’s list, the total 16 is true (8 + 3 + 5), and 12 is false, because 3 and 9 aren’t next to each other.

Now suppose the list can hold up to 1,000,000 minutes. Module 1 set a budget of about 10⁸ simple steps per second. Figure 2 extends its table of limits with the patterns of this course that reach each cost.

largest n       target cost    patterns that reach it (module)
about 10        O(n!)          every order, backtracking (10)
about 25        O(2^n)         every subset, backtracking (10)
about 464       O(n^3)         three nested loops (none in this course)
about 10,000    O(n^2)         two nested loops; DP over two lists (11)
about 4,500,000 O(n log n)     sort (1); heap (8); binary search per item (9)
about 10^8      O(n)           window, two pointers, prefix sums (2);
                               Set and Map (3); stack, queue (5);
                               walks of trees and graphs (6, 7)
larger          O(log n), O(1) binary search (9); Map.get (3);
                               a prefix sum lookup (2)

Figure 2: the input limit sets the target cost, and the target cost leaves only a few patterns to choose from.

With 1,000,000 minutes, O(n²) is 10¹² steps, about three hours. So the target is O(n), or O(n log n) at most. But does the budget of 10⁸ steps per second still hold on a current machine?

For loops of arithmetic and array reads, it does, with room to spare. A step that hashes into a large Map or grows a Set ran 7 to 14 times under the budget. So when each step of a solution hashes, count it as about 10 simple steps. “Going deeper”, at the end of the module, has the file that measured six kinds of steps.

Every number in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ.

Steps 3 to 6 on problem B

The slow solution tries every start and adds minutes until the sum reaches or passes the total. method.ts writes it and times it against the window from opening.ts. Save it:

// The method on problem B, a run of minutes that adds up to a total: node method.ts
import assert from "node:assert/strict";
import { bench } from "./bench.ts";
import { hasRunWithTotal } from "./opening.ts";

// The slow solution: try every start, and add minutes until the sum reaches or passes the total.
// O(n^2) time in the worst case (a start can add up to n minutes), O(1) memory.
export function hasRunSlow(counts: number[], total: number): boolean {
  for (let start = 0; start < counts.length; start++) {
    let sum = 0;
    for (let end = start; end < counts.length && sum < total; end++) {
      sum += counts[end];
      if (sum === total) return true;
    }
  }
  return false;
}

// Even counts from 2 to 200, and an odd total near half their sum: no run matches, so both
// versions do all their work.
function makeMinutes(n: number): { counts: number[]; total: number } {
  const counts = Array.from({ length: n }, () => 2 * (1 + Math.floor(Math.random() * 100)));
  const sum = counts.reduce((s, c) => s + c, 0);
  return { counts, total: 2 * Math.floor(sum / 4) + 1 };
}

let sink = 0; // keeps every result, so no run can be skipped as unused

if (process.argv[1] === import.meta.filename) {
  for (let t = 0; t < 1000; t++) {
    const counts = Array.from({ length: Math.floor(Math.random() * 30) }, () => 1 + Math.floor(Math.random() * 9));
    const total = Math.floor(Math.random() * 60);
    assert.equal(hasRunSlow(counts, total), hasRunWithTotal(counts, total));
  }
  console.log("hasRunSlow and hasRunWithTotal agree on 1,000 random lists: true");

  const sizes = [10_000, 20_000, 40_000];
  bench("hasRunSlow", sizes, makeMinutes, ({ counts, total }) => (sink += +hasRunSlow(counts, total)));
  bench("hasRunWithTotal", sizes, makeMinutes, ({ counts, total }) => (sink += +hasRunWithTotal(counts, total)));
  bench("hasRunWithTotal, larger", [1_000_000, 2_000_000, 4_000_000], makeMinutes, ({ counts, total }) => (sink += +hasRunWithTotal(counts, total)));
  if (sink !== 0) console.log(sink);
}

The input makes both versions do all their work: every count is even and the total is odd, so no run matches.

Pause and predict. hasRunSlow takes about 40 ms for 10,000 minutes. How long does it take for 40,000?

node method.ts printed:

hasRunSlow and hasRunWithTotal agree on 1,000 random lists: true

hasRunSlow
             n   median ms   x prev
        10,000       40.14
        20,000      159.52      4.0
        40,000      638.86      4.0

hasRunWithTotal
             n   median ms   x prev
        10,000        0.12
        20,000        0.16      1.4
        40,000        0.32      2.0

hasRunWithTotal, larger
             n   median ms   x prev
     1,000,000        8.01
     2,000,000       16.03      2.0
     4,000,000       30.67      1.9

The slow version grew 4 times per doubling, so it’s O(n²) as stated. At 1,000,000 minutes it would take about 640 ms × 625 = 400 seconds (not run). Figure 3 compares the two at the sizes they share.

median ms for a run of minutes (each # is about 15 ms)

n = 10,000   slow     ###                                           40.14
             window   |                                              0.12
n = 20,000   slow     ###########                                  159.52
             window   |                                              0.16
n = 40,000   slow     ###########################################  638.86
             window   |                                              0.32

Figure 3: the slow version grows 4 times per doubling of the minutes, and the window grows 2 times.

Step 4 asks where the slow version repeats itself. Figure 4 traces both versions on Figure 1’s list with the total 15, as trace-demo.ts prints it.

total 15, minutes 8 3 5 9 1

slow: every start, add until the sum reaches 15
start 0:  +8 = 8     +3 = 11    +5 = 16  (over)
start 1:  +3 = 3     +5 = 8     +9 = 17  (over)
start 2:  +5 = 5     +9 = 14    +1 = 15  found
9 additions

window: add on the right, drop on the left while over 15
right 0:  +8 = 8
right 1:  +3 = 11
right 2:  +5 = 16   -8 = 8
right 3:  +9 = 17   -3 = 14
right 4:  +1 = 15  found
5 additions, 2 drops

Figure 4: each new start adds again the minutes the last start already added, while the window keeps the sum and only adjusts its two ends.

The slow version added 5 three times, and 3 and 9 twice. Each start rebuilds a sum that mostly overlaps the last one. That’s the repeated work. “A run of consecutive items” plus “a range that mostly overlaps the last one” is the sign of Module 2’s window that grows and shrinks.

Step 6 tests the edge cases, and the first one is the window’s own condition. Adding a minute must only raise the sum, and dropping one must only lower it, which holds because every count is positive. With a negative count, dropping a minute can raise the sum, so the window can skip the run it needed. Then the pattern is Module 3’s Map of earlier running totals.

The other edge cases are an empty list, a total of 0 (no run is empty, so false) and a run that is the whole list. opening.test.ts checks each one.

Rule: Find the repeated work in the slow solution before you name a pattern. The pattern is whatever removes that work.

The limit can choose the pattern

Problem C shows step 2 deciding between two patterns. Module 11’s row of reachable totals costs O(n · T) for n costs and a total T. Module 10’s backtracking costs O(2ⁿ).

Suppose the list has up to 200 costs of at most 100 each. The totals reach at most 20,000, so the row is 200 × 20,000 = 4 × 10⁶ steps, while 2²⁰⁰ subsets are out of reach.

Now suppose the list has up to 20 costs of up to 10⁹ each. The row would need 20 × 10⁹ steps, and 2²⁰ is about 10⁶ subsets. So with the same question, backtracking is now the right choice.

Signs that point to each pattern

Step 5 needs a map from what you see in a problem to a pattern. Each row of this table uses the names that its module used, and each module’s cheat sheet has more detail.

Module Patterns Signs in the problem
1 Read the input limit; replace a scan inside a loop with a Set or Map Every problem: read n first. includes, indexOf, find, concat or sort inside a loop
2 Sliding window, two pointers, prefix sums “the longest (shortest) run such that”, “every k consecutive”, a pair in sorted data, many range totals on data that doesn’t change
3 Hashing: existence, counting, grouping, partner lookup, earlier running totals “seen before?”, “how many of each”, “all X for each Y”, two items that combine to a target, a run that adds up to exactly k with negative values
4 Linked list with node references, dummy head, fast and slow pointers, LRU cache items removed or moved in the middle while you hold them, “does it come back?” in O(1) memory, “least recently used”
5 Stack, queue with a head index or ring buffer, monotonic stack, deque nesting or undo, first in first out, “next (previous) larger or smaller” for every item, the max of every window
6 Depth-first walk with an explicit stack, breadth-first walk by level, binary search tree a hierarchy (folders, org charts, JSON) whose depth comes from input, “per level”, keys in order
7 Visited set, BFS for fewest steps, Kahn’s algorithm, connected components links or dependencies, “fewest steps” when every step costs the same, “build after”, “how many groups”, a grid
8 Binary heap (priority queue): top k, two heaps for a median, merge k sorted lists, Dijkstra’s algorithm “top k”, “take the smallest next” again and again, “median so far”, “cheapest path” when steps cost different amounts
9 Lower and upper bound, binary search on the answer, greedy rule sorted data and “the first at or after”, “the smallest (largest) x such that” with a yes-or-no check that flips once, intervals
10 Backtracking (choose, explore, undo), pruning “list every”, “all the ways”, n up to about 20 to 25
11 Dynamic programming: find the state, top down (memoization), bottom up (a table) “how many ways”, “the fewest”, “the most”, where the slow recursion asks the same smaller question many times

Two rows can fit one problem. Both a Map of running totals and a window can find a run with a total. Then the condition decides (positive values or not), and so does the limit.

A short tour of tries

Suppose a command line keeps a list of known words. As you type, it shows how many words start with what you’ve typed so far. With the words in a Set, each count checks every word with startsWith, which is O(n · P) for n words and a prefix of P characters. At 1,000,000 words, 100 counts took about one second in the run below.

A trie is a tree with one node per distinct prefix of the stored words. Each node maps the next character to a child node. So a count walks P nodes from the root and reads a number stored there, whatever n is.

trie.ts keeps in each node the number of words that pass through it. Save it:

// A trie of words: one node per distinct prefix, and each node maps the next character to a child.
// node trie.ts

export class TrieNode {
  children = new Map<string, TrieNode>();
  isWord = false; // a stored word ends here
  count = 0; // how many stored words start with the prefix that leads here
}

export class Trie {
  root = new TrieNode();

  // O(L) for a word of L characters. A word added twice is stored once.
  add(word: string): void {
    if (this.has(word)) return;
    let node = this.root;
    node.count++;
    for (const ch of word) {
      let next = node.children.get(ch);
      if (next === undefined) {
        next = new TrieNode();
        node.children.set(ch, next);
      }
      node = next;
      node.count++;
    }
    node.isWord = true;
  }

  // O(P) for a prefix of P characters, however many words are stored.
  countWithPrefix(prefix: string): number {
    let node = this.root;
    for (const ch of prefix) {
      const next = node.children.get(ch);
      if (next === undefined) return 0;
      node = next;
    }
    return node.count;
  }

  // O(L).
  has(word: string): boolean {
    let node: TrieNode | undefined = this.root;
    for (const ch of word) {
      node = node.children.get(ch);
      if (node === undefined) return false;
    }
    return node.isWord;
  }
}

if (process.argv[1] === import.meta.filename) {
  const t = new Trie();
  for (const cmd of ["deploy", "deploy-preview", "dev", "db-migrate", "db-seed", "dev"]) t.add(cmd);
  console.log("start with 'de':", t.countWithPrefix("de"), " 'db-':", t.countWithPrefix("db-"), " 'x':", t.countWithPrefix("x"), " '':", t.countWithPrefix(""));
  console.log("has 'dev':", t.has("dev"), " has 'de':", t.has("de"));
}

node trie.ts adds five commands, one of them twice, and printed:

start with 'de': 3  'db-': 2  'x': 0  '': 5
has 'dev': true  has 'de': false

add checks has first, so the second “dev” is not counted again. Figure 5 is the trie, as trace-demo.ts prints it.

root 5
    d 5
        e 3
            p 2   l 2   o 2   y 2 *
                - 1   p 1   r 1   e 1   v 1   i 1   e 1   w 1 *
            v 1 *
        b 2   - 2
            m 1   i 1   g 1   r 1   a 1   t 1   e 1 *
            s 1   e 1   e 1   d 1 *
28 nodes, one per distinct prefix; countWithPrefix("de") = 3

Figure 5: each node holds the number of words that pass through it, and * marks the end of a word. A run of nodes with one child each is drawn on one line.

add, has and countWithPrefix are O(L) for a word or prefix of L characters. The memory is one node per distinct prefix, at most the total length of all the words.

Pause and predict. A Set of 100,000 words of 8 letters holds about 4.8 MB with its strings. How much does a trie of the same words hold?

trie-vs-set.ts measures both, with a garbage collection before each reading, then times 100 prefix counts. Run it with node --expose-gc trie-vs-set.ts:

8 random letters: 100,000 words, 800,000 characters
  Set with its strings 4.8 MB; trie 114.2 MB, 507,514 nodes, 236 bytes per node
URL paths: 99,125 words, 2,610,322 characters
  Set with its strings 7.0 MB; trie 179.5 MB, 804,832 nodes, 234 bytes per node

same counts for 100 prefixes on 10,000 words: true

100 prefix counts, scanning a Set
             n   median ms   x prev
        10,000       10.27
       100,000      103.33     10.1
     1,000,000     1025.39      9.9

100 prefix counts, walking a trie
             n   median ms   x prev
        10,000        0.03
       100,000        0.03      1.0
     1,000,000        0.03      1.2

The trie held 24 times the memory of the Set for random words, and 26 times for URL paths. Each node is an object with its own Map, about 235 bytes. The Set held 3 to 6 bytes per character of its words, strings included.

The counts behave as the costs say. Scanning the Set grew 10 times per 10 times more words, O(n · P). Walking the trie stayed at 0.03 ms, O(P).

A trie is worth it when many prefix questions hit a word list that changes rarely, as in completions or routing by path. It also fits an algorithm that walks a word one character at a time (Practice 6 has one). For “is this exact word there?”, a Set is as fast and 24 times smaller.

A short tour of bit manipulation

Module 10 listed every subset of a list by backtracking. When the list has at most about 25 items, a subset also fits in one number. A bitmask is a number whose bits stand for yes-or-no answers. Here bit i is 1 when item i is in the subset, so counting the mask from 0 to 2ⁿ − 1 visits every subset once.

This excerpt from the lab’s bits.ts lists the subsets of three flags:

// Subset masks: bit i set means item i is in the subset. Works for n <= 30 with Number.
const items = ["sso", "audit", "backup"];
for (let mask = 0; mask < 1 << items.length; mask++) {
  const picked = items.filter((_, i) => (mask & (1 << i)) !== 0);
  console.log(mask.toString(2).padStart(3, "0"), JSON.stringify(picked));
}

It printed the eight masks and their subsets:

000 []
001 ["sso"]
010 ["audit"]
011 ["sso","audit"]
100 ["backup"]
101 ["sso","backup"]
110 ["audit","backup"]
111 ["sso","audit","backup"]

<< shifts bits to the left, so 1 << i is a number with only bit i set. & keeps the bits that are 1 on both sides. So (mask & (1 << i)) !== 0 tests whether item i is in the subset.

JavaScript’s bitwise operators first turn each side into a 32-bit whole number. The top bit of the 32 is the sign bit, and when it is 1, the number is negative.

Pause and predict. 1 << 30 is 1,073,741,824. What do 1 << 31 and 1 << 32 print?

node bits.ts printed these lines, among others:

1 << 30                      1073741824
1 << 31                      -2147483648
1 << 32                      1

1 << 31 sets the sign bit, so it’s negative. 1 << 32 is 1, because a shift uses its count modulo 32, so it’s 1 << 0.

bits.ts also shows two common mistakes:

  • A loop bound of 1 << n. With n = 31 the bound is negative and the loop runs 0 times, and with n = 32 it runs once. Number masks are safe up to n = 30. Write the bound as 2 ** n, but 2³¹ subsets are already far over the budget.
  • Precedence. mask & (1 << i) === 1 means mask & ((1 << i) === 1), because JavaScript applies === before &. It said “out” for bits 1 and 2 of 0b110, which are in. TypeScript rejects it, but plain JavaScript runs it with no error. Write (mask & (1 << i)) !== 0.

Bit manipulation is worth it for subsets of up to about 25 items, and for sets of flags you test often. For everyday code, a Set of names is easier to read, and it has no 32-bit edge.

Six practice problems

Each problem below comes from everyday software and doesn’t say which pattern it needs. Use the six steps on each one before you open a hint.

The problems are in the module’s exercises folder, and the answers are in solutions. Run all the tests with:

node --test "exercises/*.test.ts"

All 34 tests fail until you write the six answers. Each problem’s tests do three things:

  • check the edge cases
  • compare your answer with a brute force on a few hundred small random inputs
  • run one large input that a correct but slow answer fails on time

The slow folder holds such slow answers, with a copy of each test. Their times come from one run each, and they moved by up to 2 times between runs. Practice 3 imports Module 8‘s heap.ts by path, so keep the module folders side by side.

Each problem has two hints. The first is about the limit and the slow solution, and the second is about the repeated work.

Practice 1: the longest chain of command (easy)

An org chart is a list where managerOf[i] is employee i’s manager, or −1 for someone with no manager. Write longestChain(managerOf): the most people in one chain from the top down. Start from exercises/longest-chain.ts:

// Practice 1: managerOf[i] is the manager of employee i, or -1 if i has no manager. Nobody manages
// themselves, directly or through others. Returns the most people in one chain of command, from
// someone with no manager down to one of their reports' reports, and so on (one person alone is a
// chain of 1). Up to 200,000 employees, and a manager's number can be larger than their report's.
export function longestChain(managerOf: number[]): number {
  throw new Error("not implemented");
}

For [-1, 0, 0, 1, 3] the answer is 4 (employees 0, 1, 3 and 4). The last test is one chain of 30,000 people, in under 100 ms.

Hint 1

The chart can have 200,000 people. Walking up from each person to the top and counting is correct. What does it cost when the chart is one long chain, and what cost does Figure 2 allow for 200,000?

Hint 2

Walking up from everyone climbs the same managers again and again. Turn the list around: give each manager a list of reports, and walk down from the top once, carrying the chain length. Which module walked a hierarchy whose depth comes from the input, and why did it avoid recursion?

Strong answer
// Practice 1: managerOf[i] is the manager of employee i, or -1 if i has no manager. Nobody manages
// themselves, directly or through others. Returns the most people in one chain of command, from
// someone with no manager down to one of their reports' reports, and so on (one person alone is a
// chain of 1). Up to 200,000 employees, and a manager's number can be larger than their report's.
// Pattern: a tree walk with an explicit stack (Module 6). Build each manager's list of reports
// once, then walk down from everyone with no manager, carrying the chain length.
// O(n) time: each employee is pushed and popped once. O(n) memory for the lists and the stack.
export function longestChain(managerOf: number[]): number {
  const reports: number[][] = Array.from({ length: managerOf.length }, () => []);
  const stack: [number, number][] = []; // [employee, people in the chain from the top to them]
  for (let e = 0; e < managerOf.length; e++) {
    if (managerOf[e] === -1) stack.push([e, 1]);
    else reports[managerOf[e]].push(e);
  }
  let most = 0;
  while (stack.length > 0) {
    const [e, length] = stack.pop()!;
    if (length > most) most = length;
    for (const r of reports[e]) stack.push([r, length + 1]);
  }
  return most;
}

Pattern: a depth-first walk with an explicit stack (Module 6), after grouping the reports by manager. That’s Module 3’s grouping, with an array per manager because the keys are 0 to n − 1.

Cost: each employee is pushed and popped once, so O(n) time. The lists and the stack are O(n) memory.

Reasoning: the slow answer in slow/longest-chain.ts walks up from everyone. That’s O(n · h) for chains h people long, and O(n²) on one chain. It took 2,221 ms on the last test. A recursive walk down throws a RangeError on that chain, because Module 6 found that recursion stops after about 5,000 to 12,000 levels.

Practice 2: services that can’t reach the database (easy)

Services call each other. Each call [from, to] means from calls to, and calls can form loops. Write cutOff(services, calls, target): the services that can’t reach target through any chain of calls, in the order of services. Start from exercises/cut-off.ts:

// Practice 2: services lists every service once, target among them. Each call [from, to] means
// `from` calls `to`; calls can form loops. Returns the services that can't reach target through
// any chain of calls, in the order of `services`. Up to 100,000 services and 300,000 calls.
export function cutOff(services: string[], calls: [string, string][], target: string): string[] {
  throw new Error("not implemented");
}

In a small system where web calls api, api calls billing and billing calls db, all three reach db. The last test is 5,000 services and 15,000 calls, in under 100 ms.

Hint 1

There can be 100,000 services and 300,000 calls. A walk from each service, stopping when it reaches the target, is correct. How many steps is that in the worst case, and what does Figure 2 allow?

Hint 2

Every walk that reaches the target goes over the same calls near the target. Ask the question the other way: if you turn every call around, which services can the target reach? Module 7 built a turned-around list for Kahn’s algorithm.

Strong answer
// Practice 2: services lists every service once, target among them. Each call [from, to] means
// `from` calls `to`; calls can form loops. Returns the services that can't reach target through
// any chain of calls, in the order of `services`. Up to 100,000 services and 300,000 calls.
// Pattern: one graph walk with a visited set (Module 7), on the calls turned around. A service
// reaches target exactly when target reaches it backward, so one walk from target answers for all.
// O(V + E) time and memory.
export function cutOff(services: string[], calls: [string, string][], target: string): string[] {
  const callers = new Map<string, string[]>(); // to -> every from that calls it
  for (const [from, to] of calls) callers.getOrInsertComputed(to, () => []).push(from);
  const reaches = new Set<string>([target]);
  const stack = [target];
  while (stack.length > 0) {
    for (const from of callers.get(stack.pop()!) ?? []) {
      if (!reaches.has(from)) {
        reaches.add(from); // mark when pushed, so no service is pushed twice
        stack.push(from);
      }
    }
  }
  return services.filter((s) => !reaches.has(s));
}

Pattern: a graph walk with a visited set (Module 7), on the calls turned around. The turned-around lists are a Map from each service to its callers, built with getOrInsertComputed (Module 3).

Cost: each service is pushed at most once and each call is read once. So it’s O(V + E) time and memory for V services and E calls.

Reasoning: a service reaches the target exactly when the target reaches it backward, so one walk answers for every service. The slow answer in slow/cut-off.ts walks forward from each service with its own visited set. That’s O(V · (V + E)), and it took 2,971 ms on the last test. The visited set also stops the walk on a loop, and without it the “loops” test never ends.

Practice 3: when the last job finishes (medium)

A build system has a fixed number of runners. Jobs start in list order, each the moment a runner is free, on the runner that is free first. Write lastFinish(durations, runners): the time the last job finishes. Start from exercises/last-finish.ts:

// Practice 3: durations[i] is how many seconds job i runs. There are `runners` runners, all free at
// time 0 (runners >= 1). Jobs start in list order, each the moment a runner is free, on the runner
// that is free first. Returns the time the last job finishes (0 for no jobs).
// Up to 200,000 jobs and 10,000 runners. You may import Module 8's heap:
// import { Heap } from "../../module-08/heap.ts";
export function lastFinish(durations: number[], runners: number): number {
  throw new Error("not implemented");
}

Jobs of 5, 2 and 4 seconds on two runners finish at 6: the third job waits for the runner that finished at 2. The last test is 200,000 jobs on 10,000 runners, in under 100 ms.

Hint 1

For each job, scanning all the runners for the one free first is correct. With 200,000 jobs and 10,000 runners, how many steps is that? What would a cost of O(n log k) for k runners come to?

Hint 2

Every job asks the same question, “which runner is free first?”, and each answer changes only one runner’s free time. Which structure hands back the smallest item again and again while the items keep changing? Also check which job finishes last: is it always the last one to start?

Strong answer
// Practice 3: durations[i] is how many seconds job i runs. There are `runners` runners, all free at
// time 0 (runners >= 1). Jobs start in list order, each the moment a runner is free, on the runner
// that is free first. Returns the time the last job finishes (0 for no jobs).
// Up to 200,000 jobs and 10,000 runners. You may import Module 8's heap:
// import { Heap } from "../../module-08/heap.ts";
// Pattern: a min-heap (Module 8) of the times the runners are free. Each job takes the top, the
// runner free first, and puts it back with its new free time. O(k + n log k) time for k runners
// (the build is O(k)), O(k) memory.
import { Heap } from "../../module-08/heap.ts";

export function lastFinish(durations: number[], runners: number): number {
  const freeAt = new Heap<number>((a, b) => a < b, new Array<number>(runners).fill(0));
  let last = 0;
  for (const d of durations) {
    const end = freeAt.peek()! + d;
    freeAt.replaceTop(end); // the runner free first takes the job
    if (end > last) last = end;
  }
  return last;
}

Pattern: a min-heap (Module 8) of the times when the runners are free. It’s built bottom-up from k zeros, and each job reads the top and replaces it with its own end time.

Cost: the build is O(k), and each job does one replaceTop, O(log k). So it’s O(k + n log k) time and O(k) memory.

Reasoning: the slow answer in slow/last-finish.ts scans every runner for every job, O(n · k), and took 7,597 ms on the last test. The answer is the largest end time, not the top of the heap at the end. The top is the runner that’s free first, which is why the lab’s tests include one long first job.

Practice 4: replicas as far apart as possible (medium)

A row of racks has free slots at whole-number positions. Put k replicas in k of the slots, so that the smallest distance between two replicas is as large as possible. Write widestSpacing(slots, k): that distance. Start from exercises/widest-spacing.ts:

// Practice 4: slots holds the positions of the free slots along one row of racks: distinct whole
// numbers from 0 to 10^9, in any order. Put k replicas in k different slots so that the smallest
// distance between two replicas is as large as possible, and return that distance.
// 2 <= k <= slots.length <= 100,000.
export function widestSpacing(slots: number[], k: number): number {
  throw new Error("not implemented");
}

For slots at 1, 2, 4, 8 and 9, three replicas fit 3 apart (at 1, 4 and 8), but not 4 apart. The last test is 50,000 slots and 20 replicas, in under 100 ms.

Hint 1

Trying the distances 1, 2, 3 and so on until one doesn’t fit is correct, but the answer can be as large as 10⁹. Can you answer “do k replicas fit at least d apart?” for one d in O(n), once the slots are sorted?

Hint 2

If k replicas fit d apart, they also fit any smaller distance apart. Which pattern searches for “the largest x such that”, with a yes-or-no check that flips once? For the check, put the first replica in the first slot and each next one in the first slot at least d further on.

Strong answer
// Practice 4: slots holds the positions of the free slots along one row of racks: distinct whole
// numbers from 0 to 10^9, in any order. Put k replicas in k different slots so that the smallest
// distance between two replicas is as large as possible, and return that distance.
// 2 <= k <= slots.length <= 100,000.
// Pattern: binary search on the answer (Module 9). fits(d) asks "can k replicas sit at least d
// apart?" and answers it greedily: take the first slot, then each slot at least d past the last
// one taken. A d that fits makes every smaller d fit, so search for the smallest d that does not
// fit; the answer is one less. O(n log n) for the sort, plus O(n) per check and O(log R) checks
// for R = the distance from the first slot to the last: O(n log n + n log R) time, O(n) memory.
export function widestSpacing(slots: number[], k: number): number {
  const sorted = slots.toSorted((a, b) => a - b);
  const fits = (d: number): boolean => {
    let placed = 1;
    let last = sorted[0];
    for (const s of sorted) {
      if (s - last >= d) {
        placed++;
        last = s;
        if (placed === k) return true;
      }
    }
    return false;
  };
  let lo = 1; // 1 always fits: the slots are distinct whole numbers
  let hi = sorted[sorted.length - 1] - sorted[0] + 1; // never fits: wider than the whole row
  while (lo < hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (fits(mid)) lo = mid + 1;
    else hi = mid; // mid doesn't fit: the first d that doesn't is mid or smaller
  }
  return lo - 1;
}

Pattern: binary search on the answer (Module 9), with a greedy check. The code searches for the smallest d that doesn’t fit, in Module 9’s shape, and returns one less.

Cost: O(n log n) for the sort. Then each check is O(n), and there are O(log R) checks for R, the distance from the first slot to the last. So it’s O(n log n + n log R) time and O(n) memory for the sorted copy.

Reasoning: the greedy check is safe by an exchange argument. Compare it with any placement that fits.

The greedy’s first replica is in the first slot, so it’s no later than the placement’s first. Suppose the greedy’s i-th replica is no later than the placement’s i-th. Then the placement’s next replica is a slot at least d past the greedy’s, so the greedy’s next one is no later either. So the greedy never runs out of slots before k.

The slow answer in slow/widest-spacing.ts tries every d from 1 up, with the same check. That’s O(n · answer), and it took 702 ms on the last test, where the answer is 18,417.

Practice 5: the largest block of free CPU time (harder)

freeCores[h] is the number of free CPU cores in hour h. A job takes the same c cores for a run of consecutive hours, so every hour of the run needs at least c free cores. Write largestBlock(freeCores): the largest cores × hours that one job can get. Start from exercises/largest-block.ts:

// Practice 5: freeCores[h] is how many CPU cores are free in hour h (a whole number from 0 to
// 10,000). A job takes the same c cores for a run of consecutive hours, so every hour of the run
// needs at least c free cores. Returns the largest c * hours one job can get. Up to 200,000 hours.
export function largestBlock(freeCores: number[]): number {
  throw new Error("not implemented");
}

For [2, 1, 5, 6, 2, 3] the answer is 10: 5 cores in hours 2 and 3. The last test is 40,000 hours that rise and then fall, in under 100 ms.

Hint 1

Every run of hours, with the fewest cores in it, is correct and O(n²). With 200,000 hours, how many steps is that? Figure 2 says the target is O(n) or O(n log n).

Hint 2

The best job uses every core of the hour with the fewest cores in its run. So for each hour h, the best job limited by h stretches left and right until it meets an hour with fewer cores. That’s “the previous smaller” and “the next smaller” for every item. Which module found the next larger item for every item in one pass?

Strong answer
// Practice 5: freeCores[h] is how many CPU cores are free in hour h (a whole number from 0 to
// 10,000). A job takes the same c cores for a run of consecutive hours, so every hour of the run
// needs at least c free cores. Returns the largest c * hours one job can get. Up to 200,000 hours.
// Pattern: a monotonic stack (Module 5). The best job limited by hour h runs from just after the
// previous hour with fewer cores to just before the next hour with fewer. The stack holds hours
// whose run hasn't ended, with cores rising from bottom to top. An hour pops every hour with at
// least as many cores, which ends their runs; the hour left below a popped one has fewer cores, so
// the run starts just after it. (Of two equal hours, the first one's run is cut short, but the
// second one's run covers it.) O(n) time: each hour is pushed once and popped once. O(n) memory.
export function largestBlock(freeCores: number[]): number {
  const n = freeCores.length;
  const waiting: number[] = [];
  let best = 0;
  for (let h = 0; h <= n; h++) {
    const cores = h < n ? freeCores[h] : -1; // a last hour with fewer cores than any, to empty the stack
    while (waiting.length > 0 && freeCores[waiting.at(-1)!] >= cores) {
      const limit = freeCores[waiting.pop()!];
      const from = waiting.length > 0 ? waiting.at(-1)! + 1 : 0; // the run starts after the hour below
      best = Math.max(best, limit * (h - from));
    }
    waiting.push(h);
  }
  return best;
}

Pattern: a monotonic stack (Module 5), with the comparison flipped for smaller values. The hour that pops an hour is the next one with the same or fewer cores. The hour left below it in the stack is the previous one with fewer. A last hour with −1 cores empties the stack.

Cost: each hour is pushed once and popped once, so O(n) time and O(n) memory.

Reasoning: the slow answer in slow/largest-block.ts tries every run, O(n²), and took 1,002 ms on the last test. When two hours have the same cores, the first one’s run is cut short at the second. That’s fine, because the second one’s run covers the whole stretch, and the lab’s tests with equal hours check it.

Practice 6: a log line without spaces (harder)

A log line lost its spaces, and you have the list of known command words. Write canSplit(line, words): whether the line can be cut into a sequence of known words, each usable any number of times. Start from exercises/can-split.ts:

// Practice 6: a log line lost its spaces. Returns true if line can be cut into a sequence of known
// words (each word can be used any number of times). Words are 1 to 20 characters long, and an
// empty line is a sequence of no words. Lines up to 100,000 characters, up to 1,000 words.
export function canSplit(line: string, words: string[]): boolean {
  throw new Error("not implemented");
}

Take the words git, push, pull, origin, main, pu and shor. The line gitpushoriginmain splits. So does pushorigin, as push + origin, though pu + shor also fits at the start and then fails. The last test is 28 copies of “a” and then a “b”, with the words a, aa and aaa, in under 100 ms.

Hint 1

Trying every word at the start and then cutting the rest is backtracking (Module 10), and it’s correct. How many ways are there to cut 28 copies of “a” into a, aa and aaa? A line can have 100,000 characters.

Hint 2

Whether the rest of the line, from position i, can be cut doesn’t depend on how you cut the part before i. So the state is one position, and there are n + 1 of them. Which module stores each state’s answer once? Why must the table be filled from the bottom up here?

Strong answer
// Practice 6: a log line lost its spaces. Returns true if line can be cut into a sequence of known
// words (each word can be used any number of times). Words are 1 to 20 characters long, and an
// empty line is a sequence of no words. Lines up to 100,000 characters, up to 1,000 words.
// Pattern: dynamic programming (Module 11) with a Set (Module 3). The state is a position: ok[i]
// says whether the first i characters can be cut into words. ok[i] is true when some word ends at
// i and ok is true where that word starts. Filled from i = 1 up, with no recursion, so a long
// line can't overflow the call stack. O(n * L) Set lookups for words up to L characters, each
// O(L) to cut and hash the piece: O(n * L^2) time, O(n) memory for ok plus the Set of words.
export function canSplit(line: string, words: string[]): boolean {
  const known = new Set(words);
  const longest = Math.max(0, ...words.map((w) => w.length));
  const ok = new Uint8Array(line.length + 1);
  ok[0] = 1; // the empty start
  for (let i = 1; i <= line.length; i++) {
    for (let len = 1; len <= Math.min(longest, i); len++) {
      if (ok[i - len] === 1 && known.has(line.slice(i - len, i))) {
        ok[i] = 1;
        break;
      }
    }
  }
  return ok[line.length] === 1;
}

Pattern: dynamic programming (Module 11) over positions, with the words in a Set (Module 3). ok[i] is true when the first i characters can be cut into words, filled from i = 1 up.

Cost: each of the n positions tries up to L word lengths, for the longest word L. Each try cuts a piece of up to L characters and hashes it. So it’s O(n · L²) time and O(n) memory, plus the Set.

Reasoning: the slow answer in slow/can-split.ts backtracks. On the last test it tries every way to cut the a’s before it meets the b, and it took 1,103 ms. It also throws a RangeError on the 100,000-character line, and so would a top-down memo, because the recursion is as deep as the number of words.

A trie of the words (the tour above) can replace the Set. Walk it from each position where ok is true, one character at a time, and you cut no substrings, so it’s O(n · L) time.

Get feedback on your own answer

Once your answer passes its tests, you can ask an AI assistant to review the choice of pattern, not the code style. Paste this, with the parts in angle brackets filled in:

Here is a problem, its input limits, and my TypeScript solution.
Don't rewrite my solution. Tell me:
1. Which pattern my solution uses, and whether another pattern fits
   the limits better.
2. Its time and memory cost in Big O, and whether that fits the limits
   at about 10^8 simple steps per second.
3. One input that would make it wrong or slow: an edge case or a worst
   case.
4. One change a reviewer would ask for, and why.

Problem: <the problem statement>
Limits: <the largest input sizes and value ranges>
My solution: <your code>

An assistant can be wrong about a cost, too. Check what it says with the tests, and with bench.ts at two or three sizes, before you trust it.

Using the method in a coding interview

Some coding interviews ask you to solve a problem like the practice problems while someone watches. The method fits that setting, because each step is something you can say out loud.

  • Restate and ask. Say the problem back in your own words. Ask for the input limits and what an empty or odd input should return.
  • Say the slow solution and its cost first. For example: “Every start with every end is O(n²), or 10¹² steps for a million minutes.”
  • Name the repeated work, then the pattern. “Each start re-adds the minutes the last start added, so a window that keeps the sum removes that work.”
  • State the cost of what you write, in time and memory, with one line on why.
  • Test out loud. Walk a small example through your code, then the edge cases: empty, one item, equal items, the largest input.

We can’t say how any interviewer scores this. What the method changes is that your reasoning is visible even before your code works.

Going deeper

You can skip this section. It holds the measurements and details that the main path left out.

How many steps fit in a second on Node.js 26

Module 1 measured a plain loop at about 1 ns per step. It chose 10⁸ steps per second because real steps do more than add. ops-per-second.ts checks that budget against six kinds of steps:

// How many steps of each kind this machine does in a second, best of 5 runs: node ops-per-second.ts
// Every step feeds a result the program prints, so the compiler can't remove it.
let sink = 0;

function rate(label: string, steps: number, fn: (steps: number) => number): void {
  let best = Infinity;
  for (let run = 0; run < 5; run++) {
    const start = performance.now();
    sink += fn(steps);
    best = Math.min(best, performance.now() - start);
  }
  console.log(`${label.padEnd(36)}${best.toFixed(1).padStart(8)} ms  ${(steps / (best / 1000)).toExponential(1)} steps/s`);
}

const N = 100_000_000;
const arr = Array.from({ length: 1_000_000 }, (_, i) => i);
const big = new Map(arr.map((i) => [i, i]));
const small = new Map(arr.slice(0, 1_000).map((i) => [i, i]));

rate("add to a sum", N, (n) => {
  let s = 0;
  for (let i = 0; i < n; i++) s += i;
  return s;
});
rate("read an array of 1,000,000", N, (n) => {
  let s = 0;
  for (let i = 0; i < n; i++) s += arr[i % 1_000_000];
  return s;
});
rate("Map.get, 1,000 keys", N / 10, (n) => {
  let s = 0;
  for (let i = 0; i < n; i++) s += small.get(i % 1_000)!;
  return s;
});
rate("Map.get, 1,000,000 keys", N / 10, (n) => {
  let s = 0;
  for (let i = 0; i < n; i++) s += big.get(i % 1_000_000)!;
  return s;
});
rate("Set.add, growing to 1,000,000 keys", N / 100, (n) => {
  const set = new Set<number>();
  for (let i = 0; i < n; i++) set.add(i);
  return set.size;
});
rate("make a small object and keep it", N / 100, (n) => {
  const kept: { x: number }[] = [];
  for (let i = 0; i < n; i++) kept.push({ x: i });
  return kept.length;
});
console.log(sink > 0 ? "" : sink);

node ops-per-second.ts printed:

add to a sum                           160.6 ms  6.2e+8 steps/s
read an array of 1,000,000             379.1 ms  2.6e+8 steps/s
Map.get, 1,000 keys                    134.5 ms  7.4e+7 steps/s
Map.get, 1,000,000 keys                670.2 ms  1.5e+7 steps/s
Set.add, growing to 1,000,000 keys     134.5 ms  7.4e+6 steps/s
make a small object and keep it         12.7 ms  7.9e+7 steps/s

Three runs of this file moved by up to a third, and the order of the rates stayed the same. A step that hashes into a large Map or grows a Set ran at 7.4 × 10⁶ to 1.5 × 10⁷ per second. That’s where “count it as about 10 simple steps” comes from.

Each step in the file feeds a sum that the program uses. The compiler can remove a loop whose result is never used, and then the loop measures nothing.

More on tries

The URL paths share long prefixes, so they need fewer nodes per character than random words.

A sorted array with Module 9‘s two bounds is the middle choice between a Set and a trie. The words with a prefix sit next to each other in sorted order. So two binary searches count them in O(P log n), with one slot per word. We didn’t measure it here.

The name comes from “retrieval”. The NIST Dictionary of Algorithms and Data Structures lists papers by de la Briandais (1959) and Edward Fredkin (1960). It also prints a 2008 note in which Fredkin says he named the structure and meant it to be said “tree”. Many people say “try”, to tell it apart from a general tree.

How a Number becomes 32 bits

JavaScript’s bitwise operators don’t work on the Number as it is stored. The spec’s NumberBitwiseOp (section 6.1.6.1.16, used by &, | and ^) first converts each side with ToInt32. ToInt32 (7.1.8) drops any fraction and keeps the low 32 bits, which gives a whole number from −2³¹ to 2³¹ − 1.

Those 32 bits are read in two’s complement: the sign bit counts as −2³¹ instead of +2³¹. >>> reads its left side with ToUint32 instead (Number::unsignedRightShift, 6.1.6.1.11), where the top bit counts as +2³¹. Figure 6 shows the 32 bits behind some lines of bits.ts, as trace-demo.ts prints them.

1 << 30         01000000 00000000 00000000 00000000   1073741824
1 << 31         10000000 00000000 00000000 00000000   -2147483648
(1 << 31) >>> 0 10000000 00000000 00000000 00000000   2147483648
-1              11111111 11111111 11111111 11111111   -1
-1 >>> 1        01111111 11111111 11111111 11111111   2147483647

Figure 6: the same 32 bits are −2,147,483,648 through ToInt32 and 2,147,483,648 through ToUint32, so the conversion an operator applies decides the sign.

So x >>> 0 shows the same bits as an unsigned number. >> copies the sign bit into the bits it frees (Number::signedRightShift, 6.1.6.1.10), and >>> fills them with 0. A shift takes its count modulo 32 (Number::leftShift, 6.1.6.1.9).

| 0 keeps the low 32 bits, so it cuts a fraction toward zero: 3.9 | 0 is 3 and -3.9 | 0 is −3. It also turns Number.MAX_SAFE_INTEGER, whose low 32 bits are all 1, into −1. The precedence mistake comes from the grammar, where & combines whole equality expressions (section 13.12).

BigInt masks

A BigInt has no 32-bit limit, so 1n << 40n and 64-bit masks work. But BigInt has no >>>, because BigInt::unsignedRightShift (6.1.6.2.11) only throws a TypeError. BigInt.asUintN(64, x) keeps the low 64 bits when you need a fixed width. bits.ts in the lab prints each of these.

A whole table row in one BigInt (stretch)

A bitmask can also hold a row of a dynamic programming table. Problem C’s row of reachable totals is one BigInt, reach, where bit t is 1 when some group adds up to t. Adding a cost c is reach |= reach << BigInt(c), one shift and one OR for the whole row. bitset-bench.ts times it against hasGroupWithTotal, with even costs and an odd total so that both fill their whole row:

hasGroupBits and hasGroupWithTotal agree on 500 random lists: true

array of booleans
             n   median ms   x prev
           200        1.95
           400        7.66      3.9
           800       30.75      4.0

BigInt bitset
             n   median ms   x prev
           200        0.07
           400        0.28      3.8
           800        0.94      3.3

Both are O(n · T), and the total grows with n here, so both grew 3.3 to 4.0 times per doubling. The bitset was 27 to 33 times faster. We measured that, but we didn’t look at how V8 stores a BigInt to explain it.

Cheat sheet

Figure 7 is the summary of the course: read the signs from the top, and try the first branch that matches.

read n and the limits -> target cost (Figure 2)
|
+-- "list every", "all the ways", n <= 25 .......... backtracking (10)
+-- "how many ways", "fewest", "most" over choices
|   that repeat under many branches ............... dynamic programming (11)
+-- sorted data, or "smallest x such that" ......... binary search (9)
+-- a rule that picks one item, proved safe ........ greedy (9)
+-- "top k", "the smallest next", again ............ heap (8)
+-- links, dependencies, grids, "fewest steps" ..... graph walk (7)
+-- a hierarchy whose depth comes from input ....... tree walk (6)
+-- nesting, "next larger", first in first out ..... stack, queue (5)
+-- items you hold and move often, "LRU" ........... linked list (4)
+-- "seen before?", counts, groups, partners ....... Set, Map (3)
`-- runs, ranges, pairs in sorted data ............. window, pointers,
                                                     prefix sums (2)

Figure 7: each branch is a sign from the table of signs, and Figure 2 then says whether the pattern it points to is fast enough.

  • Method: restate, read the limit, write the slow solution, find the repeated work, pick the pattern, test the edge cases.
  • Repeated work: the pattern is whatever removes the work the slow solution does more than once.
  • Budget: about 10⁸ simple steps per second (Module 1); count a step that hashes into a large Map as about 10.
  • Limits: n ≈ 10 allows O(n!), 25 O(2ⁿ), 10,000 O(n²), 4.5 million O(n log n), 10⁸ O(n).
  • Conditions: a window needs positive values; a greedy rule needs a brute-force check; a table over values costs O(n · T).
  • Trie: O(L) per word or prefix, but 24 times the memory of a Set; worth it only for many prefix questions.
  • Bits: a mask of n bits holds a subset; bitwise operators work on 32 bits, so Number masks are safe up to n = 30.
  • Check: compare the fast answer with the slow one on small random inputs, then time the largest input.

To keep practicing, take a slow function from your own code, read its real input limit, and find the work it repeats.

Sources