progress

~/problems / Intervals

Punch one point out of a run of ranges

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Databricks

A storage engine tracks live row ids as half-open ranges: [a, b] means ids a .. b - 1 ([4, 7] is 4, 5, 6). The ranges never overlap but are not sorted.

Reading the ranges in list order gives a flat sequence of ids; position is a 0-based index into it. Write

remove_point(ranges: list[list[int]], position: int) -> list[list[int]]

that deletes the id at position and returns the new list:

  • The range holding it is replaced in place by what's left: two ranges, one shorter range, or nothing.
  • All other ranges stay as they were, in order. Don't modify the input.
  • If position is out of range (including any negative position), raise IndexError.
ranges = [[20, 23], [3, 5], [9, 10]]
# flat sequence: 20, 21, 22, 3, 4, 9
remove_point(ranges, 1)   # [[20, 21], [22, 23], [3, 5], [9, 10]]   21 was in the middle
remove_point(ranges, 3)   # [[20, 23], [4, 5], [9, 10]]             3 was the start of [3, 5]
remove_point(ranges, 5)   # [[20, 23], [3, 5]]                      [9, 10] held only 9
remove_point(ranges, 6)   # raises IndexError

Up to 10**5 ranges; ids go up to 10**12.

⭐ Bonus: a speed test with 100,000 huge ranges earns a star in O(number of ranges), without writing out the flat sequence.

Topic: Intervals / sweep line. Sort by start, merge; sweep events for overlaps.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc