Twelve Days · day 1 · both parts
Day 1: Dusty Shed
Day 1 is a warm-up: count some numbers, pick three, multiply (and in part 2, pick the other three). The answer fits on one line, so this post takes the long way round. It starts with the version a beginner would write and hands one piece at a time to Python’s standard library, then looks at what each of those pieces does inside CPython and measures it. Why this series works this way is on the calendar page.
The puzzle, in my words
The input is a list of ID numbers, one per line. Part 1: find the three IDs that appear most often and multiply them together. In the example, 57 appears six times, 43 five times and 76 four times, so the answer is 57 × 43 × 76 = 186276.
Part 2: the same for the three that appear least often: 55 (once), 45 (twice) and 78 (three times), 55 × 45 × 78 = 193050.
Throughout, n is the number of IDs in the input and k the number of distinct IDs.
Solutions
The same two answers in every language I could get my hands on. Each one starts from what a beginner in that language would write and moves step by step to what an experienced programmer would write, with notes on what each tool does inside that language’s runtime.
Python
Six steps from a beginner’s version to the idiomatic one, then part 2. The framed notes say what each tool does inside CPython 3.15; the longer stories are in the linked articles.
Part 1: the three most common
Step 1: a beginner’s version
Split the input into words, count each ID in a dictionary, sort the
(id, count) pairs by count, and multiply the first three IDs.
def part1(text: str) -> int:
counts = {}
for word in text.split():
n = int(word)
if n in counts:
counts[n] += 1
else:
counts[n] = 1
items = sorted(counts.items(), key=lambda item: item[1], reverse=True)
result = 1
for n, count in items[:3]:
result *= n
return result
Nothing wrong with it. It’s just doing by hand a few things Python can do for us.
Step 2: smaller tools, same shape
Three small swaps:
counts.get(n, 0) + 1returns 0 for an ID we haven’t seen, so the if/else goes away.map(int, text.split())converts each word to a number as we loop, so the separateint(word)line goes too.- Sorting the dictionary’s keys with
key=counts.getsorts IDs by their count directly, without building pairs first.
def part1(text: str) -> int:
counts = {}
for n in map(int, text.split()):
counts[n] = counts.get(n, 0) + 1
top = sorted(counts, key=counts.get, reverse=True)[:3]
result = 1
for n in top:
result *= n
return result
Step 3: Counter
Counting things is common enough that the standard library has a class for
it. collections.Counter counts an iterable in one call, and its
most_common(3) gives the same three IDs as the sort and slice from step 2.
It returns (id, count) pairs, so we unpack and ignore the count.
from collections import Counter
def part1(text: str) -> int:
counts = Counter(map(int, text.split()))
result = 1
for n, _ in counts.most_common(3):
result *= n
return result
Step 4: the loop is a fold
“Start with one value and combine it with each next item” is a fold, and
functools.reduce is Python’s fold.
from collections import Counter
from functools import reduce
def part1(text: str) -> int:
counts = Counter(map(int, text.split()))
top = [n for n, _ in counts.most_common(3)]
return reduce(lambda x, y: x * y, top)
Step 5: that lambda already exists
lambda x, y: x * y is just multiplication as a function, and the operator
module has every operator in that form, so it becomes operator.mul.
from collections import Counter
from functools import reduce
from operator import mul
def part1(text: str) -> int:
counts = Counter(map(int, text.split()))
top = [n for n, _ in counts.most_common(3)]
return reduce(mul, top)
Step 6: so does the whole fold
reduce(mul, ...) has a name too: math.prod, in the standard library since
Python 3.8. With nothing left worth naming, it fits on one line.
from collections import Counter
from math import prod
def part1(text: str) -> int:
return prod(n for n, _ in Counter(map(int, text.split())).most_common(3))
Shorter, but is it better?
| step | what changed | lines | picking three |
|---|---|---|---|
| 1 | dict, sorted, loops | 12 | sort k: O(k log k) |
| 2 | dict.get, map(int, ...), key=counts.get | 8 | sort k: O(k log k) |
| 3 | Counter.most_common | 5 | heap of 3: O(k) |
| 4 | functools.reduce | 3 | heap of 3: O(k) |
| 5 | operator.mul | 3 | heap of 3: O(k) |
| 6 | math.prod | 1 | heap of 3: O(k) |
All six are O(n) for counting, which dominates. Each step is a smaller program, but step 6 isn’t automatically the best one. Steps 3 to 5 read like the puzzle itself: count, take the top three, multiply. The one-liner asks you to read it inside out. For a puzzle I’d keep the one-liner; in code someone else maintains I’d stop at step 3 or 5.
One thing none of the versions handle: a tie for third place. If two IDs share
the third-highest count, the “three most common” isn’t well defined, and both
sorted and most_common quietly keep whichever came first. The puzzle input
presumably avoids that.
Part 2: the other end
Part 2 wants the three least common IDs instead. The quickest change to
step 6 is to take the other end of most_common(). Called with no argument it
returns every ID, most common first, so the last three are the least common:
from collections import Counter
from math import prod
def part2(text: str) -> int:
return prod(n for n, _ in Counter(map(int, text.split())).most_common()[-3:])
It works, but it sorts every ID just to keep three, and you have to know the
order most_common() returns to read [-3:] correctly. The heapq module has
a function for exactly this question, and it keeps only three IDs as it goes:
from collections import Counter
from heapq import nsmallest
from math import prod
def part2(text: str) -> int:
counts = Counter(map(int, text.split()))
return prod(nsmallest(3, counts, key=counts.get))
nsmallest(3, counts, key=counts.get) reads as “the three IDs with the
smallest counts”. Its twin, heapq.nlargest, is exactly what
most_common(3) calls. There’s no least_common.
The tie caveat matters more here, and the two versions don’t agree on it.
Plenty of IDs could appear just once. If, say, four IDs appear once each,
most_common()[-3:] keeps the last three it met and nsmallest keeps the
first three: different IDs, different answers. The puzzle input has to avoid
that case for the question to have one answer.
C
C has no dictionary, no Counter, no sorted. Its standard library gives
you scanf to read numbers and qsort to sort an array, and that’s about it.
So the C version of this ladder is less about finding the right library call
and more about choosing the right data structure. Every program below reads
the input on stdin and prints one number; each file is complete, includes and
all, and compiles with cc -std=c17 -O2 -Wall -Wextra -Werror.
Part 1: the three most common
Step 1: a beginner’s version
Without a hash map, a beginner keeps two arrays side by side: the IDs seen so far and how many times each appeared. Every new number is looked up with a linear search. Then a bubble sort puts the highest counts first.
/* Step 1: what a beginner writes. Two parallel arrays (the IDs seen so far
* and how often), a linear search for each number, a bubble sort by count,
* and the first three IDs multiplied. */
#include <stdio.h>
#define MAX_IDS 100000
int ids[MAX_IDS];
int counts[MAX_IDS];
int main(void) {
int distinct = 0;
int n;
while (scanf("%d", &n) == 1) {
int found = 0;
for (int i = 0; i < distinct; i++) {
if (ids[i] == n) {
counts[i]++;
found = 1;
break;
}
}
if (!found) {
ids[distinct] = n;
counts[distinct] = 1;
distinct++;
}
}
/* bubble sort, highest count first */
for (int i = 0; i < distinct - 1; i++) {
for (int j = 0; j < distinct - 1 - i; j++) {
if (counts[j] < counts[j + 1]) {
int t = counts[j];
counts[j] = counts[j + 1];
counts[j + 1] = t;
t = ids[j];
ids[j] = ids[j + 1];
ids[j + 1] = t;
}
}
}
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= ids[i];
}
printf("%lld\n", result);
return 0;
}
Step 2: a struct and qsort
An ID and its count belong together, so they become a struct, and the bubble
sort is replaced by the C library’s qsort with a comparison function. The
comparison returns (y > x) - (y < x) rather than y - x, a common C idiom:
subtracting two ints can overflow, comparing them can’t.
/* Step 2: keep each ID and its count together in a struct, and let the C
* library sort: qsort with a comparison function. */
#include <stdio.h>
#include <stdlib.h>
#define MAX_IDS 100000
struct entry {
int id;
int count;
};
static struct entry entries[MAX_IDS];
static int by_count_desc(const void *a, const void *b) {
const struct entry *x = a, *y = b;
return (y->count > x->count) - (y->count < x->count);
}
int main(void) {
int distinct = 0;
int n;
while (scanf("%d", &n) == 1) {
int i = 0;
while (i < distinct && entries[i].id != n) {
i++;
}
if (i == distinct) {
entries[distinct++] = (struct entry){n, 0};
}
entries[i].count++;
}
qsort(entries, distinct, sizeof entries[0], by_count_desc);
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= entries[i].id;
}
printf("%lld\n", result);
return 0;
}
Step 3: a hash table
To make counting O(1) per ID we need a hash table, and C makes you write it. This one is about as small as a correct one gets: an array whose size is a power of two, Fibonacci hashing to pick a slot, linear probing to find the next free one, and doubling the array once it is three-quarters full.
/* Step 3: the linear search makes counting O(n * k). A hash table makes each
* lookup O(1) on average. C's standard library has none, so here is a small
* open-addressing one: a power-of-two array, a multiplicative hash, linear
* probing, and doubling when it gets 3/4 full. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct entry {
int id;
int count; /* 0 = empty slot */
};
struct table {
struct entry *slots;
size_t cap; /* a power of two: 2^bits */
unsigned bits;
size_t used;
};
static size_t slot_for(int id, unsigned bits) {
/* Fibonacci hashing: multiply by 2^64 / golden ratio and keep the top
* `bits` bits, which mixes all of the key's bits into the slot number */
return (size_t)(((uint64_t)(uint32_t)id * 0x9E3779B97F4A7C15ull) >> (64 - bits));
}
static void grow(struct table *t);
static void add(struct table *t, int id) {
size_t i = slot_for(id, t->bits);
while (t->slots[i].count && t->slots[i].id != id) {
i = (i + 1) & (t->cap - 1);
}
if (!t->slots[i].count) {
t->slots[i].id = id;
t->used++;
}
t->slots[i].count++;
if (t->used * 4 >= t->cap * 3) {
grow(t);
}
}
static void grow(struct table *t) {
struct table bigger = {calloc(t->cap * 2, sizeof *t->slots), t->cap * 2, t->bits + 1, 0};
if (!bigger.slots) {
perror("calloc");
exit(1);
}
for (size_t i = 0; i < t->cap; i++) {
if (t->slots[i].count) {
size_t j = slot_for(t->slots[i].id, bigger.bits);
while (bigger.slots[j].count) {
j = (j + 1) & (bigger.cap - 1);
}
bigger.slots[j] = t->slots[i];
bigger.used++;
}
}
free(t->slots);
*t = bigger;
}
static int by_count_desc(const void *a, const void *b) {
const struct entry *x = a, *y = b;
return (y->count > x->count) - (y->count < x->count);
}
int main(void) {
struct table t = {calloc(64, sizeof(struct entry)), 64, 6, 0};
if (!t.slots) {
perror("calloc");
return 1;
}
int n;
while (scanf("%d", &n) == 1) {
add(&t, n);
}
/* pack the occupied slots to the front, then sort them */
size_t k = 0;
for (size_t i = 0; i < t.cap; i++) {
if (t.slots[i].count) {
t.slots[k++] = t.slots[i];
}
}
qsort(t.slots, k, sizeof *t.slots, by_count_desc);
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= t.slots[i].id;
}
printf("%lld\n", result);
free(t.slots);
return 0;
}
Step 4: don’t sort what you won’t use
Sorting k entries to look at three of them is wasted work. One pass over the table, keeping the three largest counts seen so far, is O(k), and for most slots it is a single comparison with the current third place.
/* Step 4: sorting all k IDs to keep three is O(k log k). One pass over the
* table that keeps the best three seen so far is O(k): each slot is compared
* with the current third place, and only a winner moves anything. Same hash
* table as step 3. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct entry {
int id;
int count; /* 0 = empty slot */
};
struct table {
struct entry *slots;
size_t cap; /* a power of two: 2^bits */
unsigned bits;
size_t used;
};
static size_t slot_for(int id, unsigned bits) {
/* Fibonacci hashing: multiply by 2^64 / golden ratio and keep the top
* `bits` bits, which mixes all of the key's bits into the slot number */
return (size_t)(((uint64_t)(uint32_t)id * 0x9E3779B97F4A7C15ull) >> (64 - bits));
}
static void grow(struct table *t);
static void add(struct table *t, int id) {
size_t i = slot_for(id, t->bits);
while (t->slots[i].count && t->slots[i].id != id) {
i = (i + 1) & (t->cap - 1);
}
if (!t->slots[i].count) {
t->slots[i].id = id;
t->used++;
}
t->slots[i].count++;
if (t->used * 4 >= t->cap * 3) {
grow(t);
}
}
static void grow(struct table *t) {
struct table bigger = {calloc(t->cap * 2, sizeof *t->slots), t->cap * 2, t->bits + 1, 0};
if (!bigger.slots) {
perror("calloc");
exit(1);
}
for (size_t i = 0; i < t->cap; i++) {
if (t->slots[i].count) {
size_t j = slot_for(t->slots[i].id, bigger.bits);
while (bigger.slots[j].count) {
j = (j + 1) & (bigger.cap - 1);
}
bigger.slots[j] = t->slots[i];
bigger.used++;
}
}
free(t->slots);
*t = bigger;
}
int main(void) {
struct table t = {calloc(64, sizeof(struct entry)), 64, 6, 0};
if (!t.slots) {
perror("calloc");
return 1;
}
int n;
while (scanf("%d", &n) == 1) {
add(&t, n);
}
/* top[0] is the most common so far; a strict > keeps the first of a tie */
struct entry top[3] = {{0, 0}, {0, 0}, {0, 0}};
for (size_t i = 0; i < t.cap; i++) {
struct entry e = t.slots[i];
if (e.count > top[2].count) {
int j = 2;
while (j > 0 && e.count > top[j - 1].count) {
top[j] = top[j - 1];
j--;
}
top[j] = e;
}
}
printf("%lld\n", (long long)top[0].id * top[1].id * top[2].id);
free(t.slots);
return 0;
}
Step 5: know your input
Every ID is a small non-negative number, so the hash table can be replaced by
a plain array indexed by the ID. There is nothing to hash, probe or resize. The
cost moves to memory: one int per possible ID, used or not. The range check
turns the assumption into an error instead of a buffer overflow.
/* Step 5: know your input. Every ID is a small non-negative number, so the
* hash table can be a plain array indexed by the ID itself: no hashing, no
* probing, no resizing. The price is memory proportional to the largest
* possible ID, and a check that the input really keeps that promise. */
#include <stdio.h>
#include <stdlib.h>
#define MAX_ID 99999
static int counts[MAX_ID + 1];
int main(void) {
int n;
while (scanf("%d", &n) == 1) {
if (n < 0 || n > MAX_ID) {
fprintf(stderr, "ID %d is outside 0..%d\n", n, MAX_ID);
return 1;
}
counts[n]++;
}
int top[3] = {0, 0, 0}; /* IDs; their counts are counts[top[i]] */
for (int id = 0; id <= MAX_ID; id++) {
if (counts[id] > counts[top[2]]) {
int j = 2;
while (j > 0 && counts[id] > counts[top[j - 1]]) {
top[j] = top[j - 1];
j--;
}
top[j] = id;
}
}
printf("%lld\n", (long long)top[0] * top[1] * top[2]);
return 0;
}
Part 2: the other end
The first try sorts step 3’s table the other way round, least common first:
/* Part 2, first try: the step 3 hash table, sorted the other way round,
* least common first. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct entry {
int id;
int count; /* 0 = empty slot */
};
struct table {
struct entry *slots;
size_t cap; /* a power of two: 2^bits */
unsigned bits;
size_t used;
};
static size_t slot_for(int id, unsigned bits) {
/* Fibonacci hashing: multiply by 2^64 / golden ratio and keep the top
* `bits` bits, which mixes all of the key's bits into the slot number */
return (size_t)(((uint64_t)(uint32_t)id * 0x9E3779B97F4A7C15ull) >> (64 - bits));
}
static void grow(struct table *t);
static void add(struct table *t, int id) {
size_t i = slot_for(id, t->bits);
while (t->slots[i].count && t->slots[i].id != id) {
i = (i + 1) & (t->cap - 1);
}
if (!t->slots[i].count) {
t->slots[i].id = id;
t->used++;
}
t->slots[i].count++;
if (t->used * 4 >= t->cap * 3) {
grow(t);
}
}
static void grow(struct table *t) {
struct table bigger = {calloc(t->cap * 2, sizeof *t->slots), t->cap * 2, t->bits + 1, 0};
if (!bigger.slots) {
perror("calloc");
exit(1);
}
for (size_t i = 0; i < t->cap; i++) {
if (t->slots[i].count) {
size_t j = slot_for(t->slots[i].id, bigger.bits);
while (bigger.slots[j].count) {
j = (j + 1) & (bigger.cap - 1);
}
bigger.slots[j] = t->slots[i];
bigger.used++;
}
}
free(t->slots);
*t = bigger;
}
static int by_count_asc(const void *a, const void *b) {
const struct entry *x = a, *y = b;
return (x->count > y->count) - (x->count < y->count);
}
int main(void) {
struct table t = {calloc(64, sizeof(struct entry)), 64, 6, 0};
if (!t.slots) {
perror("calloc");
return 1;
}
int n;
while (scanf("%d", &n) == 1) {
add(&t, n);
}
size_t k = 0;
for (size_t i = 0; i < t.cap; i++) {
if (t.slots[i].count) {
t.slots[k++] = t.slots[i];
}
}
qsort(t.slots, k, sizeof *t.slots, by_count_asc);
printf("%lld\n", (long long)t.slots[0].id * t.slots[1].id * t.slots[2].id);
free(t.slots);
return 0;
}
And the one-pass version keeps the three smallest counts instead. Empty slots have a count of 0, which would always win, so they are skipped:
/* Part 2: the one-pass selection from step 4, keeping the three smallest
* counts instead. Empty slots (count 0) are skipped, since 0 would always
* win. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct entry {
int id;
int count; /* 0 = empty slot */
};
struct table {
struct entry *slots;
size_t cap; /* a power of two: 2^bits */
unsigned bits;
size_t used;
};
static size_t slot_for(int id, unsigned bits) {
/* Fibonacci hashing: multiply by 2^64 / golden ratio and keep the top
* `bits` bits, which mixes all of the key's bits into the slot number */
return (size_t)(((uint64_t)(uint32_t)id * 0x9E3779B97F4A7C15ull) >> (64 - bits));
}
static void grow(struct table *t);
static void add(struct table *t, int id) {
size_t i = slot_for(id, t->bits);
while (t->slots[i].count && t->slots[i].id != id) {
i = (i + 1) & (t->cap - 1);
}
if (!t->slots[i].count) {
t->slots[i].id = id;
t->used++;
}
t->slots[i].count++;
if (t->used * 4 >= t->cap * 3) {
grow(t);
}
}
static void grow(struct table *t) {
struct table bigger = {calloc(t->cap * 2, sizeof *t->slots), t->cap * 2, t->bits + 1, 0};
if (!bigger.slots) {
perror("calloc");
exit(1);
}
for (size_t i = 0; i < t->cap; i++) {
if (t->slots[i].count) {
size_t j = slot_for(t->slots[i].id, bigger.bits);
while (bigger.slots[j].count) {
j = (j + 1) & (bigger.cap - 1);
}
bigger.slots[j] = t->slots[i];
bigger.used++;
}
}
free(t->slots);
*t = bigger;
}
int main(void) {
struct table t = {calloc(64, sizeof(struct entry)), 64, 6, 0};
if (!t.slots) {
perror("calloc");
return 1;
}
int n;
while (scanf("%d", &n) == 1) {
add(&t, n);
}
struct entry low[3];
int have = 0;
for (size_t i = 0; i < t.cap; i++) {
struct entry e = t.slots[i];
if (!e.count) {
continue;
}
if (have < 3 || e.count < low[2].count) {
int j = have < 3 ? have++ : 2;
while (j > 0 && e.count < low[j - 1].count) {
low[j] = low[j - 1];
j--;
}
low[j] = e;
}
}
printf("%lld\n", (long long)low[0].id * low[1].id * low[2].id);
free(t.slots);
return 0;
}
C++
C++ has everything C was missing here: two map types, std::sort, and since
C++20 the ranges library, where algorithms take a whole container and a
projection. So the C++ ladder is about picking the right standard tool, and
then about one surprise in reading the input. Every program reads stdin and
prints one number, and compiles with
c++ -std=c++23 -O2 -Wall -Wextra -Werror (Apple clang 21 with its libc++,
which reports itself as version 22.1.6). Timings are best of 11 runs on an
Apple M2 Pro, startup included, on the shared timing input: 100,000 IDs drawn
from 50,000 distinct values.
Part 1: the three most common
Step 1: a beginner’s version
std::cin >> n reads the next number, std::map counts, and a lambda tells
std::sort to put the largest count first. The map can’t be sorted by value,
so the pairs are copied into a vector first.
// Step 1: what a beginner writes. Count with std::map, copy the pairs into a
// vector, sort it by count with a lambda, multiply the first three IDs.
#include <algorithm>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
int main() {
std::map<int, int> counts;
int n;
while (std::cin >> n) {
counts[n]++;
}
std::vector<std::pair<int, int>> items;
for (auto it = counts.begin(); it != counts.end(); ++it) {
items.push_back(*it);
}
std::sort(items.begin(), items.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second > b.second;
});
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= items[i].first;
}
std::cout << result << "\n";
return 0;
}
Step 2: a hash table
Nothing here needs the IDs in order, so the tree can become a hash table.
Only the type changes: std::unordered_map has the same operator[].
// Step 2: the IDs don't need to stay sorted, so count them in a hash table,
// std::unordered_map, instead of a tree. Only the container changes.
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::unordered_map<int, int> counts;
int n;
while (std::cin >> n) {
counts[n]++;
}
std::vector<std::pair<int, int>> items;
for (auto it = counts.begin(); it != counts.end(); ++it) {
items.push_back(*it);
}
std::sort(items.begin(), items.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second > b.second;
});
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= items[i].first;
}
std::cout << result << "\n";
return 0;
}
Step 3: whole ranges
Two habits of modern C++. The vector is built from the map with one
constructor call that takes a begin and an end. And std::ranges::sort
(C++20) takes the vector itself, a comparator, and a projection, the
member to compare by. std::greater{} means “largest first”, and the lambda
disappears.
// Step 3: work on whole ranges. The vector is built from the map in one
// constructor call, and std::ranges::sort takes the vector, std::greater for
// "largest first", and a projection that names the member to compare.
#include <algorithm>
#include <functional>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::unordered_map<int, int> counts;
int n;
while (std::cin >> n) {
counts[n]++;
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::sort(items, std::greater{}, &std::pair<int, int>::second);
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= items[i].first;
}
std::cout << result << "\n";
return 0;
}
Step 4: sort only the top three
std::ranges::partial_sort(items, items.begin() + 3, ...) puts the three
largest counts at the front, sorted, and leaves the rest in an unspecified
order.
// Step 4: only the first three places matter. partial_sort sorts just the
// first three; the rest of the vector is left in an unspecified order.
#include <algorithm>
#include <functional>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::unordered_map<int, int> counts;
int n;
while (std::cin >> n) {
counts[n]++;
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::partial_sort(items, items.begin() + 3, std::greater{}, &std::pair<int, int>::second);
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= items[i].first;
}
std::cout << result << "\n";
return 0;
}
Step 5: ranges all the way
The input loop and the product become ranges too.
std::views::istream<int>(std::cin) is a range that reads the next int each
time the loop asks for one. views::take(3) | views::keys is a lazy view of
the first three IDs, and C++23’s std::ranges::fold_left multiplies them,
starting from 1LL so the product is a long long. The counting line now
reads ++counts[n]; the count comes out the same either way.
// Step 5: the loops become ranges too. views::istream reads ints from
// std::cin as the loop asks for them, views::keys drops the counts, and
// C++23's ranges::fold_left multiplies the three IDs.
#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::unordered_map<int, int> counts;
for (int n : std::views::istream<int>(std::cin)) {
++counts[n];
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::partial_sort(items, items.begin() + 3, std::greater{}, &std::pair<int, int>::second);
auto top = items | std::views::take(3) | std::views::keys;
std::cout << std::ranges::fold_left(top, 1LL, std::multiplies{}) << "\n";
}
Step 6: the slow part was std::cin
Steps 1 to 5 all take 105 to 114 ms, whatever they do with the counts.
Reading the same input through a std::ifstream opened on /dev/stdin
instead of std::cin changes one line, keeps the same operator>>, and the
program drops to 11.8 ms. /dev/stdin is a Unix path, and I only tested it
on macOS, so step 5 is the portable ending; step 6 is what the measurements
say.
// Step 6: in libc++, std::cin fetches one character at a time with getc().
// A std::ifstream on /dev/stdin reads the same bytes through a buffered
// std::filebuf. Only the stream changes; operator>> does the same parsing.
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <ranges>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::ifstream input("/dev/stdin");
std::unordered_map<int, int> counts;
for (int n : std::views::istream<int>(input)) {
++counts[n];
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::partial_sort(items, items.begin() + 3, std::greater{}, &std::pair<int, int>::second);
auto top = items | std::views::take(3) | std::views::keys;
std::cout << std::ranges::fold_left(top, 1LL, std::multiplies{}) << "\n";
}
Part 2: the other end
The first try is step 3 with the default comparator, which is
std::ranges::less; passing {} asks for it. Least common comes first:
// Part 2, first try: step 3 with the sort turned round. The default
// comparator of std::ranges::sort is std::ranges::less, so {} asks for it
// and the least common IDs come first.
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::unordered_map<int, int> counts;
int n;
while (std::cin >> n) {
counts[n]++;
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::sort(items, {}, &std::pair<int, int>::second);
long long result = 1;
for (int i = 0; i < 3; i++) {
result *= items[i].first;
}
std::cout << result << "\n";
return 0;
}
And the final version is step 6 with the same change: partial_sort with
{} keeps the three smallest counts. They take 105.4 ms and 12.2 ms.
// Part 2: step 6 with the default comparator, so partial_sort puts the three
// smallest counts first.
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <ranges>
#include <unordered_map>
#include <utility>
#include <vector>
int main() {
std::ifstream input("/dev/stdin");
std::unordered_map<int, int> counts;
for (int n : std::views::istream<int>(input)) {
++counts[n];
}
std::vector<std::pair<int, int>> items(counts.begin(), counts.end());
std::ranges::partial_sort(items, items.begin() + 3, {}, &std::pair<int, int>::second);
auto bottom = items | std::views::take(3) | std::views::keys;
std::cout << std::ranges::fold_left(bottom, 1LL, std::multiplies{}) << "\n";
}
Go
Go has a built-in map and a sort package, so the beginner’s version is short
from the start. What has changed is everything around them. Since Go
1.21 there are generic slices, maps and cmp packages, since Go 1.23
functions can be iterators, and since Go 1.24 the map itself is a different
data structure. And Go deliberately randomises map iteration, which matters
more here than you’d expect. Every program below reads the input on stdin and
prints one number; each file is complete and builds with go build file.go on
go1.27.4. A single file needs no go.mod.
Part 1: the three most common
Step 1: a beginner’s version
Read numbers with fmt.Scan until it fails, count them in a map, copy the
keys into a slice, and sort that slice by count with sort.Slice and a
closure.
// Step 1: what a beginner writes. fmt.Scan reads one number at a time, a map
// counts them, the keys go into a slice, and sort.Slice orders that slice by
// count with a closure. The first three keys are multiplied.
package main
import (
"fmt"
"sort"
)
func main() {
counts := map[int]int{}
for {
var n int
_, err := fmt.Scan(&n)
if err != nil {
break
}
counts[n]++
}
keys := []int{}
for id := range counts {
keys = append(keys, id)
}
// highest count first
sort.Slice(keys, func(i, j int) bool {
return counts[keys[i]] > counts[keys[j]]
})
result := 1
for i := 0; i < 3; i++ {
result *= keys[i]
}
fmt.Println(result)
}
counts[n]++ needs no if/else for a new ID. The spec says indexing a map with
a missing key gives the zero value of the element type, so a new ID starts
at 0 and becomes 1.
Step 2: buffered input
fmt.Scan is convenient and slow. A bufio.Scanner reads large blocks and
hands out one token at a time; bufio.ScanWords makes the tokens
whitespace-separated words, like fmt.Scan’s, and strconv.Atoi parses each
one. The rest of the program doesn’t change.
// Step 2: fmt.Scan reads os.Stdin one byte per Read call. A bufio.Scanner
// reads 4 KB at a time and hands out whole words; strconv.Atoi turns each
// word into an int. Everything after the input loop is unchanged.
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
keys := []int{}
for id := range counts {
keys = append(keys, id)
}
// highest count first
sort.Slice(keys, func(i, j int) bool {
return counts[keys[i]] > counts[keys[j]]
})
result := 1
for i := 0; i < 3; i++ {
result *= keys[i]
}
fmt.Println(result)
}
Step 3: the generic sort
sort.Slice predates generics. It takes the slice as any and a less
function on indexes. Go 1.21 added slices.SortFunc, which takes the
elements themselves and a three-way comparison. cmp.Compare(x, y) returns
-1, 0 or +1, and passing b before a sorts in descending order. With the
final length known, the key slice also gets its capacity up front.
// Step 3: the generic sort. slices.SortFunc takes the elements themselves
// instead of indexes, and cmp.Compare returns -1, 0 or +1. Comparing b with a
// (not a with b) puts the highest count first.
package main
import (
"bufio"
"cmp"
"fmt"
"os"
"slices"
"strconv"
)
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
keys := make([]int, 0, len(counts))
for id := range counts {
keys = append(keys, id)
}
slices.SortFunc(keys, func(a, b int) int {
return cmp.Compare(counts[b], counts[a])
})
result := 1
for _, id := range keys[:3] {
result *= id
}
fmt.Println(result)
}
Step 4: iterators
Go 1.23 made functions rangeable, and the maps package gained maps.Keys,
which returns an iterator rather than a slice. slices.SortedFunc collects an
iterator into a new slice and sorts it, so the copying loop disappears.
// Step 4: iterators. maps.Keys returns an iterator over the map's keys, and
// slices.SortedFunc collects it into a new slice and sorts that slice in one
// call, so the loop that copied the keys goes away.
package main
import (
"bufio"
"cmp"
"fmt"
"maps"
"os"
"slices"
"strconv"
)
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
keys := slices.SortedFunc(maps.Keys(counts), func(a, b int) int {
return cmp.Compare(counts[b], counts[a])
})
result := 1
for _, id := range keys[:3] {
result *= id
}
fmt.Println(result)
}
Step 5: don’t sort what you won’t use
Sorting 43,000 keys to read three of them is wasted work. One pass over the map that keeps the three highest counts seen so far is O(k), and for most entries it is one comparison with the current third place. An experienced Go programmer would write this with a small struct and a fixed-size array, with no slice and no allocation for the result.
// Step 5: don't sort what you won't use. One pass over the map keeps the three
// highest counts seen so far: O(k) instead of O(k log k), and no slice of keys
// at all.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
type entry struct {
id, count int
}
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
// top[0] has the highest count; the zero value (count 0) loses to any ID
var top [3]entry
for id, c := range counts {
if c <= top[2].count {
continue
}
i := 2
for i > 0 && c > top[i-1].count {
top[i] = top[i-1]
i--
}
top[i] = entry{id, c}
}
fmt.Println(top[0].id * top[1].id * top[2].id)
}
Part 2: the other end
The first try is step 4 with the comparison turned around, least common first:
// Part 2, step 1: step 4 with the comparison the other way round, so the
// least common IDs come first.
package main
import (
"bufio"
"cmp"
"fmt"
"maps"
"os"
"slices"
"strconv"
)
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
keys := slices.SortedFunc(maps.Keys(counts), func(a, b int) int {
return cmp.Compare(counts[a], counts[b])
})
result := 1
for _, id := range keys[:3] {
result *= id
}
fmt.Println(result)
}
And the one-pass version keeps the three smallest counts instead. Every count in the map is at least 1, so count 0 marks a place that isn’t filled yet:
// Part 2, step 2: step 5 turned around. One pass keeps the three lowest
// counts. Every count in the map is at least 1, so an empty place is marked
// with count 0 and filled by the first IDs the loop meets.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
type entry struct {
id, count int
}
func main() {
counts := map[int]int{}
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
n, err := strconv.Atoi(sc.Text())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
counts[n]++
}
// bottom[0] has the lowest count; count 0 means "not filled yet"
var bottom [3]entry
for id, c := range counts {
if bottom[2].count != 0 && c >= bottom[2].count {
continue
}
i := 2
for i > 0 && (bottom[i-1].count == 0 || c < bottom[i-1].count) {
bottom[i] = bottom[i-1]
i--
}
bottom[i] = entry{id, c}
}
fmt.Println(bottom[0].id * bottom[1].id * bottom[2].id)
}
Rust
Rust’s standard library has what this puzzle needs, though less of it is in
scope by default than in Python: HashMap lives in std::collections and
needs a use, and slices come with stable and unstable sorts and an O(n)
selection. The surprises are in the details. A HashMap lists its keys in a
different order in every process, and even in two maps of the same program.
A sort can refuse a comparison that isn’t an order. And whether * panics on
overflow depends on a compiler flag. Every program below reads the input on
stdin and prints one number; each file is complete and builds with
rustc --edition 2024 -C opt-level=3 file.rs on rustc 1.100.1. A single file
needs no Cargo project.
Part 1: the three most common
Step 1: a beginner’s version
Read stdin line by line, parse each line into an i64, and count in a
HashMap. If the ID is there, get_mut gives a mutable reference to its
count, otherwise insert adds it. Then copy the pairs into a Vec, sort them
by count with a closure, and multiply the first three IDs.
use std::collections::HashMap;
use std::io;
fn main() {
let mut counts: HashMap<i64, usize> = HashMap::new();
for line in io::stdin().lines() {
let line = line.unwrap();
let n: i64 = line.trim().parse().unwrap();
if let Some(count) = counts.get_mut(&n) {
*count += 1;
} else {
counts.insert(n, 1);
}
}
let mut pairs: Vec<(i64, usize)> = Vec::new();
for (id, count) in &counts {
pairs.push((*id, *count));
}
pairs.sort_by(|a, b| b.1.cmp(&a.1));
let mut result: i64 = 1;
for i in 0..3 {
result *= pairs[i].0;
}
println!("{}", result);
}
Every line from lines() is an io::Result<String>, and parse returns a
Result too, so each needs an unwrap(), which stops the program with a
panic on an error. parse works out what to parse into from the annotation
on n. In the comparison, b.1.cmp(&a.1) compares the counts with b first,
which sorts in descending order.
Step 2: the entry API
counts.entry(n) looks the key up once and returns an Entry, which is
either occupied or vacant. or_insert(0) puts a 0 into a vacant one, and
either way returns a mutable reference to the count, which *... += 1
increments. The if/else goes away.
use std::collections::HashMap;
use std::io;
fn main() {
let mut counts: HashMap<i64, usize> = HashMap::new();
for line in io::stdin().lines() {
let n: i64 = line.unwrap().trim().parse().unwrap();
*counts.entry(n).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = Vec::new();
for (id, count) in &counts {
pairs.push((*id, *count));
}
pairs.sort_by(|a, b| b.1.cmp(&a.1));
let mut result: i64 = 1;
for i in 0..3 {
result *= pairs[i].0;
}
println!("{}", result);
}
Step 3: iterators instead of loops
counts.into_iter().collect() moves the pairs out of the map into a new
Vec, which replaces the copying loop. At the end, iter().take(3) yields the
first three pairs, map keeps the ID of each, and product() multiplies
them.
use std::collections::HashMap;
use std::io;
fn main() {
let mut counts: HashMap<i64, usize> = HashMap::new();
for line in io::stdin().lines() {
let n: i64 = line.unwrap().trim().parse().unwrap();
*counts.entry(n).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
pairs.sort_by(|a, b| b.1.cmp(&a.1));
let result: i64 = pairs.iter().take(3).map(|&(id, _)| id).product();
println!("{result}");
}
Step 4: sort by key, and don’t ask for stability
sort_unstable_by_key takes a function that extracts the sort key from each
element. std::cmp::Reverse wraps a value and turns its ordering around, so
Reverse(count) puts the highest counts first without writing a comparison
at all.
use std::cmp::Reverse;
use std::collections::HashMap;
use std::io;
fn main() {
let mut counts: HashMap<i64, usize> = HashMap::new();
for line in io::stdin().lines() {
let n: i64 = line.unwrap().trim().parse().unwrap();
*counts.entry(n).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
pairs.sort_unstable_by_key(|&(_, count)| Reverse(count));
let result: i64 = pairs.iter().take(3).map(|&(id, _)| id).product();
println!("{result}");
}
Step 5: read everything, and use ?
io::read_to_string reads all of stdin into one String, and
split_ascii_whitespace walks it in words, borrowing each one from the big
string with no allocation. main now returns a Result, so the ? operator
can pass a read or parse error up and out of main instead of panicking
inside unwrap. Blank lines and extra spaces no longer matter either.
use std::cmp::Reverse;
use std::collections::HashMap;
use std::error::Error;
use std::io;
fn main() -> Result<(), Box<dyn Error>> {
let input = io::read_to_string(io::stdin())?;
let mut counts: HashMap<i64, usize> = HashMap::new();
for word in input.split_ascii_whitespace() {
*counts.entry(word.parse()?).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
pairs.sort_unstable_by_key(|&(_, count)| Reverse(count));
let result: i64 = pairs.iter().take(3).map(|&(id, _)| id).product();
println!("{result}");
Ok(())
}
Step 6: don’t sort what you won’t use
Sorting 43,282 pairs to read three is wasted work.
select_nth_unstable_by_key(2, ...) reorders the Vec so that the element at
index 2 is the one a full sort would put there, everything before it compares
less or equal, and everything after it greater or equal. The three most
common pairs end up in pairs[..3], in no particular order, which is all a
product needs.
use std::cmp::Reverse;
use std::collections::HashMap;
use std::error::Error;
use std::io;
fn main() -> Result<(), Box<dyn Error>> {
let input = io::read_to_string(io::stdin())?;
let mut counts: HashMap<i64, usize> = HashMap::new();
for word in input.split_ascii_whitespace() {
*counts.entry(word.parse()?).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
// Moves the three most common pairs into pairs[..3], in no particular order.
pairs.select_nth_unstable_by_key(2, |&(_, count)| Reverse(count));
let result: i64 = pairs[..3].iter().map(|&(id, _)| id).product();
println!("{result}");
Ok(())
}
Part 2: the other end
The first try is step 5 with the key not reversed, so the least common pairs come first:
use std::collections::HashMap;
use std::error::Error;
use std::io;
fn main() -> Result<(), Box<dyn Error>> {
let input = io::read_to_string(io::stdin())?;
let mut counts: HashMap<i64, usize> = HashMap::new();
for word in input.split_ascii_whitespace() {
*counts.entry(word.parse()?).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
pairs.sort_unstable_by_key(|&(_, count)| count);
let result: i64 = pairs.iter().take(3).map(|&(id, _)| id).product();
println!("{result}");
Ok(())
}
And the selection version picks the three smallest counts instead:
use std::collections::HashMap;
use std::error::Error;
use std::io;
fn main() -> Result<(), Box<dyn Error>> {
let input = io::read_to_string(io::stdin())?;
let mut counts: HashMap<i64, usize> = HashMap::new();
for word in input.split_ascii_whitespace() {
*counts.entry(word.parse()?).or_insert(0) += 1;
}
let mut pairs: Vec<(i64, usize)> = counts.into_iter().collect();
// Moves the three least common pairs into pairs[..3], in no particular order.
pairs.select_nth_unstable_by_key(2, |&(_, count)| count);
let result: i64 = pairs[..3].iter().map(|&(id, _)| id).product();
println!("{result}");
Ok(())
}
Zig
Zig’s standard library has a hash map, a growable array and two sorts, so
nothing here has to be written from scratch as in C. The difference is that
nothing allocates on its own. Every container that can grow takes an
Allocator, and main decides where memory comes from. Since Zig 0.16 all
I/O goes through an Io value as well, and main can receive both in one
std.process.Init parameter. Every program below reads stdin and prints one
number; each file is complete and builds with zig build-exe -O fast on
Zig 0.17.1 (fast is the mode called ReleaseFast before 0.17.0). Timings
are best of 11 runs on an Apple M2 Pro, startup included, on the shared timing
input: 100,000 IDs drawn from 50,000 values (43,282 distinct). Each range
covers six timing sessions.
Part 1: the three most common
Step 1: a beginner’s version
Read all of stdin into one buffer, split it into lines with
std.mem.tokenizeScalar, and parse each line with std.fmt.parseInt. Count
in a std.AutoHashMap. get returns an optional, if (...) |count| unwraps
it, and put stores the new count. Then copy the pairs into an ArrayList,
sort it with std.mem.sort and a lessThan function, and multiply the first
three IDs.
// Step 1: what a beginner writes. Read all of stdin, split it into lines,
// count each ID in an AutoHashMap with get and put, copy the pairs into an
// ArrayList, sort it by count with std.mem.sort, and multiply the first three.
const std = @import("std");
const Pair = struct {
id: u32,
count: u32,
};
fn byCountDesc(_: void, a: Pair, b: Pair) bool {
return a.count > b.count;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(gpa, .unlimited);
defer gpa.free(input);
var counts = std.AutoHashMap(u32, u32).init(gpa);
defer counts.deinit();
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
if (counts.get(id)) |count| {
try counts.put(id, count + 1);
} else {
try counts.put(id, 1);
}
}
var pairs: std.ArrayList(Pair) = .empty;
defer pairs.deinit(gpa);
var it = counts.iterator();
while (it.next()) |entry| {
try pairs.append(gpa, .{ .id = entry.key_ptr.*, .count = entry.value_ptr.* });
}
std.mem.sort(Pair, pairs.items, {}, byCountDesc);
var result: u64 = 1;
for (pairs.items[0..3]) |pair| {
result *= pair.id;
}
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Every call that can fail is marked with try, which returns the error from
main; the program then prints the error name and exits with status 1. Every
allocation has a defer that frees it when main returns. The map stores the
allocator it was created with, while the ArrayList takes it on every
append. Output goes through a buffered writer, and a forgotten flush
prints nothing at all.
Step 2: getOrPut
getOrPut looks the ID up once and returns pointers to its key and value,
plus found_existing. A new entry’s value is undefined, so it is set to 0
first, and then the count goes up through the pointer. The if/else on get
goes away.
// Step 2: getOrPut. One lookup finds the ID's slot or makes a new one, and
// returns a pointer to the count, so the if/else on get goes away.
const std = @import("std");
const Pair = struct {
id: u32,
count: u32,
};
fn byCountDesc(_: void, a: Pair, b: Pair) bool {
return a.count > b.count;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(gpa, .unlimited);
defer gpa.free(input);
var counts = std.AutoHashMap(u32, u32).init(gpa);
defer counts.deinit();
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
const slot = try counts.getOrPut(id);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
var pairs: std.ArrayList(Pair) = .empty;
defer pairs.deinit(gpa);
var it = counts.iterator();
while (it.next()) |entry| {
try pairs.append(gpa, .{ .id = entry.key_ptr.*, .count = entry.value_ptr.* });
}
std.mem.sort(Pair, pairs.items, {}, byCountDesc);
var result: u64 = 1;
for (pairs.items[0..3]) |pair| {
result *= pair.id;
}
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Step 3: an arena, and a map without an allocator inside
Everything this program allocates lives until it exits, so it can all come
from one arena, which frees everything at once. std.process.Init already
has one, init.arena, backed by the page allocator, so all the defers and
deinits go away. The map becomes AutoHashMapUnmanaged, which takes the
allocator on every call that may allocate, as ArrayList already does.
// Step 3: an arena. Everything this program allocates lives until it exits,
// so it all comes from the arena that main receives in std.process.Init,
// which frees it all at once when main returns. Every defer and deinit goes
// away. The map becomes the unmanaged kind, which doesn't keep an allocator
// inside and takes one on every call that may allocate, like ArrayList.
const std = @import("std");
const Pair = struct {
id: u32,
count: u32,
};
fn byCountDesc(_: void, a: Pair, b: Pair) bool {
return a.count > b.count;
}
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var counts: std.AutoHashMapUnmanaged(u32, u32) = .empty;
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
const slot = try counts.getOrPut(arena, id);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
var pairs: std.ArrayList(Pair) = .empty;
var it = counts.iterator();
while (it.next()) |entry| {
try pairs.append(arena, .{ .id = entry.key_ptr.*, .count = entry.value_ptr.* });
}
std.mem.sort(Pair, pairs.items, {}, byCountDesc);
var result: u64 = 1;
for (pairs.items[0..3]) |pair| {
result *= pair.id;
}
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Step 4: don’t ask for stability
std.mem.sort is a stable sort. Nothing here needs equal counts to keep
their order, so std.mem.sortUnstable does the same job.
// Step 4: don't ask for stability. std.mem.sort is a stable sort; nothing
// here needs equal counts to keep their order, so std.mem.sortUnstable
// (pattern-defeating quicksort) does the same job.
const std = @import("std");
const Pair = struct {
id: u32,
count: u32,
};
fn byCountDesc(_: void, a: Pair, b: Pair) bool {
return a.count > b.count;
}
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var counts: std.AutoHashMapUnmanaged(u32, u32) = .empty;
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
const slot = try counts.getOrPut(arena, id);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
var pairs: std.ArrayList(Pair) = .empty;
var it = counts.iterator();
while (it.next()) |entry| {
try pairs.append(arena, .{ .id = entry.key_ptr.*, .count = entry.value_ptr.* });
}
std.mem.sortUnstable(Pair, pairs.items, {}, byCountDesc);
var result: u64 = 1;
for (pairs.items[0..3]) |pair| {
result *= pair.id;
}
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Step 5: don’t sort what you won’t use
Sorting 43,282 pairs to read three is wasted work. One pass over the map
keeps the three highest counts seen so far, shifting lower ones down, and the
ArrayList of pairs is gone.
// Step 5: don't sort what you won't use. One pass over the map keeps the
// three highest counts seen so far: O(k) instead of O(k log k), and the
// ArrayList of pairs is gone.
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var counts: std.AutoHashMapUnmanaged(u32, u32) = .empty;
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
const slot = try counts.getOrPut(arena, id);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
// top_ids[0] has the highest count; a slot stays at count 0 until filled
var top_ids = [3]u32{ 0, 0, 0 };
var top_counts = [3]u32{ 0, 0, 0 };
var it = counts.iterator();
while (it.next()) |entry| {
const count = entry.value_ptr.*;
if (count <= top_counts[2]) continue;
var j: usize = 2;
while (j > 0 and count > top_counts[j - 1]) : (j -= 1) {
top_ids[j] = top_ids[j - 1];
top_counts[j] = top_counts[j - 1];
}
top_ids[j] = entry.key_ptr.*;
top_counts[j] = count;
}
const result = @as(u64, top_ids[0]) * top_ids[1] * top_ids[2];
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Step 6: know your input
Every ID is below 100,000, so the map can be a plain array indexed by the ID.
Its size is computed at compile time, @splat(0) fills it with zeros, and
the range check turns a broken promise into an error instead of an
out-of-bounds write.
// Step 6: know your input. Every ID is below 100,000, so the map becomes a
// plain array indexed by the ID, sized at compile time. Nothing to hash,
// probe or grow, and the only allocation left is the input itself.
const std = @import("std");
const max_id = 99_999;
var counts: [max_id + 1]u32 = @splat(0);
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
if (id > max_id) {
std.debug.print("ID {d} is above {d}\n", .{ id, max_id });
return error.IdOutOfRange;
}
counts[id] += 1;
}
var top_ids = [3]u32{ 0, 0, 0 };
var top_counts = [3]u32{ 0, 0, 0 };
for (counts, 0..) |count, id| {
if (count <= top_counts[2]) continue;
var j: usize = 2;
while (j > 0 and count > top_counts[j - 1]) : (j -= 1) {
top_ids[j] = top_ids[j - 1];
top_counts[j] = top_counts[j - 1];
}
top_ids[j] = @intCast(id);
top_counts[j] = count;
}
const result = @as(u64, top_ids[0]) * top_ids[1] * top_ids[2];
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Part 2: the other end
The first try is step 4 with the comparison turned around, least common first (8.4 to 10.0 ms):
// Part 2, step 1: step 4 with the comparison turned around, so the least
// common IDs come first.
const std = @import("std");
const Pair = struct {
id: u32,
count: u32,
};
fn byCountAsc(_: void, a: Pair, b: Pair) bool {
return a.count < b.count;
}
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var counts: std.AutoHashMapUnmanaged(u32, u32) = .empty;
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
const slot = try counts.getOrPut(arena, id);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
var pairs: std.ArrayList(Pair) = .empty;
var it = counts.iterator();
while (it.next()) |entry| {
try pairs.append(arena, .{ .id = entry.key_ptr.*, .count = entry.value_ptr.* });
}
std.mem.sortUnstable(Pair, pairs.items, {}, byCountAsc);
var result: u64 = 1;
for (pairs.items[0..3]) |pair| {
result *= pair.id;
}
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
And the array version keeps the three lowest counts instead (6.1 to 7.5 ms). IDs that never appeared have a count of 0, which would always win, so the pass skips them:
// Part 2, step 2: step 6's array, keeping the three lowest counts instead.
// IDs that never appeared have a count of 0, which would always win, so the
// pass skips them.
const std = @import("std");
const max_id = 99_999;
var counts: [max_id + 1]u32 = @splat(0);
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
var stdin_buffer: [4096]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(io, &stdin_buffer);
const input = try stdin_reader.interface.allocRemaining(arena, .unlimited);
var lines = std.mem.tokenizeScalar(u8, input, '\n');
while (lines.next()) |line| {
const id = try std.fmt.parseInt(u32, line, 10);
if (id > max_id) {
std.debug.print("ID {d} is above {d}\n", .{ id, max_id });
return error.IdOutOfRange;
}
counts[id] += 1;
}
const none = std.math.maxInt(u32);
var low_ids = [3]u32{ 0, 0, 0 };
var low_counts = [3]u32{ none, none, none };
for (counts, 0..) |count, id| {
if (count == 0 or count >= low_counts[2]) continue;
var j: usize = 2;
while (j > 0 and count < low_counts[j - 1]) : (j -= 1) {
low_ids[j] = low_ids[j - 1];
low_counts[j] = low_counts[j - 1];
}
low_ids[j] = @intCast(id);
low_counts[j] = count;
}
const result = @as(u64, low_ids[0]) * low_ids[1] * low_ids[2];
var stdout_buffer: [64]u8 = undefined;
var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
try stdout_writer.interface.print("{d}\n", .{result});
try stdout_writer.interface.flush();
}
Swift
Swift’s standard library has everything this puzzle needs without an import:
readLine() for input, a Dictionary for counting, and sorted(by:) with a
closure. The interesting parts are what those types promise. A dictionary is a
value type that copies itself only when you change a shared copy, its order is
deliberately unpredictable, and its sort has been stable since Swift 5 but was
only documented as stable in Swift 5.8. Every program below reads the input on
stdin and prints one number. Each file is complete and builds with
swiftc -O file.swift on Apple Swift 6.4.2. Top-level code in a single file
needs no main function.
Part 1: the three most common
Step 1: a beginner’s version
Read lines with readLine() until it returns nil, parse each with Int(),
count in a dictionary with if/else on the optional that a lookup returns, sort
the pairs by count, and multiply the first three IDs.
// Step 1: what a beginner writes. readLine() returns one line at a time, Int()
// parses it, a dictionary counts each ID with if/else on the optional it
// returns, sorted(by:) orders the pairs by count, and a loop multiplies the
// first three IDs.
var counts: [Int: Int] = [:]
while let line = readLine() {
if let n = Int(line) {
if let c = counts[n] {
counts[n] = c + 1
} else {
counts[n] = 1
}
}
}
// highest count first
let sorted = counts.sorted { $0.value > $1.value }
var result = 1
for i in 0..<3 {
result *= sorted[i].key
}
print(result)
Int(line) returns nil for a line that isn’t a number, and if let skips
it. Sorting a dictionary gives an array of its elements, and a
Dictionary element is the labelled tuple (key: Key, value: Value), which is
why the closure can say $0.value and the loop sorted[i].key.
Step 2: the default subscript
counts[n, default: 0] returns 0 for an ID we haven’t seen, and += 1
writes the result back. The if/else goes away.
// Step 2: the subscript with a default value. counts[n, default: 0] gives 0
// for an ID we haven't seen, and += 1 writes the new count back in place, so
// the if/else goes away.
var counts: [Int: Int] = [:]
while let line = readLine() {
if let n = Int(line) {
counts[n, default: 0] += 1
}
}
// highest count first
let sorted = counts.sorted { $0.value > $1.value }
var result = 1
for i in 0..<3 {
result *= sorted[i].key
}
print(result)
Step 3: build the dictionary in one call
Two changes, both about building the counts in one expression. The input
becomes a sequence: AnyIterator { readLine() } wraps readLine as an
iterator, and compactMap keeps the lines that parse as an Int, giving an
array of all n IDs. Then each ID becomes an (id, 1) pair, and
Dictionary(_:uniquingKeysWith:) builds the dictionary, calling + on the
two values whenever a key repeats.
// Step 3: build the dictionary in one call. The input lines become a sequence
// of IDs, each ID becomes an (id, 1) pair, and Dictionary(_:uniquingKeysWith:)
// adds up the 1s of every repeated key with +.
let ids = AnyIterator { readLine() }.compactMap { Int($0) }
let counts = Dictionary(ids.map { ($0, 1) }, uniquingKeysWith: +)
// highest count first
let sorted = counts.sorted { $0.value > $1.value }
var result = 1
for i in 0..<3 {
result *= sorted[i].key
}
print(result)
Step 4: one pipeline
The sort, the first three, the IDs and the product become one chain.
prefix(3) keeps the three most common pairs, map(\.key) takes their IDs,
and reduce(1, *) multiplies them. A key path such as \.key can stand in
for a function that reads that property, and an operator such as * is a
function too.
// Step 4: one pipeline. prefix(3) keeps the three most common pairs,
// map(\.key) uses a key path as a function to pick their IDs, and
// reduce(1, *) multiplies them.
let ids = AnyIterator { readLine() }.compactMap { Int($0) }
let counts = Dictionary(ids.map { ($0, 1) }, uniquingKeysWith: +)
let product = counts
.sorted { $0.value > $1.value }
.prefix(3)
.map(\.key)
.reduce(1, *)
print(product)
Step 5: don’t sort what you won’t use
Sorting 43,282 pairs to keep three is wasted work. One pass over the
dictionary that keeps the three highest counts seen so far is O(k), and the
where clause on the for loop skips every entry that can’t beat third
place with a single comparison. The three places are labelled tuples, so
the code reads top[2].count rather than top[2].1.
// Step 5: don't sort what you won't use. One pass over the dictionary keeps
// the three highest counts seen so far: O(k) instead of O(k log k).
let ids = AnyIterator { readLine() }.compactMap { Int($0) }
let counts = Dictionary(ids.map { ($0, 1) }, uniquingKeysWith: +)
// top[0] has the highest count; count 0 loses to every real ID
var top = [(id: 0, count: 0), (id: 0, count: 0), (id: 0, count: 0)]
for (id, count) in counts where count > top[2].count {
var i = 2
while i > 0 && count > top[i - 1].count {
top[i] = top[i - 1]
i -= 1
}
top[i] = (id, count)
}
print(top.map(\.id).reduce(1, *))
Part 2: the other end
The first try is step 4’s pipeline with the comparison turned round, so the least common IDs come first:
// Part 2, step 1: step 4's pipeline with the comparison turned round, so the
// least common IDs come first.
let ids = AnyIterator { readLine() }.compactMap { Int($0) }
let counts = Dictionary(ids.map { ($0, 1) }, uniquingKeysWith: +)
let product = counts
.sorted { $0.value < $1.value }
.prefix(3)
.map(\.key)
.reduce(1, *)
print(product)
And the one-pass version keeps the three lowest counts instead. Every count
is at least 1, so Int.max marks a place that isn’t filled yet:
// Part 2, step 2: one pass that keeps the three lowest counts. Every count is
// at least 1, so Int.max marks a place that isn't filled yet.
let ids = AnyIterator { readLine() }.compactMap { Int($0) }
let counts = Dictionary(ids.map { ($0, 1) }, uniquingKeysWith: +)
// bottom[0] has the lowest count
var bottom = [(id: 0, count: Int.max), (id: 0, count: Int.max), (id: 0, count: Int.max)]
for (id, count) in counts where count < bottom[2].count {
var i = 2
while i > 0 && count < bottom[i - 1].count {
bottom[i] = bottom[i - 1]
i -= 1
}
bottom[i] = (id, count)
}
print(bottom.map(\.id).reduce(1, *))
Java
Java has a hash map, a sort that takes a lambda, and since Java 8 streams
that count and sort in one pipeline. So the beginner’s version is already
short. So this ladder is mostly about what those tools cost. Every key and
count in a HashMap is an object, the JVM needs about 24 ms to start, and
code runs in the interpreter until the JIT compiler gets to it. Every program below reads the
input on stdin and prints one number; each file is complete, imports and all,
and is built with javac and run with java from OpenJDK 27.0.1.1 (the
Homebrew build). Timings are best of 11 runs on an Apple M2 Pro, startup
included, on the shared timing input: 100,000 IDs drawn from 50,000 distinct
values.
The class names look wrong on purpose. Java code uses CamelCase class names
like PartOneStepOne, but javac insists that a public class lives in a file
of the same name (class Foo is public, should be declared in a file named Foo.java), and these files follow the repo’s part1_step1 naming. So the
class in part1_step1.java is public class part1_step1.
Part 1: the three most common
Step 1: a beginner’s version
A Scanner reads one int at a time, a HashMap counts with
containsKey, get and put, and the map’s entries are copied into an
ArrayList so that Collections.sort can order them by count with a lambda.
The product goes into a long.
// Step 1: what a beginner writes. A Scanner reads one int at a time, a HashMap
// counts them with containsKey/get/put, the entries are copied into a list,
// and Collections.sort orders that list by count with a lambda. The first
// three keys are multiplied in a long.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class part1_step1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Integer, Integer> counts = new HashMap<>();
while (sc.hasNextInt()) {
int n = sc.nextInt();
if (counts.containsKey(n)) {
counts.put(n, counts.get(n) + 1);
} else {
counts.put(n, 1);
}
}
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(counts.entrySet());
// highest count first
Collections.sort(entries, (a, b) -> b.getValue() - a.getValue());
long result = 1;
for (int i = 0; i < 3; i++) {
result *= entries.get(i).getKey();
}
System.out.println(result);
}
}
Step 2: smaller tools, same shape
Two swaps. counts.merge(n, 1, Integer::sum) puts 1 for a new ID and
otherwise combines the old count with 1 using Integer.sum, so the if/else
goes away. Map.Entry.comparingByValue(Comparator.reverseOrder()) builds the
comparator, and List.sort replaces Collections.sort.
// Step 2: the library's small helpers. Map.merge replaces the if/else, and
// Map.Entry.comparingByValue builds the comparator instead of a hand-written
// subtraction. List.sort is the method behind Collections.sort.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class part1_step2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Integer, Integer> counts = new HashMap<>();
while (sc.hasNextInt()) {
counts.merge(sc.nextInt(), 1, Integer::sum);
}
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
long result = 1;
for (int i = 0; i < 3; i++) {
result *= entries.get(i).getKey();
}
System.out.println(result);
}
}
Step 3: buffered input
Scanner is convenient and slow. A BufferedReader hands out whole lines
and Integer.parseInt converts each one. The rest of the program doesn’t
change.
// Step 3: buffered input. A BufferedReader hands out whole lines and
// Integer.parseInt converts each one; the Scanner and its regular expressions
// are gone. Counting and sorting don't change.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class part1_step3 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Integer> counts = new HashMap<>();
String line;
while ((line = in.readLine()) != null) {
counts.merge(Integer.parseInt(line), 1, Integer::sum);
}
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
long result = 1;
for (int i = 0; i < 3; i++) {
result *= entries.get(i).getKey();
}
System.out.println(result);
}
}
Step 4: streams
Since Java 8 the same work is a pipeline. in.lines() is a stream of lines,
Collectors.groupingBy(Function.identity(), Collectors.counting()) builds the
map of counts, and a second stream over the entries sorts them, keeps three
and multiplies their keys.
// Step 4: streams. Collectors.groupingBy with counting() builds the map of
// counts, and a second stream sorts the entries, keeps three and multiplies
// their keys.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class part1_step4 {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Long> counts = in.lines()
.map(Integer::valueOf)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
long result = counts.entrySet().stream()
.sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
.limit(3)
.mapToLong(Map.Entry::getKey)
.reduce(1, (a, b) -> a * b);
System.out.println(result);
}
}
Step 5: don’t sort what you won’t use
Sorting 43,000 entries to read three of them is wasted work. A
PriorityQueue ordered by count is a min-heap, so its head is the smallest
count kept so far. Add each entry and drop the head whenever the queue grows
to four. After one pass the three highest counts are left. var (Java 10)
saves writing the queue’s type twice.
// Step 5: don't sort what you won't use. A PriorityQueue ordered by count is a
// min-heap; keeping it at three entries leaves the three highest counts in it
// after one pass over the map.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.function.Function;
import java.util.stream.Collectors;
public class part1_step5 {
public static void main(String[] args) {
var in = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Long> counts = in.lines()
.map(Integer::valueOf)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// the head of the queue is the smallest of the counts kept so far
var top = new PriorityQueue<Map.Entry<Integer, Long>>(Map.Entry.comparingByValue());
for (var e : counts.entrySet()) {
top.add(e);
if (top.size() > 3) {
top.poll();
}
}
long result = 1;
for (var e : top) {
result *= e.getKey();
}
System.out.println(result);
}
}
Step 6: no boxing at all
The JDK has no map from int to int. It does have a fast sort for
int[].
This step changes three things at once. mapToInt(Integer::parseInt) reads
the IDs into an int[] with no Integer in sight, Arrays.sort puts equal
IDs next to each other, and one pass measures each run of equal IDs and keeps
the three longest.
// Step 6: no boxing at all. The IDs go into an int[], Arrays.sort puts equal
// IDs next to each other, and one pass over the sorted array measures each
// run of equal IDs and keeps the three longest. No HashMap, no Integer.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class part1_step6 {
public static void main(String[] args) {
var in = new BufferedReader(new InputStreamReader(System.in));
int[] ids = in.lines().mapToInt(Integer::parseInt).toArray();
Arrays.sort(ids);
// topId[0] has the highest count; count 0 loses to any ID
int[] topId = new int[3];
int[] topCount = new int[3];
for (int start = 0, end; start < ids.length; start = end) {
end = start + 1;
while (end < ids.length && ids[end] == ids[start]) {
end++;
}
int c = end - start;
if (c <= topCount[2]) {
continue;
}
int i = 2;
while (i > 0 && c > topCount[i - 1]) {
topId[i] = topId[i - 1];
topCount[i] = topCount[i - 1];
i--;
}
topId[i] = ids[start];
topCount[i] = c;
}
System.out.println((long) topId[0] * topId[1] * topId[2]);
}
}
Which one would I keep?
| step | what changed | timing input | picking three |
|---|---|---|---|
| 1 | Scanner, HashMap, Collections.sort | 125.5 ms | sort k: O(k log k) |
| 2 | merge, comparingByValue | 125.2 ms | sort k: O(k log k) |
| 3 | BufferedReader, parseInt | 60.8 ms | sort k: O(k log k) |
| 4 | streams, groupingBy(counting()) | 73.1 ms | sort k: O(k log k) |
| 5 | PriorityQueue of three | 68.6 ms | heap of 3: O(k) |
| 6 | int[], Arrays.sort, runs | 58.5 ms | one pass after O(n log n) |
The one big jump is dropping Scanner. After that the differences are a few
milliseconds on top of a 24 ms JVM start. An experienced Java programmer
would write step 4 or step 5: a stream to count, then a sort or a heap to
pick. I’d keep step 5. Step 6 is what I’d write if this ran in a hot loop on
large inputs, and only for int keys.
Part 2: the other end
The first try is step 4 with the comparator the right way round for once.
comparingByValue() without reversed() puts the least common first.
// Part 2, first try: step 4 with the comparator the other way round. Without
// reversed(), comparingByValue() puts the smallest counts first.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class part2_step1 {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Long> counts = in.lines()
.map(Integer::valueOf)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
long result = counts.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.limit(3)
.mapToLong(Map.Entry::getKey)
.reduce(1, (a, b) -> a * b);
System.out.println(result);
}
}
Then step 5’s heap turned around. With the comparator reversed, the head is the largest count kept so far, and that is the one to drop:
// Part 2: step 5's heap turned around. With the comparator reversed the head
// of the PriorityQueue is the largest count kept so far, and that is the one
// to drop when a fourth entry comes in.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.function.Function;
import java.util.stream.Collectors;
public class part2_step2 {
public static void main(String[] args) {
var in = new BufferedReader(new InputStreamReader(System.in));
Map<Integer, Long> counts = in.lines()
.map(Integer::valueOf)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
var top = new PriorityQueue<Map.Entry<Integer, Long>>(
Map.Entry.<Integer, Long>comparingByValue().reversed());
for (var e : counts.entrySet()) {
top.add(e);
if (top.size() > 3) {
top.poll();
}
}
long result = 1;
for (var e : top) {
result *= e.getKey();
}
System.out.println(result);
}
}
And step 6 turned around, keeping the three shortest runs. MAX_VALUE marks a
place not filled yet:
// Part 2: step 6 turned around. Sort the IDs, measure each run of equal IDs,
// and keep the three shortest runs.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class part2_step3 {
public static void main(String[] args) {
var in = new BufferedReader(new InputStreamReader(System.in));
int[] ids = in.lines().mapToInt(Integer::parseInt).toArray();
Arrays.sort(ids);
// topId[0] has the lowest count; MAX_VALUE marks a place not yet filled
int[] topId = new int[3];
int[] topCount = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
for (int start = 0, end; start < ids.length; start = end) {
end = start + 1;
while (end < ids.length && ids[end] == ids[start]) {
end++;
}
int c = end - start;
if (c >= topCount[2]) {
continue;
}
int i = 2;
while (i > 0 && c < topCount[i - 1]) {
topId[i] = topId[i - 1];
topCount[i] = topCount[i - 1];
i--;
}
topId[i] = ids[start];
topCount[i] = c;
}
System.out.println((long) topId[0] * topId[1] * topId[2]);
}
}
Clojure
Clojure is a Lisp on the JVM. Its maps are immutable: assoc returns a new
map and leaves the old one alone. Its sort hands the work to Java, and its
numbers are boxed java.lang.Long objects. Each program below is a script of
top-level forms, run with clojure -M file.clj on Clojure 1.12.7 (CLI
1.12.7.1681) and OpenJDK 27.0.1.1. None of them needs a library beyond
Clojure itself. Before the first run, the CLI had put Clojure 1.12.7,
spec.alpha 0.5.238 and core.specs.alpha 0.4.74 into ~/.m2 once. No run
downloads anything. Every program reads the input on stdin and prints one
number. Timings are best of 11 runs on an Apple M2 Pro, startup included, on
the shared timing input: 100,000 IDs drawn from 50,000 distinct values. Three
runs of the timing command differed by up to 39 ms for the same step, so I
only compare gaps larger than that. The numbers below are from the run with
the least load on the machine.
Startup is most of every number here. I timed these baselines the same way:
| program | time |
|---|---|
a Java Hello class | 22.2 ms |
java -cp ... clojure.main hello.clj | 245.3 ms |
clojure -M hello.clj | 260.9 ms |
clojure -M on (when true (println 42)) | 352.9 ms |
The last line is the surprise. Starting Clojure costs about 220 ms on top of
the JVM, and the clojure launcher script adds about 15 ms. Then
the first macro in a file costs another 90 ms.
Part 1: the three most common
Step 1: a beginner’s version
slurp reads all of stdin into a string, clojure.string/split-lines cuts
it into lines, and parse-long turns each line into a number. A map can’t be
changed in place, so reduce passes it along: each step returns a new map
with one count added. sort-by val orders the entries by count, lowest
first, so reverse puts the highest first. apply * multiplies the three
keys.
;; Step 1: what a beginner writes. Read all of stdin, split it into lines,
;; parse each line, count with reduce and an if, sort the map's entries by
;; count, and multiply the first three keys.
(require '[clojure.string :as str])
(def ids (map parse-long (str/split-lines (slurp *in*))))
(def counts
(reduce (fn [counts id]
(if (contains? counts id)
(assoc counts id (inc (get counts id)))
(assoc counts id 1)))
{}
ids))
;; sort-by sorts ascending, so reverse puts the highest counts first
(def top3 (take 3 (reverse (sort-by val counts))))
(println (apply * (map key top3)))
Step 2: smaller tools, same shape
Three swaps. (update counts id (fnil inc 0)) replaces the if: fnil
wraps inc so that a missing count, nil, starts at 0. sort-by takes >
as its comparator, so nothing needs reversing. And reduce * multiplies,
which is the fold apply * was doing anyway.
;; Step 2: smaller tools, same shape. update with (fnil inc 0) replaces the
;; if, sort-by takes > as its comparator so nothing needs reversing, and
;; reduce with * multiplies.
(require '[clojure.string :as str])
(def ids (map parse-long (str/split-lines (slurp *in*))))
(def counts
(reduce (fn [counts id] (update counts id (fnil inc 0)))
{}
ids))
(def top3 (take 3 (sort-by val > counts)))
(println (reduce * (map key top3)))
Step 3: frequencies
Counting is common enough to be a core function. frequencies returns a
map from each distinct item to its count.
;; Step 3: frequencies. Counting things is a core function: it returns a map
;; from each distinct item to how many times it appears.
(require '[clojure.string :as str])
(def counts (frequencies (map parse-long (str/split-lines (slurp *in*)))))
(def top3 (take 3 (sort-by val > counts)))
(println (reduce * (map key top3)))
Step 4: one pipeline
->> threads a value through a list of forms, inserting it as the last
argument of each. The program reads top to bottom, in the order the data
flows.
;; Step 4: one pipeline. The ->> macro threads each result in as the last
;; argument of the next form, so the program reads top to bottom.
(require '[clojure.string :as str])
(->> (slurp *in*)
str/split-lines
(map parse-long)
frequencies
(sort-by val >)
(take 3)
(map key)
(reduce *)
println)
Step 5: don’t sort what you won’t use
Sorting 43,282 entries to read three is wasted work. One reduce over the
map keeps a vector of the best three entries so far, highest count first.
An entry that doesn’t beat the current third place costs one comparison.
;; Step 5: don't sort what you won't use. One reduce over the counts keeps
;; the three best entries seen so far, highest count first. Most entries
;; lose to the current third place and cost one comparison.
(require '[clojure.string :as str])
(defn keep-top3 [best entry]
(if (and (= 3 (count best))
(<= (val entry) (val (peek best))))
best
(->> (conj best entry)
(sort-by val >)
(take 3)
vec)))
(->> (slurp *in*)
str/split-lines
(map parse-long)
frequencies
(reduce keep-top3 [])
(map key)
(reduce *)
println)
Which one would I keep?
| step | what changed | timing input | picking three |
|---|---|---|---|
| 1 | reduce, assoc, reverse, sort-by | 453.1 ms | sort k: O(k log k) |
| 2 | update + fnil, sort-by val > | 470.9 ms | sort k: O(k log k) |
| 3 | frequencies (and no macros) | 365.1 ms | sort k: O(k log k) |
| 4 | ->> pipeline | 451.2 ms | sort k: O(k log k) |
| 5 | reduce keeping three | 452.4 ms | one pass: O(k) |
Step 4 is what a Clojure programmer writes, and the one I’d keep. Each line is one transformation, and every one of them is a core function. Step 5 is the right algorithm and the version for large k, but here it trades a readable line for a helper function and buys nothing measurable. Start-up is 270 to 360 ms of every row. No change to the code itself moved the time by more than the noise.
Part 2: the other end
Step 4 turned around. Without a comparator sort-by sorts ascending, so
the least common IDs come first:
;; Part 2, step 1: step 4 with the sort turned around. sort-by with no
;; comparator sorts ascending, so the least common IDs come first.
(require '[clojure.string :as str])
(->> (slurp *in*)
str/split-lines
(map parse-long)
frequencies
(sort-by val)
(take 3)
(map key)
(reduce *)
println)
And step 5 turned around, keeping the three smallest counts:
;; Part 2, step 2: step 5 turned around. One reduce keeps the three entries
;; with the smallest counts seen so far, lowest count first.
(require '[clojure.string :as str])
(defn keep-bottom3 [best entry]
(if (and (= 3 (count best))
(>= (val entry) (val (peek best))))
best
(->> (conj best entry)
(sort-by val)
(take 3)
vec)))
(->> (slurp *in*)
str/split-lines
(map parse-long)
frequencies
(reduce keep-bottom3 [])
(map key)
(reduce *)
println)
JavaScript
JavaScript gives a beginner two ways to count things: a plain object {} and
a Map. They look interchangeable here and they aren’t. One turns every key
into a string and lists integer keys in numeric order; the other keeps keys as
numbers in the order they arrived. The language’s sort also has a default
that surprises people with numbers. Every program below reads the input on
stdin and prints one number. Each file is complete, imports and all, and runs
with node part1_step1.mjs < input on Node 23.11.0 (V8 12.9).
Part 1: the three most common
Step 1: a beginner’s version
Read all of stdin as one string, split it into lines, count each ID in an
object with if/else, sort the [id, count] pairs that Object.entries returns
by count, and multiply the first three IDs.
// Step 1: what a beginner writes. Read all of stdin, split it into lines,
// count each ID in a plain object, sort the [id, count] pairs by count and
// multiply the first three IDs.
import fs from "fs";
const input = fs.readFileSync(0, "utf8");
const lines = input.trim().split("\n");
const counts = {};
for (const line of lines) {
const id = Number(line);
if (counts[id]) {
counts[id] = counts[id] + 1;
} else {
counts[id] = 1;
}
}
const entries = Object.entries(counts);
entries.sort((a, b) => b[1] - a[1]);
let result = 1;
for (let i = 0; i < 3; i++) {
result = result * entries[i][0];
}
console.log(result);
fs.readFileSync(0, "utf8") reads file descriptor 0, which is stdin. Node’s
documentation for readFileSync accepts a file name or a descriptor as its
first argument.
Step 2: a Map
A Map takes keys of any type and keeps them as they are, so the IDs stay
numbers. counts.get(id) returns undefined for an ID we haven’t seen, and
?? 0 (ES2020) turns that into a zero, so the if/else goes away. Spreading the
Map with [...counts] gives the same [id, count] pairs as before.
// Step 2: a Map instead of a plain object. Its keys stay numbers, and it
// iterates in the order the IDs first appeared.
import fs from "fs";
const input = fs.readFileSync(0, "utf8");
const lines = input.trim().split("\n");
const counts = new Map();
for (const line of lines) {
const id = Number(line);
counts.set(id, (counts.get(id) ?? 0) + 1);
}
const entries = [...counts];
entries.sort((a, b) => b[1] - a[1]);
let result = 1;
for (let i = 0; i < 3; i++) {
result = result * entries[i][0];
}
console.log(result);
Step 3: one chain
In a chain of array methods, map(Number) parses every line, sort ranks the
pairs, slice(0, 3) keeps three and reduce folds them into a product.
Destructuring in the parameters (([, a], [, b]), (product, [id])) names
the parts of each pair instead of indexing with [0] and [1]. The import
changes to node:fs, the explicit way to name a Node built-in module.
// Step 3: the same steps as one chain of array methods. map parses the
// lines, sort ranks the [id, count] pairs, slice keeps three and reduce
// multiplies them.
import { readFileSync } from "node:fs";
const ids = readFileSync(0, "utf8").trim().split("\n").map(Number);
const counts = new Map();
for (const id of ids) {
counts.set(id, (counts.get(id) ?? 0) + 1);
}
const result = [...counts]
.sort(([, a], [, b]) => b - a)
.slice(0, 3)
.reduce((product, [id]) => product * id, 1);
console.log(result);
Step 4: don’t sort what you won’t use
Sorting k entries to keep three is wasted work. One pass over the Map,
keeping the three best entries in a small sorted array, is O(k). findIndex
finds where a new entry belongs among at most three, splice inserts it and
pop drops whatever fell to fourth place.
// Step 4: sorting all k IDs to keep three is O(k log k). One pass over the
// Map that keeps the three best entries seen so far is O(k).
import { readFileSync } from "node:fs";
const ids = readFileSync(0, "utf8").trim().split("\n").map(Number);
const counts = new Map();
for (const id of ids) {
counts.set(id, (counts.get(id) ?? 0) + 1);
}
// top is kept sorted, most common first. A strict > puts a new entry after
// any entry with the same count, so the first ID seen wins a tie.
const top = [];
for (const entry of counts) {
const at = top.findIndex(([, count]) => entry[1] > count);
if (at !== -1) {
top.splice(at, 0, entry);
if (top.length > 3) top.pop();
} else if (top.length < 3) {
top.push(entry);
}
}
console.log(top.reduce((product, [id]) => product * id, 1));
Part 2: the other end
The first try is step 3’s chain with the comparison turned round, so the least common IDs come first:
// Part 2, step 1: step 3's chain with the comparison turned round, so the
// least common IDs come first.
import { readFileSync } from "node:fs";
const ids = readFileSync(0, "utf8").trim().split("\n").map(Number);
const counts = new Map();
for (const id of ids) {
counts.set(id, (counts.get(id) ?? 0) + 1);
}
const result = [...counts]
.sort(([, a], [, b]) => a - b)
.slice(0, 3)
.reduce((product, [id]) => product * id, 1);
console.log(result);
And the one-pass version keeps the three smallest counts instead, with <
where part 1 had >:
// Part 2, step 2: step 4's single pass, keeping the three smallest counts.
import { readFileSync } from "node:fs";
const ids = readFileSync(0, "utf8").trim().split("\n").map(Number);
const counts = new Map();
for (const id of ids) {
counts.set(id, (counts.get(id) ?? 0) + 1);
}
// bottom is kept sorted, least common first; the first ID seen wins a tie.
const bottom = [];
for (const entry of counts) {
const at = bottom.findIndex(([, count]) => entry[1] < count);
if (at !== -1) {
bottom.splice(at, 0, entry);
if (bottom.length > 3) bottom.pop();
} else if (bottom.length < 3) {
bottom.push(entry);
}
}
console.log(bottom.reduce((product, [id]) => product * id, 1));
Ruby
Ruby’s core library already has most of this puzzle in it. Its Hash keeps
keys in the order they arrived, Enumerable has a method that counts for you, and max_by takes a
count of how many winners you want. So the Ruby ladder is mostly about which
of those methods to reach for, and what each one does inside the interpreter.
Every program below reads the input on stdin and prints one number. Each file
is complete and runs with ruby part1_step1.rb < input on ruby 4.0.10.
Part 1: the three most common
Step 1: a beginner’s version
Read all of stdin, split it into lines, count each ID in a hash with if/else,
sort the [id, count] pairs with a comparison block, and multiply the first
three IDs.
# Step 1: what a beginner writes. Read all of stdin, split it into lines,
# count each ID in a hash with if/else, sort the [id, count] pairs by count
# with a comparison block, and multiply the first three IDs.
lines = STDIN.read.split("\n")
counts = {}
lines.each do |line|
id = line.to_i
if counts[id]
counts[id] += 1
else
counts[id] = 1
end
end
# highest count first
sorted = counts.sort { |a, b| b[1] <=> a[1] }
result = 1
sorted.first(3).each do |pair|
result *= pair[0]
end
puts result
counts.sort turns the hash into an array of [id, count] pairs and sorts
that. The block compares two pairs, and b[1] <=> a[1] puts the larger count
first.
Step 2: a default value
Hash.new(0) makes a hash that returns 0 for any key it doesn’t have, so the
if/else goes away and counts[id] += 1 works for new IDs too.
# Step 2: Hash.new(0) gives every missing key a default of 0, so the
# if/else disappears.
lines = STDIN.read.split("\n")
counts = Hash.new(0)
lines.each do |line|
counts[line.to_i] += 1
end
# highest count first
sorted = counts.sort { |a, b| b[1] <=> a[1] }
result = 1
sorted.first(3).each do |pair|
result *= pair[0]
end
puts result
Step 3: sort_by
sort_by takes a block that returns a sort key for one element. Negating the
count puts the most common IDs first. The block also unpacks the pair into
id and count, so the last loop reads |id, _count| instead of pair[0].
# Step 3: sort_by computes each pair's sort key once, where sort's block runs
# for every comparison. Negating the count puts the highest first.
lines = STDIN.read.split("\n")
counts = Hash.new(0)
lines.each do |line|
counts[line.to_i] += 1
end
sorted = counts.sort_by { |_id, count| -count }
result = 1
sorted.first(3).each do |id, _count|
result *= id
end
puts result
Step 4: tally
Counting the elements of a list is common enough that Enumerable has a method
for it. tally returns a hash from each distinct element to its count, so the
whole counting loop becomes one call, and reading the input becomes a
pipeline. split with no argument splits on any whitespace, and
map(&:to_i) converts each word.
# Step 4: Enumerable#tally is the whole counting loop. The input becomes a
# pipeline: split on whitespace, convert, count.
counts = STDIN.read.split.map(&:to_i).tally
sorted = counts.sort_by { |_id, count| -count }
result = 1
sorted.first(3).each do |id, _count|
result *= id
end
puts result
Step 5: the loop is a fold
map(&:first) keeps the IDs from the pairs. inject(:*) folds them with
*, starting from the first ID and multiplying in each next one. With that,
the whole thing reads left to right as count, sort, take three, multiply.
# Step 5: the multiplying loop is a fold. map(&:first) keeps the IDs and
# inject(:*) multiplies them together.
counts = STDIN.read.split.map(&:to_i).tally
puts counts.sort_by { |_id, count| -count }.first(3).map(&:first).inject(:*)
Step 6: don’t sort what you won’t use
Sorting 43,000 pairs to keep three is wasted work. max_by(3) returns the
three elements with the largest block values, largest first, without sorting
the rest. This is what I’d write.
# Step 6: max_by(3) picks the three largest counts without sorting all k of
# them.
counts = STDIN.read.split.map(&:to_i).tally
puts counts.max_by(3) { |_id, count| count }.map(&:first).inject(:*)
Part 2: the other end
Part 2 wants the three least common IDs. Sorting by the count itself, without the minus sign, puts them first:
# Part 2, step 1: step 5 sorted the other way round. Sorting by the count
# itself puts the least common IDs first.
counts = STDIN.read.split.map(&:to_i).tally
puts counts.sort_by { |_id, count| count }.first(3).map(&:first).inject(:*)
And min_by(3) is max_by(3)’s twin, with the same buffer of 12 and no full
sort:
# Part 2, step 2: min_by(3) is max_by(3)'s twin.
counts = STDIN.read.split.map(&:to_i).tally
puts counts.min_by(3) { |_id, count| count }.map(&:first).inject(:*)
Haskell
Haskell has no mutable dictionary in its standard library. The map type that
ships with GHC, Data.Map from the containers package, is an immutable
balanced binary tree. Inserting returns a new map and leaves the old one
alone. Values are lazy unless you ask otherwise, input arrives as a String
that is a linked list of characters, and sortBy is a lazy merge sort. All four of those show up in this ladder. Every
program below reads the input on stdin and prints one number; each file is
complete and compiles with ghc -O2 file.hs on GHC 9.14.1, using only
packages that come with GHC (base, containers 0.8, bytestring). No
cabal project is needed.
Part 1: the three most common
Step 1: a beginner’s version
Read all of stdin with getContents, split it with lines, and turn each line
into an Int with read. There is no loop that mutates a map, so a recursive
function passes the map along instead. Each call inserts one ID with
Map.insertWith (+) n 1, which adds 1 to an existing count or starts a new one
at 1. Then Map.toList gives (id, count) pairs, sortBy with a lambda puts
the highest count first, and the first three IDs are multiplied.
-- Step 1: what a beginner writes. getContents reads all of stdin as a String,
-- lines and read turn it into Ints, a recursive function counts them into a
-- Data.Map with insertWith, and sortBy with a lambda puts the highest count
-- first.
import Data.List (sortBy)
import qualified Data.Map as Map
count :: [Int] -> Map.Map Int Int -> Map.Map Int Int
count [] counts = counts
count (n : ns) counts = count ns (Map.insertWith (+) n 1 counts)
main :: IO ()
main = do
input <- getContents
let ids = map read (lines input) :: [Int]
counts = count ids Map.empty
sorted = sortBy (\(_, a) (_, b) -> compare b a) (Map.toList counts)
print (product (map fst (take 3 sorted)))
Step 2: let the library fold
Two swaps, as in the Python ladder. Map.fromListWith (+) takes a list of
(key, value) pairs and builds the map itself, combining the values of equal
keys with (+); a list comprehension turns each ID into (n, 1). And
sortOn (Down . snd) replaces the lambda. Down is a wrapper whose ordering
is the reverse of the value inside it, so sorting by Down count puts the
highest count first.
-- Step 2: two library swaps. Map.fromListWith builds the whole map from
-- (key, value) pairs, combining the values of equal keys with (+), and
-- sortOn (Down . snd) sorts by count, highest first, without a lambda.
import Data.List (sortOn)
import qualified Data.Map as Map
import Data.Ord (Down (..))
main :: IO ()
main = do
input <- getContents
let ids = map read (lines input) :: [Int]
counts = Map.fromListWith (+) [(n, 1 :: Int) | n <- ids]
sorted = sortOn (Down . snd) (Map.toList counts)
print (product (map fst (take 3 sorted)))
Step 3: Data.Map.Strict
Data.Map is lazy in its values. insertWith (+) on an existing key stores
the unevaluated expression 1 + old in the node, and the count is only
computed when the sort asks for it. Data.Map.Strict has the same Map type and the same functions, but forces every value before
it goes into the map. Only the import changes.
-- Step 3: Data.Map is lazy in its values, so every (+) on a count is stored as
-- an unevaluated thunk until the sort asks for it. Data.Map.Strict has the
-- same Map type and the same functions, but forces each value as it goes in.
-- Only the import changes.
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import Data.Ord (Down (..))
main :: IO ()
main = do
input <- getContents
let ids = map read (lines input) :: [Int]
counts = Map.fromListWith (+) [(n, 1 :: Int) | n <- ids]
sorted = sortOn (Down . snd) (Map.toList counts)
print (product (map fst (take 3 sorted)))
Step 4: IntMap
Data.Map works for any key with an Ord instance and compares keys at every
node. For Int keys, containers also has Data.IntMap, a big-endian
Patricia trie. Each node splits its keys on one bit, and a lookup follows the
bits of the key from the top down. The API is the same, so again only the
import changes.
-- Step 4: Data.Map is a balanced binary search tree that works for any Ord
-- key. For Int keys, Data.IntMap is a Patricia trie that branches on the
-- key's bits instead of comparing keys. Same API, different import.
import qualified Data.IntMap.Strict as IntMap
import Data.List (sortOn)
import Data.Ord (Down (..))
main :: IO ()
main = do
input <- getContents
let ids = map read (lines input) :: [Int]
counts = IntMap.fromListWith (+) [(n, 1 :: Int) | n <- ids]
sorted = sortOn (Down . snd) (IntMap.toList counts)
print (product (map fst (take 3 sorted)))
Step 5: ByteString
Steps 1 to 4 spend most of their time before the counting starts. A strict
ByteString holds the whole input as one block of bytes, and
BS.readInt parses an Int from the front of it and returns the rest.
unfoldr keeps calling it, after dropSpace skips the newline, until it
returns Nothing.
-- Step 5: String is a linked list of Char, and read is a general parser for
-- Haskell syntax. A strict ByteString holds the input as one block of bytes,
-- and readInt parses an Int from its front and returns the rest.
import qualified Data.ByteString.Char8 as BS
import qualified Data.IntMap.Strict as IntMap
import Data.List (sortOn, unfoldr)
import Data.Ord (Down (..))
readInts :: BS.ByteString -> [Int]
readInts = unfoldr (BS.readInt . BS.dropSpace)
main :: IO ()
main = do
input <- BS.getContents
let counts = IntMap.fromListWith (+) [(n, 1 :: Int) | n <- readInts input]
sorted = sortOn (Down . snd) (IntMap.toList counts)
print (product (map fst (take 3 sorted)))
Step 6: sortBy with comparing
sortOn f computes f x once for every element, pairs it with the element,
sorts the pairs, and strips the keys off again. That is worth it when f is
expensive. Down . snd is a field access and a wrapper, so
sortBy (comparing (Down . snd)) compares the pairs directly.
comparing f x y is compare (f x) (f y).
-- Step 6: sortOn pairs every element with its sort key before sorting, which
-- pays off when the key is expensive to compute. Down . snd is cheap, so
-- sortBy (comparing (Down . snd)) compares the pairs directly.
import qualified Data.ByteString.Char8 as BS
import qualified Data.IntMap.Strict as IntMap
import Data.List (sortBy, unfoldr)
import Data.Ord (Down (..), comparing)
readInts :: BS.ByteString -> [Int]
readInts = unfoldr (BS.readInt . BS.dropSpace)
main :: IO ()
main = do
input <- BS.getContents
let counts = IntMap.fromListWith (+) [(n, 1 :: Int) | n <- readInts input]
top = take 3 (sortBy (comparing (Down . snd)) (IntMap.toList counts))
print (product (map fst top))
Part 2: the other end
The least common IDs are the same sort with the order turned around:
comparing snd without Down.
-- Part 2: step 6 with the order turned around. comparing snd sorts by count,
-- smallest first.
import qualified Data.ByteString.Char8 as BS
import qualified Data.IntMap.Strict as IntMap
import Data.List (sortBy, unfoldr)
import Data.Ord (comparing)
readInts :: BS.ByteString -> [Int]
readInts = unfoldr (BS.readInt . BS.dropSpace)
main :: IO ()
main = do
input <- BS.getContents
let counts = IntMap.fromListWith (+) [(n, 1 :: Int) | n <- readInts input]
low = take 3 (sortBy (comparing snd) (IntMap.toList counts))
print (product (map fst low))
OCaml
OCaml gives you two counting structures out of the box. Hashtbl is a mutable
hash table, and Map is an immutable balanced tree you get by applying a
functor to a key module. It also gives you compare, one function that orders
almost any two values of the same type. Both the table and compare are
polymorphic, and that is where the interesting questions in this ladder are.
Every program below reads the input on stdin and prints one number; each file
is complete and compiles on its own with ocamlopt from OCaml 5.5.2 (the
Homebrew build, no flambda), standard library only.
Part 1: the three most common
Step 1: a beginner’s version
Read lines with input_line until it raises End_of_file, count in a
Hashtbl with find_opt and replace, fold the table into a list of
(id, count) pairs, sort it by count with List.sort, and take the first
three with a pattern.
let () =
let counts = Hashtbl.create 16 in
(try
while true do
let n = int_of_string (String.trim (input_line stdin)) in
match Hashtbl.find_opt counts n with
| Some c -> Hashtbl.replace counts n (c + 1)
| None -> Hashtbl.add counts n 1
done
with End_of_file -> ());
let pairs = Hashtbl.fold (fun id c acc -> (id, c) :: acc) counts [] in
let sorted = List.sort (fun (_, a) (_, b) -> compare b a) pairs in
match sorted with
| (a, _) :: (b, _) :: (c, _) :: _ -> Printf.printf "%d\n" (a * b * c)
| _ -> failwith "need at least three different IDs"
The match at the end is how OCaml says “the first three elements”. The
compiler checks that the patterns cover every list, so the short-list case has
to be written down, here as a failwith.
Step 2: read everything, then pipe
In_channel.input_all (OCaml 4.14) reads the whole input into one string, and
String.split_on_char cuts it into lines. From there the program is a
pipeline with |>. List.filter_map with int_of_string_opt turns each line
into Some n or drops it, which also takes care of the empty string after the
last newline. Counting and sorting don’t change.
let () =
let counts = Hashtbl.create 16 in
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.iter (fun n ->
match Hashtbl.find_opt counts n with
| Some c -> Hashtbl.replace counts n (c + 1)
| None -> Hashtbl.add counts n 1);
let pairs = Hashtbl.fold (fun id c acc -> (id, c) :: acc) counts [] in
let sorted = List.sort (fun (_, a) (_, b) -> compare b a) pairs in
match sorted with
| (a, _) :: (b, _) :: (c, _) :: _ -> Printf.printf "%d\n" (a * b * c)
| _ -> failwith "need at least three different IDs"
Step 3: a pure Map
Idiomatic OCaml prefers immutable data. Map.Make (Int) builds a map module
for int keys, and List.fold_left threads the map through the IDs. Each
IntMap.update returns a new map with one count changed, and nothing is
mutated. IntMap.bindings returns the pairs sorted by key.
module IntMap = Map.Make (Int)
let () =
let counts =
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.fold_left
(fun m n ->
IntMap.update n
(function None -> Some 1 | Some c -> Some (c + 1))
m)
IntMap.empty
in
let pairs = IntMap.bindings counts in
let sorted = List.sort (fun (_, a) (_, b) -> compare b a) pairs in
match sorted with
| (a, _) :: (b, _) :: (c, _) :: _ -> Printf.printf "%d\n" (a * b * c)
| _ -> failwith "need at least three different IDs"
Step 4: say the key type
Back to a hash table, but a typed one. Hashtbl.Make (Int) builds a table
module for int keys that tests equality with Int.equal. The generic table
from step 2 compares keys with polymorphic compare, because it has to work
for any type. The sort says Int.compare for the same reason. Everything else
is step 2.
module IntTbl = Hashtbl.Make (Int)
let () =
let counts = IntTbl.create 16 in
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.iter (fun n ->
match IntTbl.find_opt counts n with
| Some c -> IntTbl.replace counts n (c + 1)
| None -> IntTbl.add counts n 1);
let pairs = IntTbl.fold (fun id c acc -> (id, c) :: acc) counts [] in
let sorted = List.sort (fun (_, a) (_, b) -> Int.compare b a) pairs in
match sorted with
| (a, _) :: (b, _) :: (c, _) :: _ -> Printf.printf "%d\n" (a * b * c)
| _ -> failwith "need at least three different IDs"
Step 5: don’t sort what you won’t use
Sorting 43,282 pairs to read three of them is wasted work. One fold over the table keeps the three highest counts seen so far in a tuple, best first, and pattern matching takes the tuple apart. An experienced OCaml programmer would write it this way. There is no list and no sort, and the accumulator is a plain value that the fold passes along.
module IntTbl = Hashtbl.Make (Int)
(* Insert (id, c) into the three highest counts seen so far, highest first. *)
let top3 id c (((_, c1) as x1), ((_, c2) as x2), ((_, c3) as x3)) =
if c > c1 then ((id, c), x1, x2)
else if c > c2 then (x1, (id, c), x2)
else if c > c3 then (x1, x2, (id, c))
else (x1, x2, x3)
let () =
let counts = IntTbl.create 16 in
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.iter (fun n ->
match IntTbl.find_opt counts n with
| Some c -> IntTbl.replace counts n (c + 1)
| None -> IntTbl.add counts n 1);
let empty = (0, 0) in
let (a, _), (b, _), (c, _) = IntTbl.fold top3 counts (empty, empty, empty) in
Printf.printf "%d\n" (a * b * c)
Part 2: the other end
The first try is step 4 with the comparison turned around, least common first:
module IntTbl = Hashtbl.Make (Int)
let () =
let counts = IntTbl.create 16 in
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.iter (fun n ->
match IntTbl.find_opt counts n with
| Some c -> IntTbl.replace counts n (c + 1)
| None -> IntTbl.add counts n 1);
let pairs = IntTbl.fold (fun id c acc -> (id, c) :: acc) counts [] in
let sorted = List.sort (fun (_, a) (_, b) -> Int.compare a b) pairs in
match sorted with
| (a, _) :: (b, _) :: (c, _) :: _ -> Printf.printf "%d\n" (a * b * c)
| _ -> failwith "need at least three different IDs"
And the one-pass version keeps the three smallest counts instead. Every count
in the table is at least 1, so the starting value uses max_int as a count
that any real one beats:
module IntTbl = Hashtbl.Make (Int)
(* Insert (id, c) into the three lowest counts seen so far, lowest first. *)
let bottom3 id c (((_, c1) as x1), ((_, c2) as x2), ((_, c3) as x3)) =
if c < c1 then ((id, c), x1, x2)
else if c < c2 then (x1, (id, c), x2)
else if c < c3 then (x1, x2, (id, c))
else (x1, x2, x3)
let () =
let counts = IntTbl.create 16 in
In_channel.input_all stdin
|> String.split_on_char '\n'
|> List.filter_map (fun line -> int_of_string_opt (String.trim line))
|> List.iter (fun n ->
match IntTbl.find_opt counts n with
| Some c -> IntTbl.replace counts n (c + 1)
| None -> IntTbl.add counts n 1);
let empty = (0, max_int) in
let (a, _), (b, _), (c, _) =
IntTbl.fold bottom3 counts (empty, empty, empty)
in
Printf.printf "%d\n" (a * b * c)
Elixir
Elixir runs on the BEAM, Erlang’s virtual machine, and its data is immutable:
Map.put doesn’t change a map, it returns a new one. So a counting loop is
a fold that threads the map through every step, and the Enum module, the
|> pipe and the Erlang standard library underneath do most of the work.
The surprises are in the VM. A map with up to 32 keys is a different data
structure from a bigger one. The sort is a merge sort written in Erlang. And
starting the VM takes about 226 ms, most of the run time of the faster
versions. Every program
below is a script that reads the input on stdin and prints one number. Each
file is complete and runs with elixir part1_step1.exs < input on Elixir
1.20.5 and Erlang/OTP 29.1.3.
Part 1: the three most common
Step 1: a beginner’s version
Read all of stdin, split it into words, turn each word into an integer, and
count with Enum.reduce: the accumulator starts as an empty map, and each ID
produces a new map with its count one higher. Map.get(acc, id, 0) returns 0
for an ID that isn’t there yet. Then sort the {id, count} pairs by count,
highest first, take three, and multiply them with another reduce.
# Step 1: what a beginner writes. Read all of stdin, split it into words,
# count each ID in a map with Map.get and Map.put inside Enum.reduce, sort
# the {id, count} pairs by count, take three and multiply them.
input = IO.read(:stdio, :eof)
ids =
input
|> String.split()
|> Enum.map(fn word -> String.to_integer(word) end)
counts =
Enum.reduce(ids, %{}, fn id, acc ->
Map.put(acc, id, Map.get(acc, id, 0) + 1)
end)
top =
counts
|> Enum.sort_by(fn {_id, count} -> count end, :desc)
|> Enum.take(3)
result = Enum.reduce(top, 1, fn {id, _count}, product -> product * id end)
IO.puts(result)
Iterating over a map gives {key, value} tuples, which is why the sort and
the last reduce take the pair apart with {_id, count} and {id, _count}.
The underscore marks a value the function doesn’t use.
Step 2: Map.update
Map.update(acc, id, 1, &(&1 + 1)) stores 1 for a new ID and otherwise
calls the function on the current count. &(&1 + 1) is the short form of
fn count -> count + 1 end. The same capture syntax turns
fn word -> String.to_integer(word) end into &String.to_integer/1, a
reference to the function by name and arity.
# Step 2: Map.update/4 is "get, change, put" in one call. The 1 is stored
# for a new ID; for one already there, the function adds one to its count.
input = IO.read(:stdio, :eof)
ids =
input
|> String.split()
|> Enum.map(&String.to_integer/1)
counts =
Enum.reduce(ids, %{}, fn id, acc ->
Map.update(acc, id, 1, &(&1 + 1))
end)
top =
counts
|> Enum.sort_by(fn {_id, count} -> count end, :desc)
|> Enum.take(3)
result = Enum.reduce(top, 1, fn {id, _count}, product -> product * id end)
IO.puts(result)
Step 3: Enum.frequencies
Counting is common enough that Enum has a function for it since Elixir
1.10. Enum.frequencies/1 returns the same map as the reduce, so counting
becomes one more stage of the input pipeline.
# Step 3: Enum.frequencies/1 is the whole counting reduce.
input = IO.read(:stdio, :eof)
counts =
input
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
top =
counts
|> Enum.sort_by(fn {_id, count} -> count end, :desc)
|> Enum.take(3)
result = Enum.reduce(top, 1, fn {id, _count}, product -> product * id end)
IO.puts(result)
Step 4: read stdin in chunks
IO.read(:stdio, :eof) and IO.binread(:stdio, :eof) both return all of
stdin as one string. This step changes only that one call.
# Step 4: IO.binread/2 reads stdin in 4 KB chunks. IO.read/2 asks for it one
# line at a time. Nothing else changes.
input = IO.binread(:stdio, :eof)
counts =
input
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
top =
counts
|> Enum.sort_by(fn {_id, count} -> count end, :desc)
|> Enum.take(3)
result = Enum.reduce(top, 1, fn {id, _count}, product -> product * id end)
IO.puts(result)
Step 5: one pipeline
|> passes the value on its left as the first argument of the call on its
right, so the whole program becomes one pipeline that reads top to bottom.
&elem(&1, 1) picks the count out of an {id, count} tuple, and
Enum.product/1 (Elixir 1.12) replaces the multiplying reduce.
# Step 5: one pipeline. elem/2 picks the count or the ID out of each pair,
# and Enum.product/1 is the multiplying reduce.
IO.binread(:stdio, :eof)
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
|> Enum.sort_by(&elem(&1, 1), :desc)
|> Enum.take(3)
|> Enum.map(&elem(&1, 0))
|> Enum.product()
|> IO.puts()
Step 6: don’t sort what you won’t use
Sorting 43,282 pairs to keep three is wasted work in theory. This version
makes one pass over the counts and keeps the three largest {count, id}
tuples in a list, largest first. Most pairs lose to the current third place
after one comparison. The rare winner is added and the list of four is sorted
and cut back to three.
# Step 6: don't sort what you won't use. One pass over the counts keeps the
# three largest {count, id} pairs, largest first. Tuples compare element by
# element, so the count decides and the ID only breaks ties.
IO.binread(:stdio, :eof)
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
|> Enum.reduce([], fn {id, count}, top ->
case top do
# Most pairs lose to the current third place: one comparison.
[_, _, third] when {count, id} <= third -> top
_ -> [{count, id} | top] |> Enum.sort(:desc) |> Enum.take(3)
end
end)
|> Enum.map(&elem(&1, 1))
|> Enum.product()
|> IO.puts()
Part 2: the other end
Part 2 wants the three least common IDs. Sorting :asc instead of :desc
puts them first:
# Part 2, step 1: step 5 sorted the other way round. :asc puts the least
# common IDs first.
IO.binread(:stdio, :eof)
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
|> Enum.sort_by(&elem(&1, 1), :asc)
|> Enum.take(3)
|> Enum.map(&elem(&1, 0))
|> Enum.product()
|> IO.puts()
And the one-pass version flips every comparison to keep the three smallest
{count, id} tuples:
# Part 2, step 2: step 6 with the comparisons flipped. It keeps the three
# smallest {count, id} pairs, smallest first.
IO.binread(:stdio, :eof)
|> String.split()
|> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
|> Enum.reduce([], fn {id, count}, bottom ->
case bottom do
[_, _, third] when {count, id} >= third -> bottom
_ -> [{count, id} | bottom] |> Enum.sort(:asc) |> Enum.take(3)
end
end)
|> Enum.map(&elem(&1, 1))
|> Enum.product()
|> IO.puts()
Erlang
Erlang has no loops and no variables that change. A map update returns a new
map, and counting is a recursive function or a fold. Much of the standard
library is written in Erlang, lists:sort included, so you can read how it
works in the language you call it from. It also has a fixed order between all
terms, which lets you sort tuples without a comparison function, and a
mutable table (ETS) for when immutability gets in the way. Every program
below is an escript: a source file with a #!/usr/bin/env escript line and a
main/1 function, run with escript part1_step1.erl < input on Erlang/OTP
29.1.3. Each reads the input on stdin and prints one number.
Part 1: the three most common
Step 1: a beginner’s version
Read stdin one line at a time with io:get_line until it returns eof. Each
line becomes an integer with list_to_integer(string:trim(Line)). There is no
loop that mutates a map, so count/1 calls itself with a new map: maps:find
says whether the ID is there, Counts#{Id := N + 1} updates an existing key
and Counts#{Id => 1} adds a new one. Then maps:to_list gives
{Id, Count} pairs, lists:sort with a fun puts the highest count first,
lists:sublist takes three, and lists:foldl multiplies them.
#!/usr/bin/env escript
%% Step 1: what a beginner writes. Read stdin one line at a time with
%% io:get_line, count each ID in a map with maps:find and a case, sort the
%% {Id, Count} pairs with a comparison fun, and multiply the first three IDs.
main(_) ->
Counts = count(#{}),
Sorted = lists:sort(fun({_, A}, {_, B}) -> A >= B end, maps:to_list(Counts)),
Top = lists:sublist(Sorted, 3),
Product = lists:foldl(fun({Id, _}, Acc) -> Id * Acc end, 1, Top),
io:format("~p~n", [Product]).
count(Counts) ->
case io:get_line("") of
eof ->
Counts;
Line ->
case string:trim(Line) of
"" ->
count(Counts);
Text ->
Id = list_to_integer(Text),
case maps:find(Id, Counts) of
{ok, N} -> count(Counts#{Id := N + 1});
error -> count(Counts#{Id => 1})
end
end
end.
Step 2: update_with
maps:update_with(Id, Fun, 1, Counts) applies Fun to the current count, or
stores 1 when the ID is new. The maps:find and its case go away.
#!/usr/bin/env escript
%% Step 2: maps:update_with/4 replaces the maps:find and the case. It applies
%% the fun to the old count, or stores the initial value 1 for a new ID.
main(_) ->
Counts = count(#{}),
Sorted = lists:sort(fun({_, A}, {_, B}) -> A >= B end, maps:to_list(Counts)),
Top = lists:sublist(Sorted, 3),
Product = lists:foldl(fun({Id, _}, Acc) -> Id * Acc end, 1, Top),
io:format("~p~n", [Product]).
count(Counts) ->
case io:get_line("") of
eof ->
Counts;
Line ->
case string:trim(Line) of
"" ->
count(Counts);
Text ->
Id = list_to_integer(Text),
count(maps:update_with(Id, fun(N) -> N + 1 end, 1, Counts))
end
end.
Step 3: read everything at once
io:setopts([binary]) makes standard input return binaries instead of lists
of characters. read_all/1 asks for 65,536 characters at a time with io:get_chars and
joins the chunks into one binary. binary:split with [global, trim_all]
cuts it at every newline and drops empty parts, and binary_to_integer
converts each line. With all the IDs in a list, counting becomes a
lists:foldl.
#!/usr/bin/env escript
%% Step 3: read all of stdin at once as a binary, split it into lines with
%% binary:split and convert each with binary_to_integer. With the IDs in a
%% list, counting becomes a lists:foldl.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Ids = [binary_to_integer(Line) || Line <- Lines],
Counts = lists:foldl(fun(Id, Acc) -> maps:update_with(Id, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Ids),
Sorted = lists:sort(fun({_, A}, {_, B}) -> A >= B end, maps:to_list(Counts)),
Top = lists:sublist(Sorted, 3),
Product = lists:foldl(fun({Id, _}, Acc) -> Id * Acc end, 1, Top),
io:format("~p~n", [Product]).
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
Step 4: term order instead of a fun
Erlang defines an order between any two terms, and tuples compare element by
element. Swapping each pair to {Count, Id} means plain lists:sort orders
them by count, then by ID, with no fun at all. lists:reverse puts the
largest first.
#!/usr/bin/env escript
%% Step 4: no comparison fun. Swap each pair to {Count, Id}: Erlang compares
%% tuples element by element, so plain lists:sort orders them by count (then
%% by ID), and lists:reverse puts the largest first.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Ids = [binary_to_integer(Line) || Line <- Lines],
Counts = lists:foldl(fun(Id, Acc) -> maps:update_with(Id, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Ids),
Sorted = lists:reverse(lists:sort([{Count, Id} || {Id, Count} <- maps:to_list(Counts)])),
Top = lists:sublist(Sorted, 3),
Product = lists:foldl(fun({_, Id}, Acc) -> Id * Acc end, 1, Top),
io:format("~p~n", [Product]).
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
Step 5: don’t sort what you won’t use
Sorting 43,000 pairs to keep three is wasted work. maps:fold visits every
key once, and top3/2 keeps the three largest {Count, Id} tuples seen so
far, comparing whole tuples with >. Its clauses try the first place, then
the second, then the third, and most tuples fall through to the last clause
after three comparisons. A pattern match pulls the three IDs out of the
result. This is the version I would write.
#!/usr/bin/env escript
%% Step 5: don't sort what you won't use. One maps:fold keeps the three
%% largest {Count, Id} tuples seen so far, and a pattern match takes the IDs
%% out of the result.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Ids = [binary_to_integer(Line) || Line <- Lines],
Counts = lists:foldl(fun(Id, Acc) -> maps:update_with(Id, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Ids),
Empty = {0, 0},
{{_, A}, {_, B}, {_, C}} =
maps:fold(fun(Id, Count, Top) -> top3({Count, Id}, Top) end,
{Empty, Empty, Empty}, Counts),
io:format("~p~n", [A * B * C]).
top3(X, {First, Second, _}) when X > First -> {X, First, Second};
top3(X, {First, Second, _}) when X > Second -> {First, X, Second};
top3(X, {First, Second, Third}) when X > Third -> {First, Second, X};
top3(_, Top) -> Top.
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
Step 6: a mutable table
This step is a contrast, and step 5 stays the version I would write. ETS is Erlang’s built-in term storage:
a hash table in the runtime, outside the process heap, that you change in
place. ets:update_counter(Counts, Id, 1, {Id, 0}) adds 1 to the count, and
inserts {Id, 0} first when the ID is new. ets:foldl replaces maps:fold.
#!/usr/bin/env escript
%% Step 6: a contrast, not an improvement. Count in an ETS table instead of a
%% map: ets:update_counter/4 adds 1 to the count in place, or inserts
%% {Id, 0} first when the ID is new. ets:foldl replaces maps:fold.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Counts = ets:new(counts, [set]),
lists:foreach(fun(Line) ->
Id = binary_to_integer(Line),
ets:update_counter(Counts, Id, 1, {Id, 0})
end, Lines),
Empty = {0, 0},
{{_, A}, {_, B}, {_, C}} =
ets:foldl(fun({Id, Count}, Top) -> top3({Count, Id}, Top) end,
{Empty, Empty, Empty}, Counts),
io:format("~p~n", [A * B * C]).
top3(X, {First, Second, _}) when X > First -> {X, First, Second};
top3(X, {First, Second, _}) when X > Second -> {First, X, Second};
top3(X, {First, Second, Third}) when X > Third -> {First, Second, X};
top3(_, Top) -> Top.
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
Part 2: the other end
Part 2 wants the three least common IDs. lists:keysort(2, ...) sorts the
{Id, Count} pairs by their second element, smallest first, so no swap and
no reverse are needed. The first three pairs come out in a pattern match:
#!/usr/bin/env escript
%% Part 2, step 1: lists:keysort(2, ...) sorts the {Id, Count} pairs by their
%% second element, least common first, without a fun. A pattern match takes
%% the first three IDs.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Ids = [binary_to_integer(Line) || Line <- Lines],
Counts = lists:foldl(fun(Id, Acc) -> maps:update_with(Id, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Ids),
[{A, _}, {B, _}, {C, _} | _] = lists:keysort(2, maps:to_list(Counts)),
io:format("~p~n", [A * B * C]).
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
And the one-pass fold keeps the three smallest tuples instead. It needs a
starting value larger than any {Count, Id}, and the term order provides
one. infinity is an atom, every atom sorts after every number, so
{infinity, none} is larger than any tuple of two numbers.
#!/usr/bin/env escript
%% Part 2, step 2: the one-pass fold from step 5, keeping the three smallest
%% {Count, Id} tuples. The starting value {infinity, none} is larger than any
%% {Count, Id}, because in Erlang's term order every atom sorts after every
%% number.
main(_) ->
ok = io:setopts([binary]),
Lines = binary:split(read_all([]), <<"\n">>, [global, trim_all]),
Ids = [binary_to_integer(Line) || Line <- Lines],
Counts = lists:foldl(fun(Id, Acc) -> maps:update_with(Id, fun(N) -> N + 1 end, 1, Acc) end,
#{}, Ids),
Empty = {infinity, none},
{{_, A}, {_, B}, {_, C}} =
maps:fold(fun(Id, Count, Bottom) -> bottom3({Count, Id}, Bottom) end,
{Empty, Empty, Empty}, Counts),
io:format("~p~n", [A * B * C]).
bottom3(X, {First, Second, _}) when X < First -> {X, First, Second};
bottom3(X, {First, Second, _}) when X < Second -> {First, X, Second};
bottom3(X, {First, Second, Third}) when X < Third -> {First, Second, X};
bottom3(_, Bottom) -> Bottom.
read_all(Chunks) ->
case io:get_chars("", 65536) of
eof -> iolist_to_binary(lists:reverse(Chunks));
Chunk -> read_all([Chunk | Chunks])
end.
Prolog
Prolog has no loops and no variables that change once bound. A program is a
set of facts and rules, repetition is recursion, and the system keeps a
database of facts that a program can add to at run time. It also defines one
order over all terms, so sort/2 needs no comparison function, and the sort
is written in C. Each program below is a script run with
swipl part1_step1.pl < input on SWI-Prolog 11.0.1. The line
:- initialization(main, main). tells SWI-Prolog to call main once the
file is loaded and then exit, with a non-zero status if main fails. Every
file reads the input on stdin and prints one number.
Much of what follows is SWI-Prolog rather than ISO Prolog. The ISO standard
has sort/2, keysort/2, assertz/1 and findall/3. msort/2, sort/4,
strings, number_string/2 and the libraries used here are not ISO, and the
notes say so where it matters.
Part 1: the three most common
Step 1: a beginner’s version
Prolog’s own answer to “store some data” is the database. read_ids reads a
line with read_line_to_string, converts it with number_string, and adds a
fact id(57) with assertz. Then setof collects the distinct IDs, and for
each one aggregate_all(count, id(N), C) counts its facts. keysort sorts
the Count-Id pairs by count, smallest first, so reverse puts the largest
first, and a pattern takes the first three.
% Step 1: what a beginner writes. Read stdin one line at a time, store
% every ID as a fact id(N), find the distinct IDs with setof/3, count each
% one with aggregate_all/3, sort Count-Id pairs with keysort/2 and reverse
% them, and multiply the first three IDs.
:- use_module(library(readutil)).
:- use_module(library(aggregate)).
:- use_module(library(lists)).
:- initialization(main, main).
:- dynamic id/1.
main :-
read_ids,
setof(N, id(N), Ids),
findall(C-N, (member(N, Ids), aggregate_all(count, id(N), C)), Pairs),
keysort(Pairs, Ascending),
reverse(Ascending, [_-A, _-B, _-C|_]),
Product is A * B * C,
format("~d~n", [Product]).
read_ids :-
read_line_to_string(user_input, Line),
( Line == end_of_file
-> true
; number_string(N, Line),
assertz(id(N)),
read_ids
).
[_-A, _-B, _-C|_] is a list pattern: it matches any list with at least three
pairs and binds the three IDs. Product is A * B * C is where arithmetic
happens. = would only build the term A*B*C.
Step 2: count by sorting
The database is global state, and a list is the Prolog way. read_ids/1 now
returns the IDs as a list. msort sorts it and keeps duplicates, so equal
IDs end up next to each other, and clumped turns each run into an
Id-Count pair: clumped([43,43,57], P) gives P = [43-2, 57-1].
transpose_pairs from library(pairs) swaps every pair to Count-Id and
keysorts the result.
% Step 2: count by sorting. Collect the IDs in a list instead of the
% database, sort it with msort/2 (which keeps duplicates), and let
% clumped/2 turn each run of equal IDs into an Id-Count pair.
% transpose_pairs/2 swaps them to Count-Id and keysorts them.
:- use_module(library(readutil)).
:- use_module(library(lists)).
:- use_module(library(pairs)).
:- initialization(main, main).
main :-
read_ids(Ids),
msort(Ids, Sorted),
clumped(Sorted, Counts),
transpose_pairs(Counts, Ascending),
reverse(Ascending, [_-A, _-B, _-C|_]),
Product is A * B * C,
format("~d~n", [Product]).
read_ids(Ids) :-
read_line_to_string(user_input, Line),
( Line == end_of_file
-> Ids = []
; number_string(N, Line),
Ids = [N|Rest],
read_ids(Rest)
).
Step 3: sort/4
SWI-Prolog’s sort/4 sorts on one argument of each term, in an order you
name. sort(2, @>=, Counts, Ranked) sorts the Id-Count pairs on the count,
largest first, and keeps pairs with equal counts. The swap and the reverse
go away.
% Step 3: sort/4. sort(2, @>=, Counts, Ranked) sorts the Id-Count pairs on
% their second argument, largest first, and keeps pairs with equal counts.
% No swap and no reverse.
:- use_module(library(readutil)).
:- use_module(library(lists)).
:- initialization(main, main).
main :-
read_ids(Ids),
msort(Ids, Sorted),
clumped(Sorted, Counts),
sort(2, @>=, Counts, [A-_, B-_, C-_|_]),
Product is A * B * C,
format("~d~n", [Product]).
read_ids(Ids) :-
read_line_to_string(user_input, Line),
( Line == end_of_file
-> Ids = []
; number_string(N, Line),
Ids = [N|Rest],
read_ids(Rest)
).
There is no step that keeps the top three in one pass, as other tabs have.
The whole of reading, msort and clumped takes 71.1 ms, and step 3 with
the sort takes 78.5, so there are about 7 ms to win.
Step 4: read everything at once
read_string(user_input, _, Text) reads all of stdin into one string.
split_string(Text, "\n", " \t\r", Lines) cuts it at newlines and strips
white space from each piece, exclude(==(""), ...) drops the empty piece
after the last newline, and maplist(number_string, Ids, NonEmpty) converts
the rest. The recursive reader goes away. This is the version I would write.
% Step 4: read everything at once. read_string/3 takes all of stdin,
% split_string/4 cuts it at newlines and strips white space, and
% number_string/2 converts each piece. The empty piece after the last
% newline is dropped before converting.
:- use_module(library(apply)).
:- use_module(library(lists)).
:- initialization(main, main).
main :-
read_string(user_input, _, Text),
split_string(Text, "\n", " \t\r", Lines),
exclude(==(""), Lines, NonEmpty),
maplist(number_string, Ids, NonEmpty),
msort(Ids, Sorted),
clumped(Sorted, Counts),
sort(2, @>=, Counts, [A-_, B-_, C-_|_]),
Product is A * B * C,
format("~d~n", [Product]).
Step 5: an AVL tree
This step is a contrast. Step 4 stays the one I would write. library(assoc) is a balanced binary
tree (AVL) keyed on the standard order of terms. foldl threads it through
the list: count/3 looks the ID up with get_assoc and stores the new count
with put_assoc, which returns a new tree and leaves the old one as it was.
assoc_to_list returns the pairs in key order.
% Step 5, a contrast: count in an AVL tree from library(assoc) instead of
% sorting. foldl/4 threads the tree through the list of IDs; each ID is
% looked up with get_assoc/3 and stored with put_assoc/4.
:- use_module(library(apply)).
:- use_module(library(assoc)).
:- use_module(library(lists)).
:- initialization(main, main).
main :-
read_string(user_input, _, Text),
split_string(Text, "\n", " \t\r", Lines),
exclude(==(""), Lines, NonEmpty),
maplist(number_string, Ids, NonEmpty),
empty_assoc(Empty),
foldl(count, Ids, Empty, Assoc),
assoc_to_list(Assoc, Counts),
sort(2, @>=, Counts, [A-_, B-_, C-_|_]),
Product is A * B * C,
format("~d~n", [Product]).
count(Id, Assoc0, Assoc) :-
( get_assoc(Id, Assoc0, C0)
-> C is C0 + 1
; C = 1
),
put_assoc(Id, Assoc0, C, Assoc).
Part 2: the other end
Part 2 wants the three least common IDs. transpose_pairs already sorts
Count-Id pairs smallest count first, so the three IDs are at the front and
step 2’s reverse goes away:
% Part 2, step 1: transpose_pairs/2 sorts Count-Id pairs smallest count
% first, so the three least common IDs are at the front. No reverse.
:- use_module(library(readutil)).
:- use_module(library(lists)).
:- use_module(library(pairs)).
:- initialization(main, main).
main :-
read_ids(Ids),
msort(Ids, Sorted),
clumped(Sorted, Counts),
transpose_pairs(Counts, [_-A, _-B, _-C|_]),
Product is A * B * C,
format("~d~n", [Product]).
read_ids(Ids) :-
read_line_to_string(user_input, Line),
( Line == end_of_file
-> Ids = []
; number_string(N, Line),
Ids = [N|Rest],
read_ids(Rest)
).
And step 4 with the order flipped: sort(2, @=<, ...) puts the smallest
counts first and keeps equal ones.
% Part 2, step 2: step 4 of part 1 with the order flipped. sort(2, @=<, ...)
% puts the smallest counts first and keeps equal counts.
:- use_module(library(apply)).
:- use_module(library(lists)).
:- initialization(main, main).
main :-
read_string(user_input, _, Text),
split_string(Text, "\n", " \t\r", Lines),
exclude(==(""), Lines, NonEmpty),
maplist(number_string, Ids, NonEmpty),
msort(Ids, Sorted),
clumped(Sorted, Counts),
sort(2, @=<, Counts, [A-_, B-_, C-_|_]),
Product is A * B * C,
format("~d~n", [Product]).
BQN
BQN is an array language. Its functions are single glyphs that work on whole
lists at once, and an expression is read from right to left: ×´ 3 ↑ ⍒ c
grades c from largest to smallest, takes the first three of that, and
multiplies them together. A beginner coming from Python or C tends to write
loops anyway, with a dictionary and a block run once per element. This ladder
starts there and swaps each loop for a primitive, until the counting and the
selecting are four glyphs. Every program reads stdin with •FLines "/dev/stdin" (a list of lines), converts each line with •ParseFloat, and
prints one number with •Show. They run with bqn file.bqn on CBQN, the C
implementation of BQN, at commit 2bf102f (2026-11-22). Under each program
there is a plain-English reading of every glyph it uses.
Part 1: the three most common
Step 1: a dictionary and a loop
BQN has a hash map, •HashMap, a mutable object with Get and Set. With
it the Python version translates almost line by line: count each ID in the
map, pair every count with its ID, sort the pairs, and multiply the IDs of the
first three.
# Count with a hash map, like a Python dict
ids ← •ParseFloat¨ •FLines "/dev/stdin"
counts ← ⟨⟩ •HashMap ⟨⟩
{ 𝕩 counts.Set 1 + 0 counts.Get 𝕩 }¨ ids
pairs ← (counts.Values @) ⋈¨ (counts.Keys @)
top ← 3 ↑ ∨ pairs
•Show ×´ 1⊑¨ top
How to read it:
←defines a name.#starts a comment.•FLines "/dev/stdin"is the list of input lines.•ParseFloat¨applies•ParseFloatto each of them;¨(Each) is the loop.⟨⟩ •HashMap ⟨⟩makes an empty map: no keys on the left, no values on the right.⟨⟩is an empty list.{ ... }¨ idsruns the block once per ID, and inside it𝕩is that ID.0 counts.Get 𝕩returns the stored count, or the left argument 0 if the ID is new.1 +adds one, and𝕩 counts.Set ...stores the result under the ID.counts.Values @andcounts.Keys @return the two lists. Those functions ignore their argument, so@(the null character) is a placeholder.⋈¨pairs them element by element intocount‿idlists, and∨sorts them in descending order: by count first, then by ID.3 ↑takes the first three pairs.1⊑¨picks item 1 (the ID, counting from 0) out of each pair.×´folds multiplication over what is left.
Step 2: Classify and Group
The array way to count starts by giving each distinct value a small number.
⊐ (Classify) does that, and ⊔ (Group) collects the positions that share a
number. The lengths of those groups are the counts. The loop and the map are
gone; the selection is still step 1’s sorted pairs.
# Count with Classify and Group instead of a hash map
ids ← •ParseFloat¨ •FLines "/dev/stdin"
uniq ← ⍷ ids
counts ← ≠¨ ⊔ ⊐ ids
top ← 3 ↑ ∨ counts ⋈¨ uniq
•Show ×´ 1⊑¨ top
How to read it:
⍷ ids(Deduplicate) lists the distinct IDs in the order they first appear.⊐ ids(Classify) replaces every ID with the position of that ID in⍷ ids: the first distinct ID becomes 0, the next new one 1, and so on. For3‿1‿3‿0‿3‿1it gives0‿1‿0‿2‿0‿1(‿joins numbers into a list).⊔(Group) on that list returns, for each class number, the list of positions where it occurs:⟨⟨0,2,4⟩, ⟨1,5⟩, ⟨3⟩⟩.≠¨takes the length (≠) of each group:3‿2‿1. Those counts line up withuniq, because both are in first-appearance order.
Step 3: grade instead of sorting pairs
Sorting pairs moves whole pairs around. ⍒ (Grade Down) moves no values and
returns the indices that would put the counts in descending order. Three of
those indices pick the three IDs out of uniq.
# Grade the counts instead of sorting pairs
ids ← •ParseFloat¨ •FLines "/dev/stdin"
uniq ← ⍷ ids
counts ← ≠¨ ⊔ ⊐ ids
•Show ×´ uniq ⊏˜ 3 ↑ ⍒ counts
How to read it:
⍒ counts(Grade Down) is a permutation of0,1, …, k−1: the index of the largest count first.3 ↑keeps the first three of those indices.uniq ⊏˜ ...selects fromuniqat those indices.⊏(Select) takes the indices on the left and the list on the right;˜(Swap) flips the arguments so the list can be written first.×´multiplies the three IDs.
Step 4: count by value
The IDs are natural numbers, so they can be used as positions directly.
/⁼ counts how often each number 0, 1, 2, … up to the largest ID occurs,
and the result’s index is the ID itself. Grade Down then returns the three
IDs directly, and there is no uniq list to select from.
# Count by value: the index of each count is the ID itself
ids ← •ParseFloat¨ •FLines "/dev/stdin"
counts ← /⁼ ids
•Show ×´ 3 ↑ ⍒ counts
How to read it:
/(Indices) turns a list of counts into a list of positions, each repeated that many times:/ 1‿2‿0‿3is0‿1‿1‿3‿3‿3.⁼(Undo) gives the inverse of a function./⁼goes back from positions to counts:/⁼ 3‿1‿3‿0‿3‿1is1‿2‿0‿3(one 0, two 1s, no 2, three 3s).⍒ countslists positions with the largest count first, and a position is an ID.
Step 5: no names at all
Step 4 is a pipeline: parse, count, grade, take three, multiply. BQN can write a pipeline as a function without naming its argument (“tacit” or point-free style), and the program becomes one definition and one line.
# The same pipeline as one tacit function
Top3 ← ×´ 3 ↑ ⍒∘(/⁼)
•Show Top3 •ParseFloat¨ •FLines "/dev/stdin"
How to read it:
⍒∘(/⁼)is a composition:∘(Atop) means “apply/⁼, then⍒to the result”. The parentheses keep⁼attached to/.3 ↑ F, inside a function definition, is a train: a number on the left of a function means “use 3 as the left argument of↑, andF 𝕩as the right one”.×´ Gis a two-function train: applyG, then×´to its result.- So
Top3 𝕩is×´ 3 ↑ ⍒ /⁼ 𝕩. Names that start with a capital letter hold functions in BQN;Top3is called like a primitive.
Part 2: the other end
The least common IDs come from Grade Up, ⍋, in place of Grade Down. With
Classify and Group every count is at least 1, so step 3 needs only that one
glyph changed:
# Least common: Grade Up instead of Grade Down
ids ← •ParseFloat¨ •FLines "/dev/stdin"
uniq ← ⍷ ids
counts ← ≠¨ ⊔ ⊐ ids
•Show ×´ uniq ⊏˜ 3 ↑ ⍋ counts
⍋ counts (Grade Up) lists indices from the smallest count to the largest;
everything else reads as in step 3.
With /⁼, every number up to the largest ID has an entry, and the ones that
never occur have a count of 0, which would always come first. So the IDs that
do occur are picked out before grading:
# Count by value, then keep only the IDs that occur
ids ← •ParseFloat¨ •FLines "/dev/stdin"
counts ← /⁼ ids
present ← / 0 < counts
•Show ×´ 3 ↑ present ⊏˜ ⍋ present ⊏ counts
How to read it:
0 < countsis a list of 1s where the count is positive and 0s elsewhere./(Indices) on that list of 0s and 1s returns the positions of the 1s: the IDs that occur.present ⊏ countsselects their counts,⍋grades them from smallest up, andpresent ⊏˜turns the three positions back into IDs.
K
K is an array language from the line of Arthur Whitney’s Ks. Most primitives
are one ASCII character with two meanings, one with a single argument on its
right and one with arguments on both sides, and an expression is read from
right to left: */3#>#'=ids groups ids, counts each group, grades the
counts from largest to smallest, takes three and multiplies them. These
programs are written for ngn/k, one dialect of K, built from source at commit
b9eeb91 (2026-07-21) and run with k file.k. Other Ks spell some of this
differently, so where a note mentions another dialect it says which. Every
program reads stdin with {x,1:0}/"" (step 1 explains why it isn’t the
shorter 0:0) and prints one number. Under each program there is a
plain-English reading of every symbol it uses.
Part 1: the three most common
Step 1: a dictionary and a fold
A beginner coming from Python reaches for a dictionary and a loop. K has both:
x!y builds a dictionary from a list of keys and a list of values, and a
fold walks the IDs and adds 1 to each one’s entry. Then the keys are put in
order of their counts, and the first three are multiplied.
/ read all of stdin, one chunk at a time, until a read comes back empty
s:{x,1:0}/""
/ split into lines, parse each line as an int
ids:`I$"\n"\s
/ count: a fold that adds 1 to the ID's entry in a dictionary
counts:{x[y]+:1;x}/[(!0)!!0;ids]
/ the IDs, ordered by count from largest to smallest
top:(!counts)@>.counts
top[0]*top[1]*top[2]
How to read it:
- A line that starts with
/is a comment.x:yassigns. {...}is a function; inside itxandyare its first and second arguments.x,yjoins two lists.1:0reads bytes from file descriptor 0, stdin, and returns them as a string.f/xwith a one-argumentfis converge: it appliesfagain and again, starting fromx, until the result stops changing. Here it starts from the empty string""and appends one chunk of input per round. When stdin is exhausted, a round appends nothing and the loop stops."\n"\ssplitssat newlines.`I$parses each piece as an integer.!0is an empty list (!ncounts 0, 1, …, n−1), so(!0)!!0is an empty dictionary: no keys, no values.f/[d;ids]with a two-argumentfis a fold. It callsfwith the dictionary so far asxand the next ID asy, and passes the result on.x[y]+:1adds 1 to the entry foryin place.;separates expressions, and the last one,x, is what the function returns.!countsis the list of keys and.countsthe list of values.>(grade down) returns the positions that put the values in descending order, and@picks the keys at those positions.top[0]*top[1]*top[2]is evaluated right to left, astop[0]*(top[1]*top[2]).
Step 2: group, then count each
=x (group) returns a dictionary from each distinct value to the positions
where it occurs. The number of positions is the count, so the fold and the
dictionary updates go away.
s:{x,1:0}/""
ids:`I$"\n"\s
/ group: ID -> the positions where it occurs; count each group
counts:#'=ids
top:(!counts)@>.counts
top[0]*top[1]*top[2]
How to read it:
=ids(group) on3 1 3 0 3 1is the dictionary3 1 0!(0 2 4;1 5;,3): 3 occurs at positions 0, 2 and 4, and so on.(a;b;c)is a list of lists, and,3a list with one item.#xis the length ofx, and'(each) applies it to every value of the dictionary.#'=idsis the dictionary3 1 0!3 2 1.- The keys come out in the order each ID first appears.
Step 3: grade the dictionary
Grading a dictionary orders it by its values and returns the keys. Steps 1 and 2 split the dictionary into keys and values only to put them back together.
s:{x,1:0}/""
ids:`I$"\n"\s
counts:#'=ids
/ grading a dictionary orders it by value and returns the keys
top:>counts
top[0]*top[1]*top[2]
How to read it:
>countslists the keys ofcountsfrom the largest count to the smallest.top[0]is the most common ID.
Step 4: one line
3# takes the first three and */ multiplies them, so the names can go.
s:{x,1:0}/""
ids:`I$"\n"\s
/ take three, multiply over them
*/3#>#'=ids
How to read it:
- Right to left:
=idsgroups,#'counts each group,>grades the counts,3#takes the first three keys, and*/multiplies them. f/with a two-argument verb on its left is over: it puts*between the items,a*b*c.
Step 5: no names at all
A sequence of verbs with no argument on the right is a function in K: it applies the verbs right to left to whatever it is given. The whole solution becomes a name for that function, applied to the parsed input.
top3:*/3#>#'=:
top3`I$"\n"\{x,1:0}/""
How to read it:
=:is group used as a one-argument function. The colon forces that reading. Without it,=at the end of the train is the two-argument equal, andtop3 xreturns a function still waiting for its other argument.top3:*/3#>#'=:names the composition of the five steps.top3 xis*/3#>#'=x.top3`I$"\n"\{x,1:0}/""reads, splits, parses and passes the result totop3.
Step 6: count by value
The IDs are natural numbers below 100,000, so they can be positions in a list. One list of zeros, with 1 added at each ID’s position, holds every count, and its grade lists IDs directly. This is the K version of the C ladder’s plain array.
s:{x,1:0}/""
ids:`I$"\n"\s
/ count by value: c[i] is how often the ID i occurs
c:@[(1+|/ids)#0;ids;+;1]
/ the positions of the three largest counts are the IDs
*/3#>c
How to read it:
|/idsis the largest ID (|is maximum,/puts it between all the items).(1+|/ids)#0is a list of that many plus one zeros.@[c;i;+;1](amend) returnscwith+1applied at every position ini. A position that appears five times inigets 1 added five times.>clists positions from the largest count down, and a position is an ID.
Part 2: the other end
The least common IDs come from < (grade up) in place of >. Group only
lists IDs that occur, so every count is at least 1:
s:{x,1:0}/""
ids:`I$"\n"\s
/ grade up instead of down: least common first
*/3#<#'=ids
< lists keys from the smallest count to the largest; the rest reads as in
step 4. The same change in the tacit version:
bottom3:*/3#<#'=:
bottom3`I$"\n"\{x,1:0}/""
Counting by value gives every number up to the largest ID a slot, and the IDs that never occur have a count of 0, which would always come first. So the IDs that do occur are picked out before grading:
s:{x,1:0}/""
ids:`I$"\n"\s
c:@[(1+|/ids)#0;ids;+;1]
/ only the IDs that occur: where the count is above zero
p:&0<c
*/3#p@<c p
How to read it:
0<cis 1 where the count is above zero and 0 elsewhere.&(where) returns the positions of the 1s: the IDs that occur.c pindexescwithp(juxtaposition is indexing),<grades those counts from the smallest up, andp@turns the three positions back into IDs.
APL
APL is an array language. Each function is one glyph, every function works
on whole arrays, and an expression is read from right to left. ×/3↑U[⍒C]
grades the counts C from largest to smallest (⍒), uses that order to
index the IDs U, takes the first three (3↑) and multiplies them (×/).
These programs run on GNU APL 2.0, a free interpreter of the ISO 13751
standard (“APL with nested arrays”) whose manual measures itself against
IBM’s APL2 throughout. Each file is a script run with apl --script --noSV -f file.apl; --noSV stops it from starting its shared-variable server. Two
pieces repeat in every file. The function READ pulls all of stdin in as
bytes, and the answer is printed with ⍞←⍕, followed by )OFF to
leave the interpreter. Under each program there is a plain-English reading
of every glyph it uses.
Part 1: the three most common
Step 1: a loop and two lists
A beginner coming from Python writes a dictionary. APL has none, so the
loop keeps two lists side by side, the IDs seen so far (U) and their counts
(C), and looks each new ID up with ⍳. Then the pairs go into a two-column
matrix, the rows are sorted by the count column, and the first three IDs are
multiplied.
⍝ Count in a loop, the way a dictionary would
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
∇COUNT;I;N
⍝ U: the IDs seen so far, C: how often each one occurred
U←⍬ ⋄ C←⍬ ⋄ I←1
L:→(I>⍴X)/0
N←U⍳X[I]
→(N≤⍴U)/OLD
U←U,X[I] ⋄ C←C,1
→NEXT
OLD:C[N]←C[N]+1
NEXT:I←I+1 ⋄ →L
∇
X←⍎⎕UCS READ
COUNT
⍝ one row per ID: (ID, count), sorted by count, largest first
M←U,[1.5]C
M←M[⍒M[;2];]
⍞←⍕M[1;1]×M[2;1]×M[3;1]
)OFF
How to read it:
⍝starts a comment, and←assigns a value to a name.∇opens and closes a defined function, APL’s classic way to write a multi-line function.∇Z←READ;Bsays: the function is calledREAD, its result isZ, andBis a local variable.COUNThas no result; it sets the global namesUandC.L:,OLD:andNEXT:are labels.→jumps to a line.→(I>⍴X)/0reads “ifI>⍴X, jump to line 0”, which leaves the function.cond/0is0when the condition is 1 and an empty list when it is 0, and a jump to an empty list does nothing.⋄separates two statements on one line.1000000 ⎕FIO[6] 0is C’sfreadon file handle 0 (stdin), up to a million bytes, returned as a list of byte values.⎕FIOis GNU APL’s file library; names starting with⎕are system functions.⍬is the empty list,⍴Xthe length ofX, and⍴⍴Bthe length of the shape, which is 0 for a single number.Z,Bjoins two lists.⎕UCSturns byte values into characters, and⍎runs that text as APL. A line of numbers is an APL list literal, so⍎returns the IDs as one numeric listX.U⍳X[I](Index Of) is the position of theI-th ID inU, or1+⍴Uif it isn’t there yet. Indexes start at 1.C[N]←C[N]+1adds one in place.U,[1.5]Cputs the two lists side by side as the columns of a k×2 matrix.M[;2]is its second column,⍒(Grade Down) gives the row numbers from the largest count to the smallest, andM[...;]reorders the rows.⍕formats the number as text, and⍞←prints text without a line end.)OFFleaves the interpreter. It prints a line end before it exits (Command.cc, line 1618), and that ends the output line.
Step 2: grade the counts, index the IDs
The matrix of pairs is not needed. ⍒C already gives the order of the
counts, and the same positions index U, because U and C line up. Then
3↑ takes three IDs and ×/ multiplies them.
⍝ Grade the counts and index the IDs with the result
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
∇COUNT;I;N
⍝ U: the IDs seen so far, C: how often each one occurred
U←⍬ ⋄ C←⍬ ⋄ I←1
L:→(I>⍴X)/0
N←U⍳X[I]
→(N≤⍴U)/OLD
U←U,X[I] ⋄ C←C,1
→NEXT
OLD:C[N]←C[N]+1
NEXT:I←I+1 ⋄ →L
∇
X←⍎⎕UCS READ
COUNT
⍞←⍕×/3↑U[⍒C]
)OFF
How to read the new line:
⍒C(Grade Down) is a list of positions intoC, largest count first.U[⍒C]reorders the IDs the same way.3↑(Take) keeps the first three.×/is Reduce with multiply, so×/a b cisa×b×c.
Step 3: no loop
The array way to count compares each distinct ID with the whole list at
once. ∪X lists the distinct IDs, and for each of them ⍵=X is a list of
1s and 0s with a 1 wherever that ID occurs. Its sum is the count.
⍝ No loop: compare each distinct ID with the whole list at once
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
X←⍎⎕UCS READ
U←∪X
C←{+/⍵=X}¨U
⍞←⍕×/3↑U[⍒C]
)OFF
How to read it:
∪X(Unique) is the distinct IDs in the order they first appear.{...}is a lambda (a “direct function”);⍵is its argument.⍵=Xcompares one ID with every element ofX, giving 0s and 1s.+/adds them up.¨(Each) applies the lambda to each distinct ID. TheXinside the lambda is the globalX.
Step 4: sort, then cut into runs
Sorting puts equal IDs next to each other, and then each ID’s count is the
length of its run. Partitioned enclose (⊂ with a left argument)
cuts a list into pieces wherever the left argument goes up, so a running sum
of “a new run starts here” marks gives one piece per run.
⍝ Sort, then cut the sorted list into runs of equal IDs
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
X←⍎⎕UCS READ
S←X[⍋X]
B←1,(1↓S)≠¯1↓S
G←(+\B)⊂S
⍞←⍕×/3↑(↑¨G)[⍒≢¨G]
)OFF
How to read it:
⍋X(Grade Up) gives the positions ofXin ascending order, andX[⍋X]isXsorted.1↓Sdrops the first element and¯1↓Sthe last, so(1↓S)≠¯1↓Scompares each element with the one before it.1,puts a 1 in front, soBhas a 1 wherever a new run starts. For43 43 57 57 57 76it is1 0 1 0 0 1.+\Bis a running sum, here1 1 2 2 2 3: the run number of each element.(+\B)⊂S(Partitioned Enclose) makes a nested list with one item per run, here(43 43) (57 57 57) (76).≢¨Gis the length (Tally) of each run, and↑¨Gthe first element (First) of each, which is its ID.
Step 5: flat run lengths
Step 4 builds one small list per run. The same counts come from the positions where the runs start, because each run ends where the next one begins. Two flat lists of integers replace the nested one.
⍝ Sort, then measure the runs from where they start
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
X←⍎⎕UCS READ
S←X[⍋X]
P←⍸1,(1↓S)≠¯1↓S
C←(1↓P,1+⍴S)-P
⍞←⍕×/3↑S[P[⍒C]]
)OFF
How to read it:
⍸(Where) gives the positions of the 1s, so⍸ 1 0 1 0 0 1is1 3 6.Pis where each run starts.P,1+⍴Sadds the position just past the end.1↓drops its first element, and subtractingPgives the length of each run,2 3 1in the example.P[⍒C]is the start of each run, longest run first, andS[...]turns those positions into IDs.
Part 2: the other end
The least common IDs come from Grade Up, ⍋, in place of Grade Down. Every
count is at least 1, so nothing else changes. First on step 2’s loop:
⍝ Least common: Grade Up instead of Grade Down
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
∇COUNT;I;N
⍝ U: the IDs seen so far, C: how often each one occurred
U←⍬ ⋄ C←⍬ ⋄ I←1
L:→(I>⍴X)/0
N←U⍳X[I]
→(N≤⍴U)/OLD
U←U,X[I] ⋄ C←C,1
→NEXT
OLD:C[N]←C[N]+1
NEXT:I←I+1 ⋄ →L
∇
X←⍎⎕UCS READ
COUNT
⍞←⍕×/3↑U[⍋C]
)OFF
And on step 5’s run lengths:
⍝ Least common, from the run lengths of the sorted list
∇Z←READ;B
⍝ all of stdin as a vector of bytes, read 1 MB at a time;
⍝ at end of input ⎕FIO[6] returns a scalar instead of a vector
Z←⍬
L:B←1000000 ⎕FIO[6] 0
→(0=⍴⍴B)/0
Z←Z,B
→L
∇
X←⍎⎕UCS READ
S←X[⍋X]
P←⍸1,(1↓S)≠¯1↓S
C←(1↓P,1+⍴S)-P
⍞←⍕×/3↑S[P[⍋C]]
)OFF
⍋C (Grade Up) lists positions from the smallest count to the largest; the
rest reads as before.
Uiua
Uiua is an array language like BQN and APL, with one difference that shapes
every line. There are no variables inside an expression, only a stack. Code
runs from right to left. Each glyph is a function that takes its arguments
off the top of the stack and pushes its results back, so /×↙3⍖ x pushes
x, grades it (⍖), takes the first three (↙3) and multiplies them
(/×). The value just to the right of a function is its first argument. A
beginner coming from Python still reaches for a map and a loop, so this
ladder starts there and swaps each piece for a primitive until the program is
one line. Every program reads all of stdin with &rs ∞ 0, splits it into
lines and parses each one with ⊜⋕⊸≠@\n, and prints one number with &p.
They run with uiua run --no-format file.ua on Uiua 0.19.1. Without that
flag, uiua run first reformats the file in place, lining up the ←
arrows. Under each program there is a plain-English reading of every
glyph and of how the stack moves.
Part 1: the three most common
Step 1: a map and a fold
Uiua has a hash map: an ordinary array that carries a set of keys, with
get, insert and has on top. With it the Python version translates line
by line: count each ID in a map, pair every count with its ID, sort the
pairs, multiply the IDs of the first three.
# Count with a map, then sort [count id] rows
Input ← &rs ∞ 0
Ids ← ⊜⋕ ⊸≠@\n Input
Bump ← insert ⊸⟜(+1 ⬚0get)
Counts ← ∧Bump Ids []
Pairs ← ⍉ ˜⊟ °map Counts
Sorted ← ⇌ ⍆ Pairs
&p /× ≡⊣ ↙3 Sorted
How to read it:
Name ← codebinds a name. When the code needs no arguments (Input,Ids,Counts) it runs once and the name holds its value. When it needs arguments (Bumpneeds two) the name becomes a function. Names are capitalised because the parser can mistake an all-lowercase name for the name of a built-in glyph.#starts a comment.&rs ∞ 0: right to left, push0(the handle of stdin), push∞, then&rs(read to string) takes the count∞, meaning “until the end”, and the handle, and pushes the whole input as one string.⊜⋕ ⊸≠@\n Input: push the string, push@\n(the newline character).≠compares the newline with every character and gives a mask of 1s, with 0s at the newlines.⊸(by) keeps≠’s last argument, the string, on the stack under the mask.⊜(partition) cuts the string into the runs where the mask is 1 and applies⋕(parse) to each run. Result: a list of numbers.Bumpis called with an ID on top of the stack and the map under it.getlooks up the ID in the map;⬚0(fill) makes it return 0 instead of failing when the ID is new.+1adds one.⟜(on) keeps the function’s first argument, the ID, on top of its result, and⊸(by) keeps its last argument, the map, underneath. The stack is now ID, new count, map, which is exactly whatinserttakes: key, value, map.∧Bump Ids []: push[], an empty array, which works as an empty map; pushIds.∧(fold) callsBumponce per ID, with the ID on top and the map so far under it, and the map it returns becomes the next one.°map Counts:°(un) runs a function backwards.°mapsplits a map into its keys (on top) and its values.⊟(couple) makes a two-row array of its two arguments, and˜(backward) swaps them, so the values come first.⍉(transpose) turns two rows of k numbers into k rows of[count id].⍆sorts the rows ascending, by count and then by ID;⇌(reverse) puts the largest first.↙3takes three rows,≡⊣takes the last item (⊣) of each row (≡, rows): the IDs./×folds multiplication over them, and&pprints the result with a newline.
Step 2: classify and group
The array way to count starts by giving each distinct value a small number.
⊛ (classify) does that, and ⊕ (group) collects the IDs that share a
number and applies a function to each group. With ⧻ (length) as that
function, the groups become counts. The selection is still step 1’s sorted
pairs.
# Count with classify and group instead of a map
Ids ← ⊜⋕ ⊸≠@\n &rs ∞ 0
Uniq ← ◴ Ids
Counts ← ⊕⧻ ⊛ Ids Ids
Pairs ← ⍉ ⊟ Counts Uniq
&p /× ≡⊣ ↙3 ⇌ ⍆ Pairs
How to read it:
◴ Ids(deduplicate) lists the distinct IDs in the order they first appear.⊛ Ids(classify) replaces every ID with the position of that ID in◴ Ids:⊛ [57 57 55 57 76]is[0 0 1 0 2].⊕⧻ ⊛ Ids Ids: pushIds, pushIdsagain and classify the top copy.⊕takes the class numbers (top) and the IDs under them, groups the IDs by class and applies⧻to each group:⊕⧻on the example above gives[3 1 1]. The counts line up withUniq, because both are in first-appearance order.⊟ Counts Uniqcouples the two lists with the counts first, so no˜is needed this time.
Step 3: grade instead of sorting pairs
Sorting pairs moves whole rows around. ⍖ (fall) moves nothing: it returns
the indices that would put the counts in descending order, and three of those
pick the IDs out of Uniq.
# Grade the counts instead of sorting pairs
Ids ← ⊜⋕ ⊸≠@\n &rs ∞ 0
Uniq ← ◴ Ids
Counts ← ⊕⧻ ⊛ Ids Ids
&p /× ↙3 ⊏ ⍖ Counts Uniq
How to read it:
- Push
Uniq, thenCountson top of it. ⍖ Counts(fall) is a permutation of 0, 1, …, k − 1, the index of the largest count first.⊏(select) takes those indices (its first argument, on top) and picks the matching items ofUniq(its second).↙3keeps the first three IDs and/×multiplies them.
Step 4: count by value
The IDs are natural numbers, so they can serve as positions. °⊚ counts how
often each number 0, 1, 2, … up to the largest ID occurs, and the index of
each count is the ID itself. ⍖ then returns IDs directly, and there is no
Uniq to select from.
# Count by value: un-where makes the index of each count the ID itself
Ids ← ⊜⋕ ⊸≠@\n &rs ∞ 0
&p /× ↙3 ⍖ °⊚ Ids
How to read it:
⊚(where) turns a list of counts into positions, each repeated that many times:⊚ [1 2 0 3]is[0 1 1 3 3 3].°⊚(un where) goes back from positions to counts:°⊚ [3 1 3 0 3 1]is[1 2 0 3](one 0, two 1s, no 2, three 3s).⍖lists positions with the largest count first, and a position is an ID.
Step 5: no names
Step 4 is a pipeline, and in Uiua a pipeline needs no names: functions take their arguments from the stack, so nothing has to be bound. Without the one binding the program is a single line.
# No names: one line, read right to left
&p /×↙3⍖°⊚ ⊜⋕⊸≠@\n &rs ∞ 0
How to read it, right to left: read stdin (&rs ∞ 0), split it at newlines
and parse each line (⊜⋕⊸≠@\n), count by value (°⊚), grade descending
(⍖), take three (↙3), multiply (/×), print (&p). Each glyph takes the
one result before it, so the stack never holds more than two values. Spaces
are optional; the formatter keeps them where they separate stages.
Part 2: the other end
The least common IDs come from ⍏ (rise) in place of ⍖. With classify and
group every count is at least 1, so step 3 needs only that one glyph changed:
# Least common: rise instead of fall
Ids ← ⊜⋕ ⊸≠@\n &rs ∞ 0
Uniq ← ◴ Ids
Counts ← ⊕⧻ ⊛ Ids Ids
&p /× ↙3 ⊏ ⍏ Counts Uniq
⍏ Counts lists indices from the smallest count to the largest; everything
else reads as in step 3.
With °⊚, every number up to the largest ID has an entry, and the ones that
never occur have a count of 0, which would always come first. So the IDs that
do occur are picked out before grading:
# Count by value, then keep only the IDs that occur
Counts ← °⊚ ⊜⋕ ⊸≠@\n &rs ∞ 0
Present ← ⊚ >0 Counts
&p /× ↙3 ⊏ ⍏ ⊏ Present Counts Present
How to read it:
>0 Countsis a mask: 1 where the count is greater than 0. (> 0 xasks whetherxis greater than 0; the first argument is the right-hand side.)⊚(where) on a mask returns the positions of its 1s: the IDs that occur.- In the last line the stack holds
Present,Counts,Present, top first.⊏selects the counts of the present IDs,⍏grades them from the smallest up, and the second⊏turns those positions back into IDs from thePresentunderneath.
Unix shell
The shell has no map type and no sort function to call. It has programs, and
a pipe to connect them. So this ladder is about choosing which program does
which part of the job: sort and uniq for counting, head, paste and bc
for picking and multiplying, and finally awk, which is a small language of its
own. Every script below is a complete POSIX sh script that reads the input
on stdin and prints one number. On this Mac, /bin/sh runs bash 3.2.57,
sort reports 2.3-Apple (201) (it is FreeBSD’s sort), and awk reports
awk version 20200816 (Brian Kernighan’s awk, as Apple builds it). Times are
for 100,000 IDs drawn from 50,000 values, best of 11 runs on an Apple M2 Pro,
startup included.
Part 1: the three most common
Step 1: a beginner’s version
sort | uniq -c | sort -rn | head -3 is one of the best-known pipelines in
Unix. sort puts equal IDs next to each other, uniq -c collapses each run
of equal lines into one line prefixed by its length, sort -rn orders those
lines by that count, largest first, and head -3 keeps three. awk '{print $2}'
cuts out the ID. A beginner then multiplies in a shell loop with $((...)).
#!/bin/sh
# Count with sort and uniq -c, sort by count, keep three IDs,
# then multiply them in a shell loop.
top=$(sort | uniq -c | sort -rn | head -3 | awk '{print $2}')
result=1
for id in $top; do
result=$((result * id))
done
echo "$result"
Step 2: the product is a pipeline stage too
The loop and the variable can go. paste -s joins all the lines it reads into
one line, with the separators from -d between them, so the three IDs become
57*43*76. bc evaluates that expression. Now the script is one pipeline from
input to answer, which is the shell’s own idiom.
#!/bin/sh
# The product is one more stage of the pipeline: paste joins the three
# IDs with '*' and bc evaluates the expression.
sort | uniq -c | sort -rn | head -3 | awk '{print $2}' | paste -sd'*' - | bc
Step 3: compare bytes
One added line, export LC_ALL=C, makes the script three times faster. My
locale is en_CA.UTF-8, and in it sort compares lines the way a
dictionary would. The C locale makes sort compare raw bytes. The lines here
are digits and spaces, so only the speed changes.
#!/bin/sh
# Step 2 in the C locale: sort and uniq compare bytes, not characters.
export LC_ALL=C
sort | uniq -c | sort -rn | head -3 | awk '{print $2}' | paste -sd'*' - | bc
Step 4: let awk finish the job
The tail of the pipeline was four programs: head, awk to cut the ID,
paste and bc. One awk program can do all four. It multiplies as it reads
and stops after the third line.
#!/bin/sh
# One awk does the work of head, the field cut, paste and bc,
# and exits after the third line.
export LC_ALL=C
sort | uniq -c | sort -rn |
awk '{ p = (NR == 1) ? $2 : p * $2 } NR == 3 { print p; exit }'
Step 5: one awk program
awk has associative arrays, so it can count without sorting. n[$1]++ adds
one to the count for this ID, and a missing element starts out empty, which
counts as 0. In the END block, one pass over the array keeps the three
largest counts seen so far. That is O(n + k), and the memory holds k IDs
instead of n lines.
#!/bin/sh
# One awk program: count in an array, then keep the three largest
# counts in a single pass over it. No sort at all.
awk '
{ n[$1]++ }
END {
for (id in n) {
c = n[id]
if (c > c1) {
c3 = c2; i3 = i2
c2 = c1; i2 = i1
c1 = c; i1 = id
} else if (c > c2) {
c3 = c2; i3 = i2
c2 = c; i2 = id
} else if (c > c3) {
c3 = c; i3 = id
}
}
print i1 * i2 * i3
}'
Part 2: the other end
The pipeline version only needs the second sort turned around. sort -n
puts the least common IDs first:
#!/bin/sh
# Step 4 with the second sort ascending: least common first.
export LC_ALL=C
sort | uniq -c | sort -n |
awk '{ p = (NR == 1) ? $2 : p * $2 } NR == 3 { print p; exit }'
And the one-awk version keeps the three smallest counts. Every count is at least 1, so an unset variable, which compares as 0, marks a place that isn’t filled yet:
#!/bin/sh
# Step 5 keeping the three smallest counts. Every count is at least 1,
# so a count of 0 (an unset variable) marks a place not filled yet.
awk '
{ n[$1]++ }
END {
for (id in n) {
c = n[id]
if (!c1 || c < c1) {
c3 = c2; i3 = i2
c2 = c1; i2 = i1
c1 = c; i1 = id
} else if (!c2 || c < c2) {
c3 = c2; i3 = i2
c2 = c; i2 = id
} else if (!c3 || c < c3) {
c3 = c; i3 = id
}
}
print i1 * i2 * i3
}'
SQL
SQL has no loops and no variables, so counting is the easy part here:
GROUP BY id and count(*) do it. ORDER BY ... LIMIT 3 picks the three
IDs. The hard part is the last step, multiplying three rows together, because
SQL has sum() but SQLite has no product(). Every step below is one SQL
file run by sqlite3, Apple’s build of SQLite 3.54.0 that comes with macOS.
A small shell script loads the input into a one-column table and runs the
step, so the steps differ only in their SQL:
exec sqlite3 :memory: \
'CREATE TABLE ids(id INTEGER);' \
'.import /dev/stdin ids' \
".read $1"
Creating the table first matters. If ids doesn’t exist, .import creates
it and uses the first line of the input as the column name: on the example
the table gets a column called "57" and 20 rows instead of 21. Timings are
best of 11 runs on an Apple M2 Pro, startup included, on the shared timing
input of 100,000 IDs drawn from 50,000 values (43,282 distinct). A step
file that only runs SELECT count(*) FROM ids takes 46.5 ms on it, so that
is the cost of loading. Starting sqlite3 on the 21-ID example takes about
7 ms.
Part 1: the three most common
Step 1: a beginner’s version
The first query anyone writes shows the answer as three rows:
SELECT id, count(*) AS c FROM ids GROUP BY id ORDER BY c DESC LIMIT 3;
Then there is no product() to wrap around it. A beginner who knows
LIMIT and OFFSET can still get one number: ask for the first, second and
third row in three scalar subqueries and multiply those.
SELECT
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 0) *
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 1) *
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 2);
Step 2: name it once with a CTE
A common table expression (WITH top AS (...)) gives the top-three query a
name. The three subqueries now read three rows from top instead of
counting the table again.
WITH top AS (
SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 3
)
SELECT
(SELECT id FROM top LIMIT 1 OFFSET 0) *
(SELECT id FROM top LIMIT 1 OFFSET 1) *
(SELECT id FROM top LIMIT 1 OFFSET 2);
Step 3: number the rows
LIMIT 1 OFFSET 1 on a CTE without an ORDER BY asks for “the second row” of
a table that has no order. It works, but SQL doesn’t promise it. A window
function gives each row a number instead: row_number() OVER () counts the
rows 1, 2, 3 as they arrive. Then one aggregate pass picks each number out
with a FILTER clause and multiplies.
WITH top AS (
SELECT id, row_number() OVER () AS r
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 3)
)
SELECT max(id) FILTER (WHERE r = 1)
* max(id) FILTER (WHERE r = 2)
* max(id) FILTER (WHERE r = 3)
FROM top;
Step 4: a product of any number of rows
Step 3 only works for exactly three rows. The general way to fold rows in SQL
is a recursive CTE. product starts as the single row (0, 1), and each
round joins the row numbered one higher from top and multiplies it in. The
last row holds the product.
WITH RECURSIVE
top(r, id) AS (
SELECT row_number() OVER (), id
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 3)
),
product(r, p) AS (
SELECT 0, 1
UNION ALL
SELECT top.r, product.p * top.id
FROM product JOIN top ON top.r = product.r + 1
)
SELECT p FROM product ORDER BY r DESC LIMIT 1;
Step 5: materialize it yourself
AS MATERIALIZED (since 3.35.0) tells SQLite to compute top once into a
temporary table. The plan now shows MATERIALIZE top, and SCAN ids runs
once.
WITH RECURSIVE
top(r, id) AS MATERIALIZED (
SELECT row_number() OVER (), id
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 3)
),
product(r, p) AS (
SELECT 0, 1
UNION ALL
SELECT top.r, product.p * top.id
FROM product JOIN top ON top.r = product.r + 1
)
SELECT p FROM product ORDER BY r DESC LIMIT 1;
Part 2: the other end
The first try is step 5 with DESC taken out, least common first:
WITH RECURSIVE
top(r, id) AS MATERIALIZED (
SELECT row_number() OVER (), id
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*) LIMIT 3)
),
product(r, p) AS (
SELECT 0, 1
UNION ALL
SELECT top.r, product.p * top.id
FROM product JOIN top ON top.r = product.r + 1
)
SELECT p FROM product ORDER BY r DESC LIMIT 1;
That gives the right answer, but on ties SQL makes no promise about which
three IDs you get. Adding id to the ORDER BY makes the choice explicit:
the smallest IDs win among equal counts.
WITH RECURSIVE
top(r, id) AS MATERIALIZED (
SELECT row_number() OVER (), id
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*), id LIMIT 3)
),
product(r, p) AS (
SELECT 0, 1
UNION ALL
SELECT top.r, product.p * top.id
FROM product JOIN top ON top.r = product.r + 1
)
SELECT p FROM product ORDER BY r DESC LIMIT 1;
The DuckDB tab runs these queries on DuckDB, where product(), QUALIFY
and max_by(id, n, 3) replace the recursive CTE.
DuckDB
DuckDB speaks nearly the same SQL as SQLite, so this tab runs the SQLite
tab’s queries first and then swaps in the tools DuckDB has and SQLite
doesn’t: a product() aggregate, QUALIFY, and max_by that returns the
top n values in one aggregate. Every step is one SQL file run by DuckDB
2.0.1 from Homebrew. As in the SQLite tab, a small shell script loads the
input into a one-column table and runs the step:
exec duckdb -no-agent -list -noheader :memory: \
-c "CREATE TABLE ids(id INTEGER); COPY ids FROM '/dev/stdin';" \
-c ".read $1"
-list -noheader prints the bare value. -no-agent arrived in 2.0.0 (it
is in the shell’s option list at v2.0.0 and not at v1.5.0). When the shell sees an AI agent’s environment variable (AI_AGENT,
CLAUDECODE and others are listed in shell.cpp) and stdout is not a
terminal, it switches to markdown tables and prints a banner. An output
mode flag such as -list already keeps it off; -no-agent makes that
explicit. Timings are best of 11 runs on an Apple M2 Pro, startup
included, on the shared timing input of 100,000 IDs drawn from 50,000
values (43,282 distinct). Every step takes 34 to 36 ms on the 21-ID
example, against about 7 ms for sqlite3, so DuckDB starts about five
times slower. On the timing input, a script that creates the table without
reading stdin takes 31.6 ms, and loading with COPY and counting the rows
takes 45.9 ms, so loading costs about 14 ms.
Part 1: the three most common
Step 1: the SQLite beginner’s query
The SQLite tab’s first step runs on DuckDB with one change, a cast on the first factor:
SELECT
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 0)::BIGINT *
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 1) *
(SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 1 OFFSET 2);
Step 2: product()
DuckDB has the aggregate SQLite lacks, so the top three go straight into
product():
SELECT product(id)::BIGINT
FROM (SELECT id FROM ids GROUP BY id ORDER BY count(*) DESC LIMIT 3);
Step 3: QUALIFY
QUALIFY filters on a window function the way HAVING filters on an
aggregate, with no subquery. Numbering the groups by count and keeping
numbers 1 to 3 reads like the problem statement:
SELECT product(id)::BIGINT
FROM (
SELECT id FROM ids
GROUP BY id
QUALIFY row_number() OVER (ORDER BY count(*) DESC) <= 3
);
Step 4: max_by(id, n, 3)
The rewrite in step 3 points at the experienced version, which asks for
the top three directly. max_by(arg, val, n) returns a list of the arg values of
the n rows with the largest val, and list_reduce folds that list with a
lambda:
SELECT list_reduce(max_by(id::BIGINT, n, 3), lambda a, b: a * b)
FROM (SELECT id, count(*) AS n FROM ids GROUP BY id);
Part 2: the other end
min_by is the mirror image:
SELECT list_reduce(min_by(id::BIGINT, n, 3), lambda a, b: a * b)
FROM (SELECT id, count(*) AS n FROM ids GROUP BY id);
A tiebreaker makes the choice explicit. (n, id) is a row value, which
DuckDB 2.0.1 types as TUPLE(BIGINT, INTEGER) and compares field by field,
so equal counts fall back to the smaller ID:
SELECT list_reduce(min_by(id::BIGINT, (n, id), 3), lambda a, b: a * b)
FROM (SELECT id, count(*) AS n FROM ids GROUP BY id);
Under the hood
Everything the six steps use, and what it costs. n is IDs read, k is distinct IDs; “expected” means average case for hashing.
| piece | what it is in CPython 3.15 | cost |
|---|---|---|
text.split() | specialised whitespace split in C | O(length of text) |
int(word) | parse decimal digits into an int stored in 30-bit digits | O(digits) |
dict counting | open-addressing hash table: index array + dense entries | O(1) expected per ID, O(n) total |
sorted(..., key=) | insertion sort under 64 items, otherwise runs + galloping merges (powersort policy) | O(k log k), k − 1 comparisons if already ordered |
Counter(iterable) | dict subclass, counting loop in C (_count_elements) | O(n) expected, ~3× faster than a Python loop |
most_common(3) | heapq.nlargest(3, items, key=itemgetter(1)) | O(k), about k comparisons |
most_common() | sorted(items, key=itemgetter(1), reverse=True) | O(k log k) |
heapq.nsmallest(3, ...) | heap of 3 decorated tuples, Python loop | O(k) |
functools.reduce | C loop, one reused argument tuple | one call of the function per item |
math.prod | C loop: long fast path, then double, then objects | O(items) |
Four longer articles, each checked against CPython’s source at v3.15.2, with links to the exact lines:
Benchmarks
Across languages
Every program from the language tabs, run the way a reader would run it: a fresh process each time, the input piped to stdin, the whole run timed from outside, startup included. Each number is the best of 11 runs on an Apple M2 Pro. The inputs are generated, never the real puzzle input:
- the 21-ID example, which costs almost nothing to process, so its time is roughly what starting the program costs;
- 100,000 IDs drawn from 50,000 values (43,282 distinct), the input every tab quotes;
- 1,000,000 IDs (50,000 distinct) for the last step of each part, built so that the top three and bottom three are unambiguous. Every program printed Python’s answer on it.
Two programs that do no work set the floor: true takes 2.0 ms (starting
any process from the benchmark script), and wc -l, which reads the 100,000
lines and counts them, 5.2 ms. The benchmark is aoc langs bench in my
solutions repo; the charts come from bench/chart_langs.py.
Scroll the chart sideways, or tap it to open it full size.
What the chart says:
- The longest lines are algorithms, not languages. C, APL and K start
with an O(n · k) count: every new ID is looked up by scanning the list of
IDs seen so far. Their last steps are 213, 125 and 68 times faster. Go’s
step 1 is slow for a different reason:
fmt.Scanasks the file for one byte per read call (the Go tab counts them). - For a third of the languages the step barely matters. In Python, Ruby, JavaScript, Swift, OCaml, DuckDB and Prolog the last step is 7 to 25% faster than the first, in Clojure 2%.
- Startup decides the bottom of the chart. On the 21-ID example the last step of Clojure takes 373 ms of its 450, Elixir 225 of 291, Erlang 181 of 228. For Java, Ruby, JavaScript and Python the example takes more than half of the whole run too (31 to 35 ms, and 19 ms for Python).
Subtracting the 100,000-ID time from the 1,000,000-ID time cancels startup and leaves the cost of 900,000 more IDs:
Scroll the chart sideways, or tap it to open it full size.
- Java and Clojure move up once startup is gone: Java to 98 ns per ID, ahead of Python, and Clojure to 234 ns, ahead of Haskell and the shell. Measured whole, they looked slow because of the JVM and Clojure starting up, not because of the counting.
- Python’s 119 ns per ID is ahead of Swift, JavaScript, Ruby and OCaml
here. Its last step hands the parsing and counting to C (
str.split,int,Counter); the Swift tab measuresreadLine()as most of that program’s time. - Erlang and Elixir run on the same VM and still differ per ID by almost 5× (216 against 1,013 ns). They are different programs, and I haven’t measured where Elixir’s extra time goes.
| Language | step 1 | last step | last step, 21-ID example | per extra ID |
|---|---|---|---|---|
| Zig | 11 ms | 6.8 ms (step 6) | 3.1 ms | 40 ns |
| C | 1.64 s | 7.7 ms (step 5) | 2.6 ms | 55 ns |
| Rust | 10 ms | 8.2 ms (step 6) | 2.8 ms | 51 ns |
| Go | 215 ms | 9.1 ms (step 5) | 3.4 ms | 47 ns |
| C++ | 109 ms | 11 ms (step 6) | 2.7 ms | 69 ns |
| BQN | 30 ms | 11 ms (step 5) | 4.0 ms | 72 ns |
| K | 920 ms | 14 ms (step 6) | 3.2 ms | 101 ns |
| Swift | 21 ms | 17 ms (step 5) | 3.0 ms | 143 ns |
| OCaml | 32 ms | 24 ms (step 5) | 3.9 ms | 197 ns |
| Python | 38 ms | 33 ms (step 6) | 19 ms | 119 ns |
| Haskell | 146 ms | 44 ms (step 6) | 18 ms | 325 ns |
| DuckDB | 48 ms | 45 ms (step 4) | 32 ms | 68 ns |
| Unix shell | 138 ms | 48 ms (step 5) | 6.3 ms | 351 ns |
| Uiua | 158 ms | 50 ms (step 5) | 12 ms | 313 ns |
| JavaScript | 65 ms | 55 ms (step 4) | 31 ms | 162 ns |
| Ruby | 61 ms | 55 ms (step 6) | 32 ms | 196 ns |
| Java | 133 ms | 65 ms (step 6) | 35 ms | 98 ns |
| SQL | 116 ms | 70 ms (step 5) | 7.3 ms | 662 ns |
| APL | 10.92 s | 88 ms (step 5) | 20 ms | 919 ns |
| Prolog | 136 ms | 121 ms (step 5) | 17 ms | 910 ns |
| Erlang | 581 ms | 228 ms (step 6) | 181 ms | 216 ns |
| Elixir | 572 ms | 291 ms (step 6) | 225 ms | 1013 ns |
| Clojure | 461 ms | 450 ms (step 5) | 373 ms | 234 ns |
Versions: Python 3.15.2, Apple clang 21 (C, C++), Rust 1.100.1, Zig 0.17.1,
Go 1.27.4, Swift 6.4.2, OpenJDK 27.0.1.1, Clojure 1.12.7, Node 23.11.0,
Ruby 4.0.10, GHC 9.14.1, OCaml 5.5.2, Elixir 1.20.5 and Erlang/OTP 29.1.3,
SWI-Prolog 11.0.1, CBQN 2bf102f, ngn/k b9eeb91, GNU APL 2.0, Uiua 0.19.1,
macOS’s sort and awk, SQLite 3.54.0, DuckDB 2.0.1. How each program is
built is in its tab.
Python in detail
Every step on generated inputs, never the real puzzle input: n IDs from 100
to a million, drawn from either 100 distinct values or
n/2 distinct values (mostly unique). Each number is the best of five runs
on an Apple M2 Pro, with Python 3.9.6, 3.12.16 and 3.15.2. The benchmark and
chart scripts are bench/day01.py and bench/chart.py in my solutions repo.
Two extra lines are baselines, not solutions: parse only turns the text
into ints and stops (list(map(int, text.split()))), and count only
also builds the Counter.
Scroll the chart sideways, or tap it to open it full size.
What the chart says:
- Most of the time is parsing. With 100 distinct IDs and a million IDs on 3.15, parsing alone takes 51 ms; the full one-liner takes 71 ms. Counting adds about 20 ms, and picking three and multiplying them add nothing you can measure.
- Steps 3 to 6 run at the same speed, because they are all
“count with Counter, then do almost nothing”.
reduce,mulandprodonly ever touch three numbers. - The beginner’s version costs about a third more (96 ms against 71 ms):
the counting loop runs as Python bytecode, where
Counterruns it in C. Step 2’sdict.getclaws back some of that. - With mostly distinct IDs the lines climb: half a million distinct keys
mean a big dict that has to resize many times on the way. Sorting all of them (steps 1, 2 and part 2’s
[-3:]) now shows up too. This shape is also noisy (on 3.12, the count-only baseline came out slower than a full solution that does the same counting), so read only big differences from it.
Scroll the chart sideways, or tap it to open it full size.
| 1M IDs, 100 distinct | 3.9.6 | 3.12.16 | 3.15.2 |
|---|---|---|---|
| parse only | 88 ms | 73 ms | 51 ms |
| count only | 116 ms | 98 ms | 72 ms |
| step 1 | 168 ms | 121 ms | 96 ms |
| step 2 | 160 ms | 107 ms | 86 ms |
step 3 (Counter) | 117 ms | 98 ms | 71 ms |
| step 6 (one-liner) | 114 ms | 97 ms | 71 ms |
part 2, nsmallest | 114 ms | 98 ms | 71 ms |
The same code got about 1.6 to 1.75× faster from 3.9 to 3.15 without a single change; parsing alone got 1.7× faster. These are three different builds (Apple’s 3.9, uv’s 3.12, Homebrew’s 3.15), so the comparison mixes interpreter improvements with build differences.