SPRGB - Some (Pseudo) Random Guy's Blog

Advent of Code 2025 Day 2 in under 200us

Optimizing advent of code 2025 day 2

Disclaimer

Problem description

Given a list of integer ranges [start, end], obtain all the distinct invalid IDs contained in each range.

Solution

The solution is to generate only invalid IDs instead of iterating over the entire range and check whether the number is an invalid ID. The algorithm is as follows:

  1. For a given [start, end] range and repetitions number, find the first seed number that generates an invalid ID >= start.
  2. If the generated invalid ID is <= end, add it to the invalid IDs list.
  3. Set seed = seed + 1 and generate the next invalid ID.
  4. Repeat 2 and 3.

Generating the seed

Ideally you want to make an initial guess for the seed value close to the correct one, and increase it as few times as possible until you find the first invalid ID. How do you get the initial invalid ID value given start and repetitions? Looking at some values from the problem statement example:

start repetitions first invalid ID
11 2 11
998 2 1010
998 3 999

If you pay close attention, there are two different cases

Generating an invalid ID

In order to generate an invalid ID for the given seed you have two options.

Using strings

This is the easiest option, you have to convert seed to a string, repeat it repetitions times and convert it back to an integer.

Using integers only

You can generate the invalid ID without strings, using integer arithmetic.

Guessing the formula from two examples:

You want repetitions terms, and each exponent should shift seed as many digits as seed contains. You can obtain the digits of a number via log10(num) + 1, then you can define the number of digits as step, and finally the formula is seed * (10 **(step*0) + 10**(step*1) + ... + 10**(step * (repetitions-1))

Results

You can find the complete solution here.