Solution for interview question: Merge Intervals
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.
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.
3. Initialize Merged Intervals List
- Create an empty list
mergedto store the merged intervals. - The list will eventually contain only the non-overlapping intervals.
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.
5. Return Merged Intervals
- After processing all intervals, return the
mergedlist which contains only non-overlapping intervals.
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.
