day 1
Frequency counting and sorting
On this page
#. Problem
— Day 1: Dusty Shed —
Due to bad weather, the Elves need to use a train to transport supplies. However, their inventory records have been lost, leaving them with only a list of container IDs.
To identify the required supplies, find the three most frequently occurring IDs and calculate their product.
For example, given the following input:
57
57
55
57
76
78
57
45
43
78
43
76
43
78
57
45
57
76
43
43
76
The three most frequently occurring IDs are:
- 57: 6 occurrences
- 43: 5 occurrences
- 76: 4 occurrences
Multiplying these three IDs gives 186276.
What is the product of the three most frequently occurring IDs in the puzzle input?
1. My approach
Used a JavaScript object to keep track of the frequency of each number. Converted the object into an array of key-value pairs, sorted it by frequency in descending order, and multiplied the first three numbers.
(function main() {
const input = `57
57
55
57
76
78
57
45
43
78
43
76
43
78
57
45
57
76
43
43
76`;
const obj = {};
const arr = input.split("\n").map(el => Number(el));
arr.forEach(el => obj[el] = obj[el] ? obj[el] + 1 : 1);
const arr2 = [];
for (const [key, value] of Object.entries(obj)) {
arr2.push([Number(key), value]);
}
const sorted = arr2.sort((a, b) => b[1] - a[1]);
console.log(sorted[0][0] * sorted[1][0] * sorted[2][0]);
}());
2. Optimal approach
2.1. Using Object and method chaining
The original approach can be simplified using built-in JavaScript methods without introducing additional data structures.
const counts = {};
for (const num of input.split("\n").map(Number)) {
counts[num] = (counts[num] ?? 0) + 1;
}
const result = Object.entries(counts)
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
.reduce((acc, [num]) => acc * Number(num), 1);
console.log(result);
Some improvements over the original implementation:
map(Number)replaces the unnecessary arrow function.- The nullish coalescing operator (
??) simplifies frequency counting. Object.entries()already returns an array of key-value pairs, eliminating the need to manually construct another array.slice()andreduce()eliminate hardcoded array indices when calculating the product.
2.2. Using Map
Since JavaScript objects implicitly convert numeric keys into
strings, Map is a more suitable data structure for storing
numeric IDs.
const counts = new Map();
for (const num of input.split("\n").map(Number)) {
counts.set(num, (counts.get(num) ?? 0) + 1);
}
const result = [...counts]
.sort(([, a], [, b]) => b - a)
.slice(0, 3)
.reduce((acc, [num]) => acc * num, 1);
console.log(result);
Unlike Object, Map preserves the original type of its keys,
eliminating the need to convert them back into numbers.
Destructuring also makes the sorting function cleaner by extracting only the frequency values.
One difference is that Map preserves insertion order, whereas
objects enumerate integer-index keys in ascending order.
This can produce different results when frequencies are tied,
unless an explicit tie-breaking rule is provided.
3. Complexity analysis
Let n be the total number of IDs and k be the number of
unique IDs.
| Operation | Time complexity |
|---|---|
| Parsing input | O(n) |
| Frequency counting | O(n) |
| Sorting | O(k log k) |
| Calculating result | O(1) |
- Time complexity:
O(n + k log k) - Space complexity:
O(n + k)
Both approaches have the same asymptotic complexity as the original implementation. The main improvements are readability, maintainability, and avoiding unnecessary conversions.
Technically, sorting all unique IDs is unnecessary since only
the top three are required. Maintaining the three highest
frequencies in a single traversal would reduce the overall
time complexity to O(n + k), or simply O(n).
However, for this particular problem, the sorting approach provides a good balance between simplicity and performance.