Learn DSA
Depth-First Search
Greedy Algorithms
Intervals
Non-Overlapping Intervals
medium
DESCRIPTION (credit Leetcode.com)
Write a function to return the minimum number of intervals that must be removed from a given array intervals, where intervals[i] consists of a starting point starti and an ending point endi, to ensure that the remaining intervals do not overlap.
Input:
Output:
Explanation: Removing the interval [4,10] leaves all other intervals non-overlapping.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
"Write a function that takes a list of intervals `intervals` and returns the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping."
Run your code to see results here
Have suggestions or found something wrong?
Explanation
def nonOverlappingIntervals(intervals):if not intervals:return 0intervals.sort(key=lambda x: x[1])end = intervals[0][1]count = 1for i in range(1, len(intervals)):# Non-overlapping interval foundif intervals[i][0] >= end:end = intervals[i][1]count += 1return len(intervals) - count
sort by end time
0 / 1
def nonOverlappingIntervals(intervals):if not intervals:return 0intervals.sort(key=lambda x: x[1])end = intervals[0][1]count = 1for i in range(1, len(intervals)):# Non-overlapping interval foundif intervals[i][0] >= end:end = intervals[i][1]count += 1return len(intervals) - count
i = 1
0 / 1
def nonOverlappingIntervals(intervals):if not intervals:return 0intervals.sort(key=lambda x: x[1])end = intervals[0][1]count = 1for i in range(1, len(intervals)):# Non-overlapping interval foundif intervals[i][0] >= end:end = intervals[i][1]count += 1return len(intervals) - count
non-overlapping interval found
0 / 4
Solution
def nonOverlappingIntervals(intervals):if not intervals:return 0intervals.sort(key=lambda x: x[1])end = intervals[0][1]count = 1for i in range(1, len(intervals)):# Non-overlapping interval foundif intervals[i][0] >= end:end = intervals[i][1]count += 1return len(intervals) - count
non-overlapping intervals
0 / 8
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.