891621. Maximal Disjoint Intervals
Medium
Maximal Disjoint Intervals
Slug: maximal-disjoint-intervals Difficulty: Medium Id: 891621
Summary
The problem is about finding the maximum number of disjoint intervals in a given set of intervals. An interval is considered disjoint if it does not overlap with any other interval in the set. The goal is to maximize the number of non-overlapping intervals.
Detailed Explanation
To solve this problem, we can sort the intervals based on their end points. Then, we iterate through the sorted intervals and count the maximum number of non-overlapping intervals.
Here's a step-by-step breakdown of the solution:
- Sort the intervals in ascending order based on their end points.
- Initialize a variable
maxDisjointIntervalsto keep track of the maximum number of disjoint intervals found so far. - Iterate through the sorted intervals, and for each interval:
- Check if it does not overlap with the previously selected interval (i.e., its start point is greater than or equal to the end point of the previous interval).
- If it does not overlap, increment the
maxDisjointIntervalscount.
- Return the maximum number of disjoint intervals found.
Here's a simple ASCII art diagram illustrating the process:
Interval 1: [1, 3]
Interval 2: [2, 5]
Interval 3: [6, 8]
Sorted Intervals:
[1, 3], [2, 5], [6, 8]
Disjoint Intervals:
- [1, 3] (maxDisjointIntervals = 1)
- [6, 8] (maxDisjointIntervals = 2)
Final Answer: The maximum number of disjoint intervals is 2.
Time Complexity Analysis:
- Sorting the intervals takes O(n log n) time, where n is the number of intervals.
- Iterating through the sorted intervals and counting the disjoint intervals takes O(n) time.
- Total time complexity is O(n log n).
Space Complexity Analysis:
- The space complexity is O(1), as we only need a constant amount of space to store the
maxDisjointIntervalsvariable.
Optimized Solutions
Java
import java.util.Arrays;
public class MaximalDisjointIntervals {
public static int maximalDisjointIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[1] - b[1]);
int maxDisjointIntervals = 0;
for (int i = 0; i < intervals.length; i++) {
if (i == 0 || intervals[i][0] >= intervals[i - 1][1]) {
maxDisjointIntervals++;
}
}
return maxDisjointIntervals;
}
}