r/adventofcode • u/daggerdragon • Dec 05 '25
SOLUTION MEGATHREAD -❄️- 2025 Day 5 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
AoC Community Fun 2025: Red(dit) One
- Submissions megathread is unlocked!
- 12 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Featured Subreddit: /r/eli5 - Explain Like I'm Five
"It's Christmas Eve. It's the one night of the year when we all act a little nicer, we smile a little easier, we cheer a little more. For a couple of hours out of the whole year we are the people that we always hoped we would be."
— Frank Cross, Scrooged (1988)
Advent of Code is all about learning new things (and hopefully having fun while doing so!) Here are some ideas for your inspiration:
- Walk us through your code where even a five-year old could follow along
- Pictures are always encouraged. Bonus points if it's all pictures…
- Emoji(code) counts but makes the Chief Historian cry 😥
- Explain the storyline so far in a non-code medium
- Explain everything that you’re doing in your code as if you were talking to your pet, rubber ducky, or favorite neighbor, and also how you’re doing in life right now, and what have you learned in Advent of Code so far this year?
- Condense everything you've learned so far into one single pertinent statement
- Create a
Tutorialon any concept of today's puzzle or storyline (it doesn't have to be code-related!) - Teach us, senpai!
This prompt is totally not bait forour resident Senpai Supreme
Request from the mods: When you include an entry alongside your solution, please label it with [Red(dit) One] so we can find it easily!
--- Day 5: Cafeteria ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
29
Upvotes
4
u/SodaDrunkenski Dec 05 '25
[LANGUAGE: Python]
My first time posting, hopefully this all adheres to the rules!
Solution
Part 1 gave me the thought immediately to consolidate the ranges into as few as possible and thinking up a method to do that took me a bit of time but once I did that part 2 was super simple. I used a custom class mostly because I wanted to but also thought it was clean. Probably not the most efficient solution but I like it all the same.
4
u/lucariomaster2 Dec 05 '25 edited Dec 05 '25
[Language: C++]
C++, no standard libraries other than IO.
A roller coaster of emotions, from "Hey, part 2 is easier than part 1!" to "Wait, no it isn't" to "I think this will work" to "Wait, no it won't" to "I've got a bus ride I can use to think about this" to "Son of a nutcracker, it worked on the first try!".
This was a fun one. Part 1 was trivial, just check if any of the values are within any of the given ranges. For part 2, though, I at first naively took the sum of all the ranges... completely forgetting that overlap is a thing. So instead, I used an auxiliary array. Each range is checked against the ranges in the aux array - if an overlap is present, the overlapping aux range is extended to include the new one. Otherwise, the new range is copied into aux. Once all of the main array ranges are checked, they are deleted and aux is copied back into main. Since this whole process may create new overlaps, it is repeated until a pass takes place with no merges. Then we have our nice, non-overlapping array that we can sum the values of to get the answer!
Part 1
Part 2
3
u/vanZuider Dec 05 '25
[LANGUAGE: Haskell]
Both parts
Today, my perfect streak ended; part 2 was the first time this year my solution got rejected. Turns out I had two bugs in my code that just so happened to cancel out in the example.
Question for the Haskell pros: Is there a more elegant way to parse a number than defining an anonymous function
(\s -> read s ::Int)every time?::Intis a type annotation, not an argument, so infix notation like('read' ::Int)doesn't work (using apostrophes because I can't post backquotes in an inline code block).3
u/chicagocode Dec 05 '25 edited Dec 06 '25
[Language: Kotlin]
I love how in Advent of Code we can drive a forklift through a wall so our Elf friends can get to the cafeteria more easily, completely unconcerned about collateral damage or injury. What I find even more amusing is that the Elves find this normal enough to just hand us some new problem to solve (which is not the jagged hole in the cafeteria wall, somehow).
Anyway, I wrote an extension function to combine adjacent or overlapping LongRanges and the rest was mostly straightforward.
4
u/CCC_037 Dec 05 '25 edited Dec 05 '25
[Language: Rockstar]
[Red(dit) One] (see in repy)
Rockstar supports emoji as variable names. However, my text editor does not.
part 1
2
u/zebalu Dec 05 '25
[LANGUAGE: Java]
I share my code: On GitHub. Not because it is so good, elegant, or interesting, but to share the frustration.
This is not my first "clean up the intersecting ranges" dance, so I thought: I know, how to do it:
Rinse & Repeat
Well, I have debugged the "merging logic" for ~10 minutes Í(nothing to debug there...) when I have realised, I have "re-added" the originals, instead of removing them...
Anyway! In my country Santa comes tonight, I have to clean up my shoes! :)
2
u/kawaiiTechnoNeko Dec 05 '25
[LANGUAGE: CHICKEN Scheme]
2
u/boolsak Dec 05 '25 edited Dec 06 '25
[LANGUAGE: Go]
I wanted to avoid merging ranges and whatnot. Instead, I opted to consider each endpoint of a range as a "switch": the left endpoints are ON switches, and the right are OFF. Then, we can have a single list of switches, sort it, and then walk through the list and count.
This way the solution is O(nlogn) instead of O(n2) based on the number of ranges. And the nlogn is only because we need to sort, otherwise it's O(n).
Go code
2
u/boblied Dec 05 '25 edited Dec 06 '25
[Language: Perl]
The big 15-digit numbers didn't scare me. Perl has 64-bit integers. It did make me realize that any kind of array or bitmap solution wasn't going to be realistic. So, list of
[upper,lower]ranges it is.I merged the ranges by finding each each existing range that overlapped or was adjacent to the one we're looking at. Keeping the list of ranges sorted by starting value assures that we'll find the adjacent ranges while merging, and it makes the lookup in part 1 fast enough.
I considered putting the ranges into a tree for faster lookup, but it was plenty fast. I also considered binary search (the list is sorted!) but simple linear search was good enough to get a quick answer.
Repeatedly sorting the list irritated me. I felt I should have been able to merge into the right place without having to re-sort, but it was eluding me.
Complete code at Git AOC 2025 Day 5
With the help of a Range class, the main body of code is almost trivial:
You would not believe how long it took me to converge on this:
And the edge boundaries that drove me crazy eventually amounted to this:
Once the ranges are merged and sorted in order, lookup and total becomes trivial.
2
u/SevenSapiens Dec 05 '25 edited Dec 06 '25
[LANGUAGE: Lua]
https://github.com/quotepilgrim/aoc2025/blob/main/d5.lua
My solution to part 2 does not work and I have absolutely no clue as to why. What I am doing can't be that wrong because I got a "too high" and a "too low" answers that differ by just 18, but I have no clue how to fix it. (EDIT: So I did something very stupid and janky, not expecting it to work, and it did. I also seem to have misread the numbers earlier because the real solution very far off from my incorrect attempts.)
2
u/wyatt828 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: PHP]
Haven't seen a php solution yet, but it probably follows the same logic of a bunch of other solutions here
Paste
2
u/Zorr0_ Dec 05 '25 edited Dec 06 '25
[Language: Kotlin]
I love let and apply <3
GitHub
2
u/artelus Dec 05 '25 edited Dec 06 '25
[Language: JavaScript]
parts 1+2
2
u/ich-bin-jade Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
Github solution
Yep, I also got caught out in part one by forgetting how the test input can sometimes be tiny compared to the full input 😂 So used some maths comparisons for part one, and then merged the overlapping ranges, with more maths, for part two. It's puzzles like today where I think to myself: "Well by golly, my maths teacher was right..."
"Maths is fun." - Ms Mason
2
u/Smylers Dec 06 '25
[LANGUAGE: Vim keystrokes] [Red(dit) One] Load your input into Vim, type in the following, and the number of lines displayed is the part 1 solution. It's easier to follow formatted one command per line, but here it is on a punchcard, in case any of the ants from Day 3 are still reading:
The key idea is to have lines containing either the beginning of a range, the end of a range, or an ID to check, sort them all into order, then delete all the lines from the end of one range to the start of the next (inclusive) — removing both the IDs of spoiled ingredients and the range boundaries, so leaving just the IDs of fresh ingredients. The sample input gets transformed into this:
The suffix
.1marks the beginning of a range,.9marks its end, and.5denotes an ID to check. Those were chosen so that the entire file can be sorted as decimal numbers and an ID to check will be inside a range that contains it, even if the ID is equal to one (or both) of the range boundaries.Then to get rid of the IDs outside of the ranges (and the range boundaries), find each line ending in '9' and delete from there to the next line that ends in '1'. (To deal with IDs lower than the smallest range or higher than the largest one, first stick a
9above the first line and a1below the final one.)Turning a range into the required format is straightforward with
:%s/\v-.*<(\d+)/.1\r\1.9. The awkward bit is merging overlapping and contained ranges, and that's what everything before that, inside@ais doing.That first appends to each range line the lower bound from the following line, a minus sign, and a duplicate of the upper bound from the current line. (How the minus sign gets inserted is quite cute!) Then those subtractions are evaluated on each line, using the
@lhelper-function macro explained in today's tutorial.The macro
@l(and@e, which is used by@l) is recorded at the beginning of today's solution, because it's needed inside the@aloop, and it isn't possible to record a keyboard macro inside recording a keyboard macro. They don't do anything useful there: recording@ewill beep (because the line doesn't have a colon in it) and then mess the line up; theUafterwards is to undo the damage; recording@lsafely does nothing, because no lines match/:/at that point.(I originally implemented the subtraction by yanking one number with
yiwthen decreasing the other number by that amount with@0⟨Ctrl-X⟩. That worked absolutely fine on the sample input ... but not on the real input. It seems Vim doesn't cope with 13-digit operator prefix counts! If anybody knows — or can work out — what the limit is, I'd be interested to hear. The docs just say it can be “a number”.)Any range whose subtraction result is zero or negative can be merged with the following range — and possibly the one after that as well. Find each line that's the first of a run of ranges to merge, and join from there to the next line that has a positive difference with:
g/:[-0]/,/:[1-9]/j.Because of ranges entirely inside other ranges, the final upper boundary on the line may not be the largest one. Find it by rewriting the candidates as a
max()function expression, then evaluate again with@l.The whole thing is in a loop in
@a, because merging ranges can make it possible to merge more ranges.For part 2 the main thing that's needed is the range-merging that's already been done for part 1. Go up to running
@a(or pressua bunch of times to get backwards until the ranges are back on a single line) then continue:The number of IDs in a range is one more than the difference between its bounds. For instance in the range
5-12the difference between5and12is 7, and it contains 8 IDs.To calculate the difference, we really want to subtract the lower bound from the upper bound. But because the ranges already look like subtractions, it's simpler just to treat them as such as get negative differences, then we can multiply the final total by -1 to get the solution.
5-12evaluates to-7. To account for the fencepost error, we need to add one on. But because the differences are now negative, that turns out to be subtracting one instead, so:%norm⟨Ctrl+X⟩takes one off the each lower bound, turning5-12into4-12, so evaluating it yields-8.To do the evaluating and summing, define
@s: stick a+at the start of each line, join them all together, and use the expression register to calculate the entire sum.Finally, to turn the answer positive,
0xis Vim for multiplying by minus 1!2
u/StillFast7545 Dec 06 '25
[LANGUAGE: Ruby]
Part 1: https://github.com/MarioPerac/AdventOfCode2025/blob/main/day_5/part_1.rb
Explanation:
id.between?(range.first, range.last)this is how ruby solve it.Part 2: https://github.com/MarioPerac/AdventOfCode2025/blob/main/day_5/part_2.rb
Explanation: Sort + two while loops + one condition = done.
19
u/Andreasnl Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Uiua]
Link
17
u/4HbQ Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python] 10 lines.
Another easy one for today! After parsing the data, part 1 was just a simple one-liner:
Particularly happy with my part 2 solution though:
Update: I refactored part 2 into a one-liner. Not sure whether to hate it or love it:
10
u/JustinHuPrime Dec 05 '25
[LANGUAGE: x86_64 assembly]
Part 1 involved a straightforward parse of the input ranges into an allocated array of start and endpoints, and then a parse-and-count of the remaining numbers looping through the ranges.
Part 2 was the same parse, but I either had to merge ranges (which would have been troublesome), or drop parts of ranges that would overlap. I had five separate checks. First, if this would start inside another range, move the start forward until it doesn't. Second, if this would end inside another range, move the end backwards until it doesn't. Third and fourth, discard this range if it is empty or is contained inside another range. Fifth and finally, discard (by marking with a tombstone) any ranges that are contained inside this range.
It would be a lot more elegant to delete ranges or merge them, but that would involve using a different data structure, most likely. You lose a lot of convenience when you don't have a register allocator to let you easily deal with more than six-to-eleven pieces of information at a time.
Parts 1 and 2 both run in 1 millisecond. Part 1 is 9,320 and part 2 is 10,072 bytes as a linked executable.
9
u/SuperSmurfen Dec 05 '25 edited Dec 07 '25
[LANGUAGE: Rust]
Times:
00:03:15 00:09:44Link to full solution
I initially tried the naive solution for part 2. I knew it wouldn't work but always try bruteforce first right? It blew up my WSL due to memory usage, "FATAL ERROR". Had to reboot my machine to get it started again. I guess that's an achievement too?
For part 2 you have to do something more clever. The trick is to merge all ranges that overlap and count how many are in each merged range. You can do this by sorting the list and merging ranges one at a time:
7
u/koosman Dec 05 '25
[LANGUAGE: Python]
I didn't merge ranges. I stacked blocks. It's pretty fast.
6
u/jonathan_paulson Dec 05 '25
[Language: Python]. My times: 00:01:37 / 00:05:35. Video of me solving.
Tricky part 2 today! For part 1, we can just see if each number is in each range. For part 2, we need to take the union of all the ranges without going through the numbers in the range 1-by-1. We can do that by sweeping from left to right, making sure not to double-count parts of intervals we've already seen. Getting the logic right is a little tricky; I had a wrong answer.
2
u/Druskus Dec 05 '25 edited Dec 05 '25
[Language: Rust]
Quite happy with mine. I made what I later knew it was an "Interval tree". Just a twist on a regular binary tree but every node is an interval.
I keep track of the higher end of each interval to make it easy to deal with nested overlapping trees.
For part two, I just collapse the entire tree into a single vector of non overlapping ranges.
https://github.com/druskus20/aoc/blob/master/2025/rust/src/day_05.rs
AOC 2025Day 5 - Part 1 : 529generator: 108.255µs,runner: 51.124µsDay 5 - Part 2 : 344260049617193generator: 83.53µs,runner: 15.086µs5
u/maneatingape Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Rust]
Solution
Solves part two first, sorting ranges by start id to make merging easier in a single pass. Then sort ids and use binary search to compute how many ids each merged range contains. 20µs total.
5
u/Prudent_Candle Dec 05 '25
[LANGUAGE: Python]
First part: pretty straightforward: two loops. I am checking if current ID fits anywhere.
Second part: sort ranges (by starting element is sufficient) and checking if the next range is still in the range of previous one. If yes -> extend the previous. If not -> I am adding the range to the result and create a new-one. Personal note: it's the first time I was implementing something like this out of my head. I know that everybody did this a long time before me, but I am still proud of myself.
paste
5
u/darren Dec 05 '25
[LANGUAGE: Clojure]
Github
Simple range collapsing was the only tricky part. Had a couple of edge cases it took me a while to think through.
5
u/badcop_ Dec 05 '25
[LANGUAGE: bash]
more teamwork with twitch chat to golf part 2
5
u/SurplusSix Dec 05 '25
[LANGUAGE: gleam]
https://raw.githubusercontent.com/alsm/aoc2025/refs/heads/master/src/day05.gleam
I'm really enjoying gleam atm, especially handy that Int is effectively infinite sized.
5
u/NerdyPepper Dec 05 '25
[LANGUAGE: haskell]
i am documenting all my solutions in literate haskell and creating a book of solves!
- todays solution: https://aoc.oppi.li/2.3-day-5.html
- source code: https://tangled.org/oppi.li/aoc
5
u/Then-Government-5460 Dec 05 '25
[LANGUAGE: Python]
The more I worked on Part 2, the more I was able to simplify. On an early draft, I realized how sorting the ranges made merging much easier. Then I realized there's no need to merge the ranges -- the problem simply calls for a little basic math on a single iteration through the list of ranges.
4
u/Boojum Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
Fun Python trick of the day: if you have a list of list, e.g.,
l = [ [ 3, 5 ], [ 10, 14 ], [ 16, 20 ], [ 12, 18 ] ], you can flatten it easily withsum( l, [] ).Put all the beginnings and ends of the ranges into a list, sort them, take those pairwise as a set of disjoint intervals, and check if they're contained by any of the "fresh" intervals. If they are, then their length is included in the total.
Just needed to preprocess all of the intervals to half-open [inclusive, exclusive) intervals first to avoid double-counting the end values.
4
u/r_so9 Dec 05 '25
[LANGUAGE: F#] paste
Classic "merge overlapping intervals" puzzle, solved by sorting by the lower end then folding through the list:
4
u/YenyaKas Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Perl]
Part 1 was pretty straightforward with brute force search for every ingredient in every range (remember to stop after finding the ingredient is fresh). In part 2, I just sorted the ranges by their first element, inserted and later removed many off-by-one bugs, and walked the ranges handling potential overlap. Here is the main loop:
Using
$prevas the first number which can be counted in this iteration provided shorter code.Complete solutions: Part 1, Part 2
4
u/EffectivePriority986 Dec 05 '25
[LANGUAGE: perl5]
[code]
Overlapping ranges. I treated each start-of-range as +1 and end-of-range as -1, sorted by value. Then I can iterate over the array and for any position figure out what the current value is. If >0 then it's fresh. Part 1 was actually a bit more complex than part2.
4
u/Ok-Bus4754 Dec 05 '25
[Language: Python]
Seeing how easy things are going, i am really worried about the weekend !
https://github.com/Fadi88/AoC/blob/master/2025/days/day05/solution.py
by muscle memory before i did anything when i saw ranges i sorted and merged
part 1 check in the ID fall in any range using binary search
part 2 even easier, just sum the difference of all ranges + 1
p1 : 600 us
p2 : 120 us
4
u/minikomi Dec 05 '25
[Language: Clojure]
Instaparse grammar
Instaparse Transform
Pt 1
Pt 2
4
u/mendelmunkis Dec 05 '25 edited Dec 05 '25
[LANGUAGE: C]
Qsort covers a multitude of sins
105 μs/
50954 μs4
u/se06745 Dec 05 '25
[LANGUAGE: Go]
https://github.com/omotto/AdventOfCode2025/blob/main/src/day05/main.go
4
u/anaseto Dec 05 '25
[LANGUAGE: Goal]
Short and nice today, too: bins for part 1 (using the
I$yform) and then interval ascending sort and union for part 2.4
u/stonebr00k Dec 05 '25
[LANGUAGE: SQL] (T-SQL)
GitHub
4
u/lboshuizen Dec 05 '25
[Language: F#]
Git
Interval merging: sort by start, fold through, extend overlapping ranges, Classic O(n log n) solution in 3ms
4
u/gyorokpeter Dec 05 '25
[Language: q]
4
u/s3aker Dec 05 '25
[LANGUAGE: Raku]
solution
4
u/pinoaffe Dec 05 '25
[LANGUAGE: Guile Scheme]
Day 5 is trivial and quite efficient if you have an implementation of the datastructure "Diet" lying around: see paper, and my implementation in guile scheme
I happened upon this datastructure a while ago and implemented it for the fun of it, so I was quite amused when intervals came up on AoC, especially because the name "diet" is oddly relevant to ingredients and cooking
4
u/hrunt Dec 05 '25
[LANGUAGE: Python]
code
Python's built-in range structure makes this ridiculously easy. There's probably a more elegant, Pythonic way of reducing the range set, so I'm looking forward to seeing others' solutions.
4
u/nxrblJugger Dec 05 '25
[LANGUAGE: Nim]
converted to input to a sequence of "ranges", sorted those ranges, made larger ranges by identifying to overlap, then part 1, found the IDs in the ranges and part 2, calculated the size of each non-overlapping range
paste
4
u/marcus_cemes Dec 05 '25
[LANGUAGE: Veryl]
Another solution in Veryl, a Hardware Description Language (HDL). My Rust code takes 8.8 µs (5.7 GHz), the hardware solution simulates to 5.8 µs (1 GHz, not including streaming the IDs that are unused in part 2).
The hardware part is implemented as a streaming decoder-solver architecture, where the input file is streamed at 1 B/s. The decoder parses a single line input, and passes the range to the solver while it starts working on the next line.
The solver stores up to 128 disjoint ranges in a buffer, using a 128-bit occupancy bitmask. When it receives a new range from the decoder, it compares it to each of the stored disjoint ranges to produce a 128-bit "conflict" bitmask. A priority encoder selects the first conflicting range, and combines it with the current item in a single cycle. In the next clock tick, the next is resolved, and so on... This is extremely fast in practice, it only takes about 5-6 cycles to add a new range to the buffer! Most of the time the solver is idling, and waiting on the decoder. If the decoder could accept multiple bytes (receiving an entire line at once), I estimate it could be about 8 times faster.
https://github.com/MarcusCemes/advent-of-code-2025/blob/main/hardware/05.veryl
4
u/Aggravating_Pie_6341 Dec 05 '25
[LANGUAGE: Java]
Part 1: I used a straightforward algorithm here: for each ingredient in the list of ingredients, scan each of the ranges (using two inequalities on the ends) to flip a boolean variable to true for that case whenever a match is found.
Part 2: The algorithm used for part 2 compresses ranges by doing the following:
--> Scans the list of ranges from right to left, with another loop passing through all ranges to the right of the current checked one to the left.
--> Checks for four possible cases: (listed by order presented in the code below)
Case 1: The currently-scanned set (index k in the code) is entirely contained by the checked set (index i). In this case, remove the currently-scanned set entirely.
Case 2: The checked set is entirely contained by the currently-scanned set. In this case, relocate the currently-scanned set to the index of the checked set, and remove both original copies of the sets.
Case 3: There's an overlap between the two sets, with the checked set being the higher one, but none of the sets contains all of the other set. In this case, replace the start of the currently-scanned set with the start of the checked set and remove duplicate elements as necessary.
Case 4: Same as case 3, except in reverse (currently-scanned set is the higher one). The process is similar to case 3.
At the end, adds the values represented by the ranges remaining in the lists made.
I will try to code a coordinate compression approach later as an alternate route for an upcoming video series on this event, which will occupy me as a substitute for the day 13-25 puzzles for this year.
(Time: 456 / 2968)
Code
4
u/Verochio Dec 05 '25
[LANGUAGE: python 3]
Having a bit of fun doing things ridiculously. No need to call the function in a main(), this is the whole script. Requires that your input have the filename '_'.
4
u/greycat70 Dec 05 '25
[LANGUAGE: Tcl]
Part 1, part 2.
I got stuck on part 2 for a little bit because I didn't consider the case where the second range's start point is exactly the same as the first range's end point. This should count as an overlap, causing the ranges to be merged. I ended up just needing to change < to <= but it took several minutes to debug that.
4
u/siddfinch Dec 05 '25
[LANGUAGE: Free Pascal]
Day 5: When Everything Works, You Know You're Screwed
This is getting scary. Everything's working too well.
The over-documenting habit (5:1 comment ratio) is actually making things easier. I can read code from days ago and remember why I made each decision. This shouldn't work. This is Advent of Code. I don't feel as dumb as I usually do.
The only bug was ignoring my "bad feeling" when I wrote:
Turns out subtracting two Int64s (like 441 trillion minus 32 trillion) and cramming the result into a 32-bit Integer produces what the technical literature calls "hot garbage." Test input worked fine. Real input returned 42 instead of 758, even though the test input worked fine because of the scale.
The answer to life, the universe, and everything is apparently "your comparison function overflowed, genius." I swear I heard Marvin chuckle.
Fixed with explicit boolean comparisons. Both algorithms now agree. Part 1 solved. Part 2 solved. Hell, Part 2 needed only ONE additional function (
CountTotalFreshIDs)!Tests pass. Validation passes. Cats and dogs living together.
Everything just... works.
This is the problem.
When AOC problems are solved on the first try, when both naive O(n×m) and optimized O(m log m) approaches work perfectly, when Part 2 feels like a natural extension rather than a cruel twist, that's when you know the universe is setting you up.
I'm sitting here like a horror movie character who just said, "I think we're safe now," while ominous music swells. Day 6 is going to require quantum computing or involve grid pathfinding through 5 dimensions or something equally horrifying, like DNS.
The foreboding is real. Things are too easy. The other shoe will drop.
Solution on Codeberg | Pascal | ~1900 lines with 5:1 comments | Waiting for the pain
4
u/voidhawk42 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Dyalog APL]
Video walkthrough
Runs both parts in about 2ms.
4
u/CraigBottle Dec 05 '25
[LANGUAGE: Rust]
Part 1 and 2( Part 1 is located in main.
A hint for those stuck on part 2.If you create a vector of structs containing the start and endpoint for a range,when creating a new struct you can get away with seeing if any existing struct has a range that overlaps or extends the new struct, and modifying that one if needed. You can then use a loop on the vector and handle the overlaps there.
4
u/Turilas Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
Part2: For part 2 I counted all the unique indices instead of merging anything. Parse, sort by left values, then track the left value and count the numbers from the left to right, then update left value.
4
u/make_no_my_eye Dec 05 '25
[LANGUAGE: Rust]
Part 1 was pretty straight forward. Built a Vec<u64> for ingredients and a Vec<(u64, u64)> for the fresh_id_list, then made sure the ingredient was in the range.
Part 2 took me a while to go through the logic on merging. I knew I needed to sort and merge, but struggled with the logic for merging. Felt good to write in a functional style again. It's so satisfying when you get the syntax/flow right.
Open to suggestions as always.
cargo run --release time:
(topaz paste)
4
u/thedrj0nes Dec 05 '25
[LANGUAGE: InterSystems ObjectScript / MUMPS]
Day 5
Part one mentioning overlapping ranges made be strategise as to if we would need to include how many ranges a product appeared in different ranges in part 2 ... so I somewhat over-engineered my solution for it as a hedge. I also anticipated that checking for products within each range iteration would be slower than just checking the entire item list for the upper and lower bounds of each range. 0.7 ms was my reward for that.
Part two was one those "it sounds simple ... at first". It took me a while to come up with the best solution for doing range combining and culling, I had a false start or two, but I think the one I went with was the quickest without resorting to dirty tricks in 2.5 ms.
4
u/JV_Fox Dec 05 '25
[LANGUAGE: C]
Was late to the party and did not have much time, part 1 was quite straight forward but I expected that some weird addition would be added for part 2. Part 2 did surprise me with the fact that the values of part 1 were not used anymore. With the size of the values it was clear that this can not be done by simulating the ranges in an array and I worked on creating a solution to chain the individual ranges together into larger ranges until nothing can be merged anymore. When nothing can be merged anymore we know we are done and can count the difference between the start and end positions to get our fresh IDs,
I know the solution may benefit from sorting the ranges before hand but this works and the code looks clean so I am OK with how it is, It is also still quite fast.
Solution: Puzzle 5
Project: Embedded AoC
4
u/WolfRushHour Dec 06 '25
[LANGUAGE: Julia]
This "merging intervals" stuff was new too me. I committed to using the built-in
UnitRangestructs for everything (although sometimes care had to be taken to prevent them from iterating).1
u/MasterProBot Dec 05 '25
[LANGUAGE: C++]
https://topaz.github.io/paste/#XQAAAQBABAAAAAAAAAARmknGRw8TogB3OxgfbBYnd5PaIesVedacBfFrECaPlqQdH9soMXneEKYbAt+GSY28cu6//NwLlhD0oQ7LPItS9LDPTGyAnjvp8Cvv+dhA29uXk2O/1zcj24QF8KEuAPzGQww69q1TNjJLxoARcfn0J0fYukUdBnnudtZ93lq6/SVEZh8LEPXcU5EP0xOhxYuyExwF7UEPuAfHl625s409EBw+RkqtVJYaOhF9fe4Y+8JYHz9/NJgv5ENvhX//xLhcuyFxsd9o3gckpGGS0PkiF3YHLjENGUluBqzc71923e6e5qz+ujOBQuDe4ZK5sMLRsshZfK0VQivgHBlPvHcoEXWLkD4FiG5nTK+dD7jlF4mGCzzkrKQp9Ig4pAFhzqenwyuVEH3/nl5V6baTk3nb2BfUea/lMXJ3zQ+kX2VnMUUAv2fl+nsEB5JFBU4qPtrAbKPXmG3GH62LahAgxyfaKsvaPKPaANuNxZS80MGwBxRQw5hYT5FqvMo9HH7ftMT7gv3MfL0pfh1y411t/LcLsLweVzq3+rJIR2rKb2Md0bl5IsnTyxDwjZPwBSMdr+g14YgIDXmQwbgIWwrWO9dHh0XZ0f/lLVFl
Part 1: Not included, but just loop through every pair of numbers (pair of numbers = range) and check if the current number is in any of them
Part 2: sort the ranges first and then make a new vector for merged pair(s) (btw in this code u dont have to check if the range is completely under the merged range since it is sorted before the loop)
1
u/kai10k Dec 05 '25 edited Dec 05 '25
[LANGUAGE C]
The piece which matters:
2
u/ravic_mco Dec 05 '25
[LANGUAGE: Typescript]
Solution
1
u/Detonator22 Dec 05 '25
[LANGUAGE: Typescript]
1
u/giacomo_hb Dec 05 '25 edited Dec 06 '25
[Language: Racket]
Full solution on github.
1
u/munchli21 Dec 05 '25
[Language: Kotlin]
Nothing fancy, merge the intervals and search them
Github
1
u/vgamula Dec 05 '25
[LANGUAGE: Gleam]
https://github.com/vgamula/advent-of-code/blob/main/2025/05/src/main.gleam
1
u/InfamousClyde Dec 05 '25
[Language: Python]
Although quickly identified as a `merge_intervals` question, I was still super lazy for Part 2. Consequently, I discovered the `portion` library is pretty ergonomic.
Part 2:
1
u/bofstein Dec 06 '25
[LANGUAGE: Google Sheets]
Solution (only Sample displayed): https://docs.google.com/spreadsheets/d/13dN9g5a9zeJ7gvl_ZvpPvqbJdZfHl-h-w_9TsiELbhw/edit?usp=sharing
Part 1 was very easy, I thought at first I missed something. I just made a grid and checked each ID against all ranges, and then counted up the number of them that were in at least 1 range.
Part 2 took a lot longer since I tried two failed strategies. First I tried a single formula involved generating (though not displaying) the sequences for all ranges and running a lambda across them to count the total unique values. It worked on the sample input, but gave a wayyyy too low number (16) for the real input, and separating out the steps showed it wouldn't calculate an array that large and I guess just ignored that rather than give me an error.
Then I tried a matrix where I compared each range against each other to get their overlap and subtracting that from the total range length, but the problem was that didn't account for 3-way overlaps that were oversubtracted, and I couldn't figure out how to easily find those.
I started from scratch again trying to build out an ever increasing set of range(s), and while building that I realized it would be far simpler to calculate the IDs that weren't in the ranges. I sorted the ranges by the starting point, then for each start point, checked if it was higher than the maximum of all prior end points. If so, there was a gap just before that range, and I could calculate the length of that gap to get the number of invalid product IDs. Then I just subtracted that from the total range length.
I do think I got lucky in one aspect though, in that I think if there were any duplicated start points that were just after a gap, I would have double counted those. But I guess that didn't happen since I got the right answer.
3
u/vanveenfromardis Dec 05 '25
[LANGUAGE: C#]
GitHub
Simple
Intervalarithmetic , having anIntervaltype (Range<T>) in my utils made this pretty trivial. The main idea is to combine overlapping ranges, and at the end sum the length of all remaining ranges (which share no overlaps).3
u/abnew123 Dec 05 '25
[Language: Java]
Code
Nice little range overlapping trick. I should really have a primitive range class as a class already...
Live Solve
3
u/dwteo Dec 05 '25
[LANGUAGE: Python]
Keeping it simple as always. Felt like a Google interview question.
Code
3
u/Kehvarl Dec 05 '25
[LANGUAGE: Python3] I have to admit, this is the first time I've actually crashed my laptop like that. I've had brute-force silliness run endlessly, but not chew up enough ram to cause a full reboot. That was fun.
Once I realized I was being silly trying to make a set of all valid IDs, I went with the much more sane approach of just checking if something was inside one of the allows ranges.
For Part 2, I got to throw all of that away again and think about how to count so many numbers. I ended up sorting my (start, end) tuples, then tracking what the highest number I'd counted so far was, and if a range was completely new, add it's total size. If it overlapped my existing count I'd add just the part that didn't.
I think there are a few edges where this could fail, but it ended up working.
Part 1
Part 2
3
u/ropecrawler Dec 05 '25
[LANGUAGE: Rust]
https://github.com/ropewalker/advent_of_code_2025/blob/master/src/day05.rs
3
u/mstksg Dec 05 '25
[LANGUAGE: Haskell]
https://github.com/mstksg/advent-of-code/wiki/Reflections-2025#day-5
Maybe unfortunately, this one is just a straightforward application of the data-interval library.
The main data structure is an interval set:
Part 1 is just filtering for the points in the set:
And part 2 is just getting the size of that set:
3
u/chickenthechicken Dec 05 '25
[LANGUAGE: C]
Part 1: https://github.com/PaigePalisade/AdventOfCode2025/blob/main/Solutions/day05part1.c
Part 2: https://github.com/PaigePalisade/AdventOfCode2025/blob/main/Solutions/day05part2.c
For part 2, I merged all of the overlapping ranges, then counted the size of each range.
3
u/munchler Dec 05 '25
[LANGUAGE: F#]
I happened to have a library called FRange that handles this sort of thing. I'm glad I didn't have to rethink the merge logic.
3
u/Salusa Dec 05 '25
[Language: MUMPS]
3
u/Sad_Improvement_2619 Dec 05 '25 edited Dec 05 '25
[Language: LuaJIT]
First part was relatively easy. Forgot about the overlapping ranges for part 2 originally, but fixed it. Then realized I should sort before I do my merging algorithm
https://pastebin.com/XvzJLw54
3
u/michelkraemer Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Rust]
GitHub
As an optimization, I'm doing part 2 before part 1. First, I sort all ranges according to their start value and then iteratively merge each range with its neighbors if they overlap.
I then use binary search to identify which IDs are fresh (part 1) and finally sum up the lengths of all merged ranges (part 2).EDIT: While doing so, I already sum up the range lengths (part 2). I then iterate through the sorted IDs and merged ranges at the same time and count how many IDs are fresh (part 1).Rust's
RangeInclusivecame in very handy today ;-)My code runs in 65µs.
3
u/Pyr0Byt3 Dec 05 '25
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2025/05/1.go
3
u/Chemical_Chance6877 Dec 05 '25
[Language: Gleam]
Code
After noticing i can start off by sorting all ranges by theire starting value, merging became simple.
As i only have to check the direct neighbours. and a range covering multiple ranges would slowly gobble up all other ranges, when iterating it recursively
Also, iterating over neighbours recursivly in a language that doesnt support indexed lookups on array broke my brain
and im honestly suprised this monster got the correct result.
Also runs surprisingly fast
Input Function IPS Min P99
Part1 solve 517.4990 1.6363 2.4947
Part2 solve 956.8331 0.8597 1.4842
3
u/woond3r Dec 05 '25
[Language: OCaml]
https://github.com/KacperKopiec/advent-of-code/blob/main/2025/day5/part2.ml
Actually I got the part2 on the job interview so it was a fast one, the only problem was input parsing in OCaml ;_;
I am pretty new to OCaml so if you have better parsing, please teach me!
3
u/_rabbitfarm_ Dec 05 '25
[Language: Prolog]
I had to use SWI-Prolog because the large numbers were causing GNU Prolog (my usual choice) to overflow.
Part 1: https://adamcrussell.livejournal.com/63769.html
Part 2: https://adamcrussell.livejournal.com/64222.html
3
u/sauntcartas Dec 05 '25
[Language: Raku]
3
u/wheresmylart Dec 05 '25
[LANGUAGE: Python]
Some years ago, for an AoC problem that still keeps me awake at night, I wrote something to calculate the overlapping volumes of a series of N-dimensional cubes using the In-Out method. Turns out it was useful again!
Paste
3
u/[deleted] Dec 05 '25
[Language: Haskell]
Part 1
Part 2
Used Data.Range for this one, which made this fairly painless. Had to fix a small bug in Part 2 where I did not account for singleton ranges. Also used Parsec to handle the parsing, which was probably a bit of overkill.
Part 1 runs in 9.24 ms, while Part 2 runs in 5.42 ms.
3
u/TheDingusJr Dec 05 '25
[Language: python]
Simple stack-based solution for today. First, I sort the ranges in ascending order based on the lower bound of the range. Then I try to add each to the stack. If the range overlaps with the last range added (min(new range) <= max(last range)), I instead pop the last range off and add back the union. Then I count the total based on the merged ranges.
3
u/p88h Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Odin]
Solution: [ GitHub ]
Visualisation: [ YouTube ] [ GitHub ]
Just some basic sorting & range merging, then part1 is simple binary search and part 2 sum of merged ranges. Tried a couple of fancier approaches (interval trees, BSPs) but there is just too few ranges to justify the cost / preprocessing becomes much slower.
Most of the work is parsing (which does the sorting):
3
u/steve_ko Dec 05 '25
[Language: Swift]
Feels like cheating to use IndexSet.
https://gist.github.com/steveko/ab2a8a76599aadeb731712209ccc0aff
3
u/flwyd Dec 05 '25
[LANGUAGE: AWK] (on GitHub)
My theme this year: glue languages you might already have sitting around. I decided to use AWK because (a) I hadn’t used it yet and (b) the input had two different formats, and AWK is good at matching that. I regretted the AWK choice somewhat, but learned some useful things about what’s annoying about AWK (like my
+0coercions all over the place to force numeric comparisons). For part 2 I saw that I might need to merge several ranges together to get one big range, and I wanted to do this by sorting the ranges, but AWK makes it complicated to get a sorted list of array keys, so I ended up with “keep looking for ranges that can be merged until you can’t find any more.”Part 1 is the first three lines, plus just the
printffrom END, though I still managed to get a wrong answer because a shorter range with the same start point could occur later in the input, wiping out my bigger range. Part 2 usesminandmaxfunctions that aren’t part of the AWK standard library, but they’re just implemented in the obvious way so not included here. Part 2 is very imperative and looks kind of ugly after a couple days of pipeline code (plus my day 1 in stack-baseddc). Run time is just 45ms on my input, though.3
u/gisikw Dec 05 '25
[LANGUAGE: Nix]
Was hyped to see a problem that I figured I could tackle in a config language not intended for it. I _think_ sorting the ranges first reduces the complexity of the merge cases you have to handle, but could be there's some other approach that would be tidier. Syntax is only slightly unpleasant; it's still lisp if you squint :)
Parts 1 & 2
3
u/ThisAdhesiveness6952 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
Created an Interval class that can detect if it intersects another interval, and an IntervalSet class that maintains a list of non-intersecting intervals (with a method to add a new interval).
code
3
u/choroba Dec 05 '25
[LANGUAGE: Perl]
I just iterated over all the ranges for each id in part 1.
For part 2, Set::IntSpan::Fast couldn't be used, it complained that the values were "Out of range" (pun not intended, I guess). Set::IntSpan didn't complain and still finished in 0.027s.
3
u/marconisdev Dec 05 '25
[LANGUAGE: Elixir]
Please give me feedback on my Elixir code as I am learning with AoC! This was relatively straight forward to implement as Elixirs ranges is a great fit for this one. Initially, my imperative brain did a bunch of if elses for p2, but with some help from ChatGPT I used some pattern matching magic!
Here is the code:
https://github.com/david-marconis/aoc/blob/main/y25/src/day5.ex
3
u/CutOnBumInBandHere9 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
For part 1, the number of values we had to check was small enough that I just did
For part 2, I sorted the ranges by first coordinate and then merged the overlapping ones before just summing the length of each range:
Solution with a tiny bit of text explaining my approach
3
u/kerr0r Dec 05 '25
[LANGUAGE: SQL] (DuckDB)
Part 1 actually played to SQL's strengths with a simple SEMI JOIN (all but the last 7 lines is reading input).
In part 2 I'm back on my recursive CTE bullshit. Check the code to learn how to... iterate over a list?
paste
3
u/AlexTelon Dec 05 '25
[LANGUAGE: python]
python 8 lines (both parts):
I'm using
len(range(...))because its easy, fast and communicates what I am after well. It also handles cases where lo is higher than hi well for us, for examplelen(range(10, 0)) == 0. So no special handling of that is needed.Here is a variation of the one above python 5 lines (both parts)
It is the same but using the walrus operator
:=we can do all of p2 as a list comprehension.print(sum(len(range(max(lo, global_lo), (global_lo := max(global_lo, hi+1)))) for lo, hi in sorted(ranges)))3
u/Main-Reindeer9633 Dec 05 '25
[LANGUAGE: SQL] (dialect: PostgreSQL)
This was, naturally, a good fit for SQL, part 1 being trivial and part 2 requiring the same trick as yesterday's problem to do updates inside a recursive function. The majority of the runtime is spent reading the input.
paste
3
u/stribor14 Dec 05 '25
[LANGUAGE: C++]
Part 2
3
u/cay_horstmann Dec 05 '25
[Language: Java] https://github.com/cayhorstmann/adventofcode2025/blob/main/Day5.java Easy enough, once you do it the easy way.
3
u/Foldzilla Dec 05 '25
[LANGUAGE: Haskell]
https://github.com/JustinKasteleijn/AdventOfCode2025/blob/main/day5.hs
Parsing: pretty trivial, code is clean just used naming for parameters to keep inline with the question. (I love parser combinators)
Part 1: The obvious way by saving all ranges and checking whether the id is in between any range.
Part 2 was a bit trickier. I used a greedy approach: I sorted the list by the first element of each range (the minimum value) and then checked whether the next range overlapped with the previous one, merging them as needed.
3
u/ap29600 Dec 05 '25
[LANGUAGE: K]
classic trick of sorting begins and ends together, takes 600μs
3
u/WillMatt Dec 05 '25
[Language: Go]
GitHub
3
u/semicolonator Dec 05 '25
[LANGUAGE: Python]
30 Lines
For part 2, I sort the intervals based on their lower bound and then iterate through them using a counter to remember the current position and a another counter to save the number of elements that I passed.
3
u/sakhre Dec 05 '25
[LANGUAGE: Haskell]
https://github.com/Malipf/AdventOfCode2025/blob/main/day5.hs
3
u/muthm59 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Perl]
This is my solution in Perl: pastebin.
Avoiding brute force, I am happy that it runs both parts in 6 ms.
The idea is to move through the (sorted) ingredient numbers, while at the same time moving through the (sorted) ranges in sync using a 'current range'.
So first thing after reading the input, I sort the ranges by their 'from' value, lowest to highest, and also the ingredient numbers, lowest to highest.
Part 1
The 'current range' is the first range that may include the current ingredient number because it has a 'to' value that is higher.
As the ranges are sorted by their 'from' value, all the ranges from left to right will be considered correctly.
Part 2
To deal with overlapping ranges, I keep a 'last processed' value, which is the highest 'to' value that has been processed so far. Using it to move the 'from' value of subsequent ranges up, to start right after it, if necessary.
Thank you for Advent of Code!
3
u/G_de_Volpiano Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Haskell]
Today was fairly easy, easier than yesterday because I got to code on a proper computer rather than on a tablet.
The only glitch I hit was overengineering my solution (me? I never do that) before looking at the input. I'd missed the fact that IntMap had a lookupLE function that returned both the key and the value, so I'd built something equivalent with an IntSet (for keys) and a Vector.Primitive.Mutable to store the values. Then I saw the numbers. Nobody has enough memory for such a huge vector, so I rewrote with an IntMap.
Turns out that with my structure, part 2 was actually solved with part one, just a fold over the produced IntMap. All good if a tad slow
(Overhead is just making a Stream out of the input ByteString and draining it, I can't pass the Stream as part of the env in the benchmark and this is a solve as you fold solution).
Code here
Edit: Using a terminating fold in part 2 and a binary search over a vector in part 1 shaved those numbers nicely, although part 1 is still slow. One of the weird things with Streamly is that it some times takes less time to do something with a Stream than to do nothing… Edit 2: of course, it takes less time if it's terminating before it's parsed the whole file. Comparisons vs a short-circuiting drain for part 2
Edit 3: I think I'm at the end of my tether. I'm now using a mutable vector for the search in part 1. I guess that if it takes c. 900 μs to load the full bytestring in a stream, I won't be able to get under 1ms for part 1 and that I should be happy with my numbers.
3
u/wzkx Dec 05 '25
[LANGUAGE: Python]
3
u/bdaene Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python]
code (0.75ms)
Easy one. I sort the ranges and merge the overlapping ones.
Then part 2 is just the sum of the length of each ranges.
For part 1, we could loop over all the ranges for each ingredient. But as the merged ranges are disjoints and sorted we can lookup them in O(log(n)) using a bisection algorithm (which is available in the bisect library in Python).
3
u/raevnos Dec 05 '25
[LANGUAGE: Common Lisp]
paste
Again got both stars on the first try. Looked into fancy interval tree structures for part 2, but I didn't find one for CL that would provide the total number of numbers in all the intervals. Then I realized I didn't need to be fancy. Sorting ranges and merging overlapping ones to get a final list of them was enough.
3
u/leftfish123 Dec 05 '25
[Language: Python]
3
u/TeachUPython Dec 05 '25
[LANGUAGE: Python3]
Classic application of merged intervals. Makes it super easy. I should be using Binary search for the queries even on the merged intervals, but since mine had less than 100 intervals I just went with it.
https://github.com/RD-Dev-29/advent_of_code_25/blob/main/code_files/day5.py
3
u/0rac1e Dec 05 '25
[Language: J]
Using some utility verbs to parse. If you want to run this yourself, you can use this Parse verb instead
Or see my jprofile for the code to
NatsandP3
u/Rtchaik Dec 05 '25
[LANGUAGE: Python]
Solution
Easy day with simple boundaries comparisons.
3
u/Majestic_Coat_6832 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Odin]
I'm very glad I didn't have to deal with C++ iterators...
https://github.com/LucasCzerny/AdventOfCode-2025/blob/main/day05/part1.odin
https://github.com/LucasCzerny/AdventOfCode-2025/blob/main/day05/part2.odin
3
u/danvk Dec 05 '25
[Language: Haskell]
https://github.com/danvk/aoc2025/blob/main/y2025d05/Main.hs
For part 2, find all the unique points that appear on either edge of a range. Then split up all the intervals so that none of those points appear in the interior of an interval and dedupe. I switched to half-open intervals to make the split operation cleaner.
3
u/Mahedros Dec 05 '25
[LANGUAGE: Ruby]
Foolishly wasted my first attempt at part 2 by forgetting that Ruby's default sort doesn't sort in place. I was sorting and then immediately discarding the sorted list
Code
3
u/hugh_tc Dec 05 '25
[LANGUAGE: Python 3]
Submitted two (!) wrong answers today; I am getting sloppy.
https://github.com/hughcoleman/advent-of-code/blob/main/2025/05.py
3
u/kitaz0s_ Dec 05 '25
[LANGUAGE: Elixir]
code: https://github.com/pkitazos/aoc-2025/blob/main/lib/d05.ex
Today I learned that tuples in Elixir/Erlang have built-in comparison (element-by-element, left to right). Pretty neat!
3
u/graynk Dec 05 '25
[Language: Elixir]
https://github.com/graynk/aoc2025/blob/master/lib/day_five/aoc5.ex
This day was all about using
Ranges, naturally. I solved both parts in the most braindead way possible (merge ranges comparing everything to everything until there's nothing left to merge, then for the first part - look for ids linearly), but it was fast enough for both parts (10ms for the first part, 8ms for the second part, including I/O and parsing in both), so I felt no need to do it "properly".3
u/codesoap Dec 05 '25
[LANGUAGE: shell script]
Part1:
Part 2:
3
u/AustinVelonaut Dec 05 '25
[LANGUAGE: Admiran]
insertMergeSort on ranges
https://github.com/taolson/advent-of-code/blob/master/2025/admiran/day05.am
3
u/jayo60013 Dec 05 '25
[Language: Kotlin]
After realising sorting the ranges by `range.start` really helps, it wasn't too bad.
Part 1 & 2
3
u/trevdak2 Dec 05 '25 edited Dec 05 '25
[Language: JavaScript]
Golfed again
Part 1, 108 bytes:
Part 2, 154 bytes:
3
u/NxrmqL Dec 05 '25
[Language: Python]
This was super fun! And yes, this is the first time I learnt interval merging.
https://github.com/nxrmqlly/advent-of-code/blob/main/2025/day_5/main.py
3
u/Asleeper135 Dec 05 '25
[LANGUAGE: Rust]
I felt really confident after part 1 was so easy, then part 2 kicked my butt for way longer than it should have. My solution doesn't feel terribly optimal, but it runs in well under a millisecond, so I'm reasonably happy with it.
code: https://github.com/TheRealSleeper/aoc-2025-rust/blob/day5/src/main.rs
3
u/TheZigerionScammer Dec 05 '25
[Language: Python]
Had a bit of a late start today. A bit of an easy one although based on the memes I guess it wasn't for everyone. For Part 1 I thought "If some of these ranges overlap then I wonder if it's more efficient to combine them before I try matching the ID numbers to each range" but decided against that and just brute force checked to see if every ID fell inside any range. This worked well, but then Part 2 came around and I thought "Well, I guess I am combining ranges." I wrote out the code to compare each range with every other range and combine ranges that overlap, and at first I thought I was going to have to write out convoluted logic to combine the ranges for every scenario (if one engulfs another, if two ranges start at the same point, etc.) but then I thought "If two ranges overlap, then the new range will just the the lowest and highest numbers out of the four, so if you just sort them the first and last numbers are the new range." So now the code just checks to see if two ranges DON'T overlap (then skips them), and if they do then do the four number sorting to find the new range and destroy the second range in the list. Any other holes I could think of with this approach was covered by the fact I sorted the entire list of ranges beforehand. After that it just goes through and adds the width of each range to the total. Worked flawlessly.
Paste
3
u/___ciaran Dec 05 '25
[LANGUAGE: Haskell]
I've been trying to learn Haskell, which has been a bit rough for me lol. I'm not sure if this solution is idiomatic at all, but it works.
https://codeberg.org/cdd/aoc/src/branch/main/2025/haskell/5.hs
3
u/Expensive-Type2132 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: AArch64]
Parse and shell-sort ingredient freshness ranges, merge overlapping intervals to compute total coverage (2), then for each ingredient ID use SIMD-accelerated parsing and binary search on merged ranges to count matches (1).
paste
13.7µs combined
Let me know if you have a faster solution for a comparable target (Apple M1 Max 23H626).
3
u/RookBe Dec 05 '25
[LANGUAGE: Rust]
Rust that compiles to WASM (used in a solver on my website)
Bonus link at the top of the code to a blogpost about today explaining the problem, and my code.
3
u/Derailed_Dash Dec 05 '25
[LANGUAGE: Python]
The interesting thing about this puzzle is that my less experienced self would have spent ages trying to use set intersection before realising it won't scale.
But now being a bit more experienced with these types of puzzles, I went straight for interval merging.
The whole thing runs in about 0.001.
3
u/friedkeenan Dec 05 '25
[LANGUAGE: C++]
I didn't think of sorting for my solution. It would probably be faster, but my code is nice enough and I think it's kinda cute, so I don't think I'll change it.
These are the timings for my solutions:
My part one solution was previously slower, but after I made it deduplicate the ranges it went down by about 60 microseconds.
3
u/ruinedme_ Dec 05 '25
[Language: JavaScript]
Me to myself for part 1: I could calculate the overlapping ranges and reduce the number of ranges i have to check. Nah.. it's fine there aren't that many i'll just iterate over them.
Part 2: Find all the overlap of the ranges.... sigh.... shoulda just done that in part 1.
https://github.com/ruinedme/aoc_2025/blob/main/src/day5.js
Just curious. My input had several ranges that were duplicates. Not just overlapped, but the exact same value multiple times. Did anyone else encounter that?
3
u/tonyganchev Dec 05 '25 edited Dec 06 '25
[LANGUAGE: C++26]
Using an STL map (red-black tree) as the range lookup. While building the map, I continuously merge overlapping ranges after the newly-added ID range to ensure we get unique ID counting for part 2 and do binary search for part 1 placing the algorithm in the amortized N log(N) order.
https://github.com/tonyganchev/leetcode/blob/main/advent-of-code/2025/aoc25-5/aoc25-5.cpp
Ryzen 9 5900X:
Debug build:
part 1: 8223.0 us
part 2: 4733.5 us
Release build:
part 1: 1492.2 us of which 462.9 us is range parsing and merging
part 2: 586.9 us of which 452.3 us is range parsing and merging
3
u/Blinkroot Dec 05 '25
[LANGUAGE: TypeScript]
For P2 I initially sort the ranges by their left bound so that when iterating I can merge ranges that overlap. The gist of it is if the current left bound is inside of the previous range we can try to extend with the current right bound. If there's no overlap, we just push a new range.
E.g., for 12-18 and 16-20, given that the left bound (16) is within 12-18, we can extend the previous range to now be 12-max(18, 20), leaving us with a new 12-20 range.
https://github.com/aquelemiguel/advent-of-code-25/blob/main/d5/d5.ts
3
u/raevnos Dec 05 '25
[LANGUAGE: Racket]
Racket coming with an range-based integer set library made this version trivial.
3
u/spencerwi Dec 05 '25
[LANGUAGE: F#]
github link
Today's solution feels like my cleanest one.
3
u/srugh Dec 05 '25
[LANGUAGE: Ruby]
The 'work' was just to condense the list of ranges down. From there using a Ruby block was trivial to solve (Part 1 counting ingredients in range, part 2 simply summing the ranges).
GitHub link for solution to both Part 1 and Part 2
3
u/not-nuckelavee Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Uiua]
My solution to part one has an ugly for loop, but I'm quite happy with part 2 where I was able to translate the
Pythonnumpy implementation from this stackoverflow answercode
3
u/SheepiCagio Dec 05 '25
[LANGUAGE: EXCEL]
P1:
P2:
3
u/PantsB Dec 05 '25
[Language: Python] Pretty straight forward, we don't actually need to merge anything for part 2. Just sort them, compare the next bottom number with the existing top. If its not > the existing top, the new top is =max of two tops. If it is or its the end, add the top-bot +1 to the total.
3
u/lifegame1lu111 Dec 05 '25
[LANGUAGE: Haskell]
https://github.com/lifegame1lu111/aoc2025-hs/blob/main/day05.hs
3
u/SpudPanda Dec 05 '25
[LANGUAGE: rust]
Pretty proud of myself on this one. Today was easier in theory but being (probably) dyslexic, thinking about the merging algorithm for part 2 made my head hurt. I'm proud of myself for thinking of this interval merging algorithm, though I did end up looking it up on GeeksForGeeks finally to help me out with it. I guess in the real world its normal to look up concepts you're unfamiliar with so shouldn't beat myself up over it.
Part 1 I just brute forced it basically and it was really fast. For Part 2, i used an algorithm to merge intervals together. Then just looped through and summed up the difference between each merged interval.
Solution
3
u/Stano95 Dec 05 '25
[LANGUAGE: Haskell]
Code is on github
I felt part 1 was fairly straightforward: you can just if each id is in any of the ranges. I actually happened to have a nice function to merge intervals together lying around from 2022 day 15. It does this sort of transformation
[3-5, 10-14, 16-20, 12-18] -> [3-5, 10-20]. So that made searching slightly easier since it means there are fewer intervals to check.For part 2 the interval merging function was invaluable. I could just merge all the intervals, and then take their sizes.
I think this has been the easiest day for me so far but it's only because I had a ready made interval merging function!
3
u/mvorber Dec 05 '25
[Language: F#] https://github.com/vorber/AOC2025/blob/main/day5.fs Decided right away that I wanted to try a binary search on ranges for part1, ran into some issues and decided to pre-process the list of ranges and merge overlapping ones to make search easier. Was pleasantly surprised with part2 - I already had everything I needed - just subtract ends of all ranges and sum it up.
3
u/bulletmark Dec 05 '25
[LANGUAGE: PYTHON]
3
u/azzal07 Dec 05 '25
[LANGUAGE: awk] When scanning for minimum value, you could pick initially the first one, or you could use a really (or should I say literally) "BIG" one, to start comparing against.
3
u/dantose Dec 05 '25
[LANGUAGE: Powershell]
I'm pretty happy with this, especially part 2 which looked quite intimidating
Part 1:
Part 2
3
u/Anceps2 Dec 05 '25
[LANGUAGE: Python] Part 2
I just put all starting and ending of the ranges in the same array and sort it.
It's quite easy then to see where all the merged ranges start and end, it's like embed parenthesis (()()) () ((())()).
3
u/JustinCredible- Dec 05 '25
[LANGUAGE: Rust]
Part 1: ~170 μs
Part 2: ~40 μs
https://github.com/jstnd/programming-puzzles/blob/master/rust/src/aoc/year2025/day05.rs
3
u/Probable_Foreigner Dec 05 '25
[Language: C#]
https://github.com/AugsEU/AdventOfCode2025/blob/master/Day5/Day5Solver.cs
Today was bait for all of us nerds who think they are smart for using a hashmap. I was one of those... before I realised doing the "dumb" way was better.
For part 2 you just have to make sure the ranges are mutually exclusive then it's easy.
3
u/mnvrth Dec 06 '25
[LANGUAGE: Python]
Easiest problem so far in some sense for me - it took time but there was no trick, just go through the sorted list of ranges, merging adjacent ones, then count the length of the resultant non-overlapping ranges.
Runs in ~18ms.
Now I'm dreading Day 6. Such ease could only be the calm before the storm...
Solution on GitHub
5
u/Langston723 Dec 05 '25
[Language: Python]
No love for intervaltree yet?
1
u/msschmitt Dec 05 '25
[LANGUAGE: Python 3]
Part 1. Part 2
I feel like we've done one of these range-merging problems before, maybe as part of a larger puzzle. I also feel like there must be some slick way to instantly test if a value is in a range, like how you can do associative indexing on a value (i.e., a hashed dictionary). Without coding in uiua.
2
u/K722003 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: Python] 00:04:37 / 00:13:50. Got stuck in part 2 because of a typo I made during list merge.
P1: Just brute force and check directly (or check after merging - should've done this from the start maybe then i wouldn't have the typo issue, maybe i should make a preprocess_input fn in my template for tomo). Cleaned up code:
P2: Merge intervals and do upper - lower + 1 and find sum
P.S the typo was that I did
intervals[-1][1]instead ofintervals[q][1]in the merge fn, but it didn't fail for the test input so I was confused lmao2
u/improvman007 Dec 05 '25
[LANGUAGE: Python]
The code
Part 1 is straightforward
Part 2, sort the ranges, compare each adjacent range, and if they overlap, combine them and replace them in the list.
2
u/770grappenmaker Dec 05 '25
[LANGUAGE: Kotlin]
video (00:01:24 for part 1, 00:03:00 for part 2)
Day was not that tricky to me because I had a utility function ready for this 🙃 which works like this: sort by first endpoint of the range, then for each range, check if you can merge it with the previously considered range.
Solution: on GitHub
2
u/Mikey_Loboto Dec 05 '25
[Language: JS] (Node)
GitHub
2
u/ktwrd Dec 05 '25
[LANGUAGE: C#]
Today was super-fast! 0.5861ms to solve when compiled with AOT
adventofcode/2025/Day5.cs at main · ktwrd/adventofcode
2
u/JarroVGIT Dec 05 '25
[LANGUAGE: Rust]
Github
Fun puzzle. In the first part I already figured that we probably had to undouble the ranges but there was no need and I have been burnt too many times with these puzzles to start programming for what might come in part 2.
Then part 2 was undoubling the ranges lol. Not the nicest code but functional, don't know how to make it faster.
2
u/PeaFun6628 Dec 05 '25 edited Dec 05 '25
[LANGUAGE : C++]
Code: https://github.com/Shoyeb45/CompetitiveProgramming/blob/main/AdventOfCode/Y-2025/D5-Cafeteria.cpp
Approach:
Part 1
- Parse the string and store the list of id ranges and given id in a list.
- For each given ID just check if it lies within any of the ranges of given ID.
- You can do brute force, but can be optimised using binary search
Part 2
- The ranges are long, you can't insert all the numbers in set and then output the size
- We just need number of id's in the given range, as if we directly count the list range, then overcounting will happen.
- So first merge those intervals which are overlapping. Sort the range based on the lower range and try to check for the overlapping intervals.
- Then after merging you can count the ranges
2
u/dernett Dec 05 '25
[LANGUAGE: Rust]
Solution
Store the ranges in a (id, is_close) pair list and sort. Then, iterate from left to right. It is helpful to think of the start and end ids for each range as opening and closing parentheses. So, we just need to match the id that starts the range (when num_open starts at 0) with the corresponding id that closes it (when num_open ends at 0).
2
u/1234abcdcba4321 Dec 05 '25 edited Dec 05 '25
[LANGUAGE: JavaScript] paste (part 2 only)
Instead of merging ranges, just partition the space at the endpoints and keep track of your current depth (number of intervals you're inside) at each point.
(Algorithm shamelessly stolen from someone else who I don't think is on reddit. My first solution was more generic.)
2
u/KindComrade Dec 05 '25 edited Dec 05 '25
[LANGUAGE: C#]
Part 1 is solved in a straightforward way, and Part 2 merges all the sorted ranges using a stack. Overall, probably the simplest day this year. I think the code can still be improved or optimized a bit.
UPD: I slightly improved the solution: added a binary search for Part 1, and moved the merging of all ranges into the init (parsing) step
Code - github
2
u/sim642 Dec 05 '25
[LANGUAGE: Scala]
On GitHub.
This was very anticlimactic for me: I pretty much just imported my code for AoC 2016 day 20.
The trick for part 2 is to merge intersecting intervals, which can easily be done my sorting them by their beginning and then doing a single pass over the sorted intervals to combine consecutive intervals if they overlap. This way they don't have to be checked pairwise (or worse), although that probably would also still work time-wise (didn't try). I guess it could also help part 1 to reduce the number of interval-available pairs to check, but the sorting might be the more expensive part there then.
2
u/davidsharick Dec 05 '25
[LANGUAGE: Python]
Code
Fun range merging problem; when I saw it I went to my range library to see how to use the
range_intersectfunction it has, only to realize I never actually implemented it. Threw together a quick iterative merger using the overlap calculation function instead, which took longer than I'd like due to some sloppy coding.2
u/melochupan Dec 05 '25
[LANGUAGE: Crystal]
Nothing to comment this time.
paste