66. Merge overlapping intervals
An interval [start, end] stands for every number from start to end, both included, like a meeting from 9 to 11.
Two intervals overlap when they share at least one number: [1, 4] and [4, 5] share 4, so they join into
[1, 5].
Write a function merge(intervals) that takes a list of intervals, in any order, and returns a list where every group
of overlapping intervals has been joined into one:
- Join intervals that overlap or touch at an end, as
[1, 4]and[4, 5]do.[1, 2]and[3, 4]don't share a number, so they stay apart. - An interval inside another disappears into it:
[1, 10]and[2, 3]give[1, 10]. - Return the merged intervals sorted by their start, each as a list
[start, end]. An empty list gives[].
Example 1
intervals = [[1, 3], [8, 10], [2, 6]][[1, 6], [8, 10]]Example 2
intervals = [[1, 4], [4, 5]][[1, 5]]Example 3
intervals = [[1, 10], [2, 3], [4, 5]][[1, 10]]Constraints
intervalshas 0 to 100 intervals, each[start, end]with whole numbers from -1000 to 1000 andstart <= end.
Submit also runs 8 more tests you can't see.
Practises Lists (lesson 9).
- Sort the intervals by their start first (
sorted(intervals)does that for pairs): then intervals that overlap sit next to each other. - Go through them keeping a list of merged intervals. An interval overlaps the last merged one if its start is at most that one's end.
- When they overlap, the last merged interval stretches to
max(its end, the new end): the new one might lie entirely inside it. Otherwise the new interval starts a fresh merged one.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def merge(intervals):
"""Join the intervals that overlap or touch.
intervals: list of [start, end] pairs, in any order
Returns: list of [start, end] pairs that don't overlap,
sorted by start
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.