The Problem
The elves' new inventory system has a database of fresh ingredient ID ranges. You need to figure out which ingredients are fresh and which are spoiled.
Summary
Part | Question | Strategy |
|---|---|---|
1 | How many available ingredients are fresh? | Check each ID against all ranges |
2 | How many IDs total are considered fresh? | Merge overlapping ranges, sum their sizes |
Part 1: Check Against Ranges
Goal: For each available ingredient ID, check if it falls within any fresh range.
Simple linear scan - for each ingredient, check all ranges:
Part 2: Count All Fresh IDs
Goal: Ignore the ingredients list. Count all IDs covered by the ranges.
The catch? Ranges can overlap! We can't just sum up (end - start + 1) for each range - we'd count overlapping IDs multiple times.
The Solution: Merge Overlapping Ranges
Sort ranges by start position
Merge overlapping/adjacent ranges
Sum the sizes of merged ranges
Visual Example
Why last.end + 1?
Adjacent ranges should also merge! Range 3-5 and 6-8 together cover 3, 4, 5, 6, 7, 8 - no gaps.
Performance
Part | Time |
|---|---|
Part 1 | 1.31ms |
Part 2 | 295µs |
Part 2 is faster because we just process the ranges once (O(n log n) for sorting), while Part 1 checks each ingredient against all ranges.