Merge Intervals: Simplifying Overlapping Ranges
The "Merge Intervals" problem is a fundamental challenge in array manipulation, involving the combination of overlapping intervals into a minimal set of non-overlapping intervals.
Problem Statement
Given an array of intervals where each interval is represented as a pair [start, end], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example
- Input: Intervals
[[1,3],[2,6],[8,10],[15,18]]Output:[[1,6],[8,10],[15,18]]Explanation: Since intervals[1,3]and[2,6]overlap, they are merged into[1,6].
Solution Approach
Breaking Down the Solution
- Sort Intervals: First, sort the intervals based on their starting points.
- Initialize Merged List: Start with the first interval in the merged list.
- Iterate and Merge: Go through each interval and merge it with the last interval in the merged list if they overlap. If they don't overlap, add the interval to the merged list.
- Return Merged Intervals: The merged list now contains the minimal set of non-overlapping intervals.
Conclusion
The Merge Intervals problem is a classic example of interval manipulation and is critical in many applications, such as calendar events, scheduling algorithms, and time-based data analysis. It emphasizes the importance of sorting and efficient merging in array processing.
Rust Solution
merged.last_mut() hands back a mutable reference to the final interval wrapped in Some, so the if let Some(last) binding lets last[1] = last[1].max(interval[1]) edit the stored interval in place and continue skips the push once a merge lands. The parameter is rebound with let mut intervals = intervals to make the moved Vec<Vec<i32>> mutable for sort_by_key(|a| a[0]). Because for interval in intervals iterates by value, each merged.push(interval) moves ownership into the result rather than cloning.
Go Solution
Go's inner []int is a slice header over a shared backing array, so last := merged[len(merged)-1] aliases the last stored interval and last[1] = curr[1] mutates it in place — no write back into merged is needed. sort.Slice sorts with a less-func comparator, func(i, j int) bool, rather than a sort key. Fresh intervals are added with merged = append(merged, curr), which reassigns the slice header, while the empty-input guard returns an explicit [][]int{} literal.
Comments (0)
Stub — comments live in your browser only (localStorage). No server round-trip yet.
No comments yet. Be the first.