Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Summary Ranges

EasyLeetCode 228 ↗

The problem, in one line. Given a sorted list of distinct integers, describe it as the fewest ranges that cover exactly those numbers, writing a lone number as itself and a longer run as first->last. LeetCode 228.

The tell. The list is already sorted, and the answer groups neighbours that are one apart. That is an interval problem in its simplest form: a run is an interval, and you only ever need to know where it stops.

The wrong first idea

Write one range per number, then glue neighbours together afterwards. Or, for each number, search the list for its neighbour.

for x in nums:
    if x + 1 in nums:   # a list lookup walks the list
        ...

The search is the cost. Checking “is the next number in the list?” by walking the list takes n steps, and it is done n times, so 10,000 numbers is about 100 million steps for a job that needs one look at each number. The sorted order already tells you where the neighbour is: it is the very next slot.

The invariant

Stand on the first number of a run. Slide a second marker right while each next number is exactly one more than the one before it. When it stops, the run is finished, and the next run starts at the very next slot.

nums = [0, 1, 2, 4, 5, 7]
start 0: 0,1,2 are one apart, 4 is not -> "0->2"
start 4: 4,5 are one apart, 7 is not   -> "4->5"
start 7: nothing after                 -> "7"

The sentence that stays true every step: everything before the start marker is already written, and the start marker sits on the first number of an unwritten run. Each number is stepped over exactly once.

The solution

def summary_ranges(nums):
    out = []
    i = 0
    while i < len(nums):
        j = i
        while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1:  # the run goes on while each step is +1
            j += 1
        out.append(str(nums[i]) if i == j else f"{nums[i]}->{nums[j]}")
        i = j + 1                                                # the next run starts right after this one
    return out

print(summary_ranges([0, 1, 2, 4, 5, 7]))
print(summary_ranges([0, 2, 3, 4, 6, 8, 9]))
print(summary_ranges([]))
['0->2', '4->5', '7']
['0', '2->4', '6', '8->9']
[]
func summaryRanges(nums []int) []string {
	out := []string{}
	for i := 0; i < len(nums); {
		j := i
		for j+1 < len(nums) && nums[j+1] == nums[j]+1 { // the run goes on while each step is +1
			j++
		}
		if i == j {
			out = append(out, strconv.Itoa(nums[i]))
		} else {
			out = append(out, fmt.Sprintf("%d->%d", nums[i], nums[j]))
		}
		i = j + 1 // the next run starts right after this one
	}
	return out
}

Same three calls print [0->2 4->5 7], [0 2->4 6 8->9], [].

Complexity

  • Time O(n): the inner marker only moves forward, and the outer one jumps to where it stopped, so each number is touched once.
  • Space O(1) beyond the answer: two indices and the output list.

Traps

  • Writing 7->7 for a run of one. The list [7] must give "7", so test i == j before formatting.
  • Setting i = j instead of j + 1 at the bottom. The loop then reads the same run forever.
  • Checking nums[j + 1] without checking j + 1 < len(nums) first. The last run of [0, 1] reads past the end.

Next in the ladder

Merge Intervals swaps single numbers for start-and-end pairs: they arrive in any order, so the first job is to sort them.