Fix the sweep that merges overlapping intervals

Review the AI's codeEasy10 min

Your task

An AI agent wrote a Java method that merges overlapping intervals, and the example in its docstring works. Rather than trust that one example, your team pins down the choices the spec leaves open and tests each one. You port the method so the tests can run against it.

An assistant wrote merge_intervals(intervals). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • intervals: a list of entries. Each entry is a list of up to 2 integers, normally [start, end], the range of numbers from start to end. Values can be negative, and intervals itself can be empty.
  • Return the merged ranges as a list of [start, end] lists.

Rules the tests check:

  • Skip an entry with fewer than 2 numbers.
  • When an entry's start is greater than its end, swap them: [5, 3] is the range from 3 to 5.
  • Sort the ranges by start, and by end when starts are equal.
  • Walk them in that order. A range joins the current merged range when its start is at or before the merged range's end. The merged end becomes the larger of the two ends. Otherwise the range starts a new merged range.
  • So ranges that share an endpoint merge, ranges inside another range vanish into it, and duplicates become one range.
  • Return the merged ranges in that sorted order. An empty input returns an empty list.

Examples

merge_intervals(intervals: list[list[int]]) -> list[list[int]]
Example 1
Inputmerge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])
Output[[1, 6], [8, 10], [15, 18]]
Example 2
Inputmerge_intervals([[1, 2], [2, 3]])
Output[[1, 3]]
Example 3
Inputmerge_intervals([[1, 10], [2, 3], [4, 5]])
Output[[1, 10]]