Merge Intervals

A coding challenge about Intervals Merging

I finished an interesting coding problem and I want to share it here.

Interval merging refers to combining several overlapping intervals into a single interval. This process is useful in various applications, such as consolidating time slots or ranges of numbers.

Python Function to Merge Intervals

Below is a Python function that merges overlapping intervals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def merge_intervals(intervals):
# Sort the intervals by their starting point
intervals = sorted(intervals, key=lambda x: x[0])
merged = []
for interval in intervals:
# If the current interval overlaps with the last interval in merged, merge them
if merged and interval[0] <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], interval[1])
else:
# If they don't overlap, add the current interval to merged
merged.append(interval)
return merged

# Example usage
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
merged_intervals = merge_intervals(intervals)
print(merged_intervals)
# Output: [[1, 6], [8, 10], [15, 18]]

Process

The process of merging intervals involves:

  1. First, sort the list of intervals based on the start point of each interval.
  2. Then, iterate through the sorted list of intervals. For each interval:
    • If it overlaps with the previous interval in the merged list, combine them into a single interval by updating the end point of the last interval in the merged list to the maximum end point of both intervals.
    • If there is no overlap, simply add the current interval to the merged list.
  3. Return the merged list of intervals as the result.

By following these steps, you can efficiently merge overlapping intervals into a consolidated list.

Posted on

2024-03-17

Updated on

2024-03-17

Licensed under

Comments

:D 一言句子获取中...