Merge Intervals – Solution & Complexity
Quick practice for Merge Intervals: 3 reasoning beats, no typing
Watch: Merge Intervals by sorting
Sort the intervals by start time. Then walk them in order: if the next one starts before the last merged one ends, extend the end; otherwise start a new interval. O(n log n) for the sort, one pass after.
Solution Walkthrough
Step 1: Understanding the Problem
- Given an array of intervals where each interval is represented as
[start, end], merge overlapping intervals. - The goal is to return a list of non-overlapping intervals that cover all intervals in the input array.
- Given an array of intervals where each interval is represented as
Step 2: Sort Intervals by Start Time
- Sort the intervals based on their starting values.
- This will make it easier to detect overlaps by ensuring that any overlapping intervals are adjacent.
Step 3: Initialize Merged Intervals List
- Create an empty list
mergedto store the merged intervals. - The list will eventually contain only the non-overlapping intervals.
- Create an empty list
Step 4: Iterate Through Sorted Intervals
- For each interval, check if it overlaps with the last interval in the
mergedlist. - If it does overlap, merge the intervals by extending the end of the last interval in
merged. - If it doesn’t overlap, simply add it to
merged.
- For each interval, check if it overlaps with the last interval in the
Step 5: Return Merged Intervals
- After processing all intervals, return the
mergedlist which contains only non-overlapping intervals.
- After processing all intervals, return the
Step 6: Consider Edge Cases
- Edge cases include:
- Only one interval, which should be returned as-is.
- Non-overlapping intervals, where each interval is added to
mergedwithout modification. - Intervals that completely overlap each other.
- Edge cases include: