The puzzle
The input lists one ID per container. Containers that hold the same kind of supply share an ID, so its frequency tells you how many of those containers are available.
- Part 1 asks for the product of the three distinct IDs that appear most often.
- Part 2 asks for the product of the three distinct IDs that appear least often among those listed.
Start with a map and a sort
I started with a map from ID to count. Then I sorted the entries by count, took three from each end, and multiplied the corresponding IDs. That gave me a reference implementation for both parts.
- Baseline
- 0.0825ms
Baseline JavaScript
function sortFrequencies(input) {
const counts = new Map();
for (const line of input.trim().split(/\r\n?|\n/)) {
const id = Number(line);
counts.set(id, (counts.get(id) ?? 0) + 1);
}
const sorted = [...counts].sort((a, b) => b[1] - a[1]);
const product = (slots) => slots.reduce((value, [id]) => value * BigInt(id), 1n);
return [product(sorted.slice(0, 3)), product(sorted.slice(-3))];
}ID 12 appears six times in the example inventory. ID 7 appears five times, and ID 34 appears four times. Those are the three longest bars, so their IDs are the three factors in Part 1.
The bars form a histogram. Each input line adds one to the counter for its ID. Let be the ID on line i. The formula below counts how many lines match ID v. Once a line has been counted, its position can be discarded.
Replace the sort with four slots at each end
The sort spends time ranking IDs in the middle of the histogram. I only needed the leading three candidates at each end and the next one, which tells me whether third place is tied. Visit each count once and keep the best four seen so far. When a new entry pushes a fifth out, four entries already rank ahead of it.
A comparison sort can take comparisons for k distinct IDs. General order-statistic selection also admits linear comparisons even when the desired rank varies. Here the rank is fixed, so an insertion into at most four slots is sufficient. Blum, Floyd, Pratt, Rivest and Tarjan, Time Bounds for Selection.
For Part 1, the rank passed to the buffer is the count. The buffer needs room for just four pairs.
function keepFour(slots, id, rank) {
let index = 0;
while (index < slots.length && slots[index][1] >= rank) index++;
if (index === 4) return;
slots.splice(index, 0, [id, rank]);
if (slots.length > 4) slots.pop();
}| Step | 1st | 2nd | 3rd | 4th |
|---|---|---|---|---|
| Before | 12 (6) | 34 (4) | 5 (3) | 26 (2) |
| Insert 7 (5) | 12 (6) | 7 (5) | 34 (4) | 5 (3) |
Count while parsing
I paired the four-slot buffers with a cheaper way to fill the histogram. For IDs from 0 through 9,999, a 40 KB typed array puts each counter at the ID’s index. As each decimal character arrives, update the in-progress ID by multiplying by ten and adding the digit. The newline commits the ID to its slot. A sentinel newline also commits the final ID when the input has no trailing newline.
This fast path avoids a temporary string per line and a hash lookup per ID. A wider range or a line that needs whitespace normalization takes the exact-integer map path. When there are few keys in a large universe, hashing avoids allocating a counter for every possible ID. Pat Morin, Open Data Structures, chapter 5.
The parser below uses character codes 48–57 for decimal digits and 10 and 13 for line endings. At the end of the string it supplies the sentinel without extending the input.
for (let i = 0; i <= text.length; i++) {
const char = i === text.length ? 10 : text.charCodeAt(i);
if (char >= 48 && char <= 57) {
id = id * 10 + char - 48;
if (id >= DENSE_SIZE) return sparseCounts(text);
hasDigits = true;
} else if (hasDigits && (char === 10 || char === 13)) {
counts[id]++;
hasDigits = false;
id = 0;
if (char === 13 && text.charCodeAt(i + 1) === 10) i++;
} else {
return sparseCounts(text);
}
}
With B input characters and a dense table of size U, parsing and counting cost O(B). The scan of the counter table costs O(U) and the table occupies 4U bytes. In a parallel version, workers could add their histograms component by component before ranking. Merging local winners alone loses information. An ID just below fourth place in every shard could have the largest global count.
Apply the same buffer to Part 2
Select Least common on the same histogram. The three shortest bars belong to IDs 91, 26, and 5, with product 11,830. The solver passes each count to the four-slot buffer with its sign flipped, so the shortest bars rank first. It considers only IDs that appear in the input.
Let H be the three IDs selected at the high end and L the three at the low end. Both answers multiply the IDs themselves.
The fourth entry checks the boundary of each group. With at least four distinct IDs, the third and fourth candidates at each end must have different counts for the three IDs to be uniquely specified. In a list of k counts in descending order, check both boundaries as follows.
Ties inside a selected group leave its product unchanged. The solver flags a tie that spans the cutoff because different IDs could be selected. If there are exactly three distinct IDs, both parts multiply all three.
- Before
- 0.0825ms
- After
- 0.0387ms
- Speedup
- 2.13×
Delay the BigInt conversion
The first histogram version converted every occupied ID to BigInt before ranking. The buffers compare frequencies, so those IDs can stay as numbers until the multiplication. I moved the conversion to the three factors of each answer. The sparse path still parses large IDs as exact integers so distinct IDs cannot round to the same key.
- Before
- 0.0387ms
- After
- 0.0322ms
- Speedup
- 1.20×
Read one whole record at a time
Bob’s input had three digits on every line. With one newline between records, I could step four characters at a time, unroll the decimal recurrence into 100a + 10b + c, and update a 4 KB histogram. The ranking pass scans a tenth as many slots. Each record still gets its digits and separator checked. Other widths and line endings go through the general parser.
for (let i = 0; i <= last; i += 4) {
const hundreds = text.charCodeAt(i) - 48;
const tens = text.charCodeAt(i + 1) - 48;
const ones = text.charCodeAt(i + 2) - 48;
if ((hundreds >>> 0) > 9 || (tens >>> 0) > 9 || (ones >>> 0) > 9 ||
(i < last && text.charCodeAt(i + 3) !== 10)) return null;
counts[100 * hundreds + 10 * tens + ones]++;
}- Before
- 0.0322ms
- After
- 0.0184ms
- Speedup
- 1.75×
Move the fixed-width parser into Rust
The three-digit fast path is a good fit for WebAssembly. It reads one contiguous byte buffer and writes a small histogram in linear memory. Each run crosses into Wasm once to reserve the input buffer and once to solve both parts. The browser encodes the text directly into that buffer and reads two 64-bit integers back. The worker keeps the allocation for another run.
I tried reading a whole record as a little-endian word. Each digit’s top four bits must equal 0x3, and the fourth byte must be a newline. After masking off the top bits, add six in each byte lane. Bit four is set exactly when the digit is ten or more. The largest lane sum is 21, so there is no carry into the next byte.
if record & 0xfff0_f0f0 != 0x0a30_3030 {
return None;
}
let digits = record & 0x000f_0f0f;
if (digits + 0x0006_0606) & 0x0010_1010 != 0 {
return None;
}
let id = 100 * (digits & 15) + 10 * ((digits >> 8) & 15) + (digits >> 16);
On the same generated 180,300 records in Chromium, that change took 0.534 ms against 0.478 ms for checking the three bytes directly. I kept the byte parser.
The general Rust parser handles ordinary decimal IDs through 9,999. Larger IDs and ambiguous rankings go back through the JavaScript reference, which can handle arbitrarily large factors and report exactly where parsing or ranking fails.
- Before
- 0.0236ms
- After
- 0.00659ms
- Speedup
- 3.59×
Benchmarks
| Workload | Optimized JavaScript | Rust/Wasm |
|---|---|---|
| Bob’s input, fresh worker | 7.6 ms | 7.9 ms |
| Bob’s input, warm solve | 0.0236 ms | 0.00659 ms |
| 180,300 shuffled three-digit IDs, warm solve | 0.809 ms | 0.525 ms |
The warm path saves about 17 microseconds on the puzzle input. The trip through a fresh worker on localhost takes several milliseconds, so worker startup and module loading dominate this short workload.
The browser comparisons use Chromium 147 on a Threadripper 9970X, with Rust 1.100.0 targeting wasm32-unknown-unknown. Each figure is the median of nine measurements. Warm measurements batch complete solves, including input encoding when needed. Fresh measurements include creating a worker, loading the solver on localhost, and receiving both answers. The earlier JavaScript milestones used Bun v1.4.5.
- Start
- 0.1125ms
- Finish
- 0.00659ms
- Speedup
- 17.1×
Run the solver
Paste one nonnegative integer ID per line. Your input stays in this browser.