Menu
CoddyTech

Non-overlapping Intervals

Interval i runs from starts[i] to ends[i]. Return the smallest number of intervals you must remove so that no two of the rest overlap. Two intervals that only touch, where one ends at the exact point the other starts, do not overlap.

Function

eraseOverlapIntervals(starts: integer-array, ends: integer-array) → integer
startsinteger-array
the start of each interval
endsinteger-array
the end of each interval, at the same index as its start
Returnsinteger
the fewest intervals to remove so that the rest do not overlap

Constraints

  • 1 ≤ starts.length == ends.length ≤ 5000
  • -5 × 104 ≤ starts[i] < ends[i] ≤ 5 × 104
  • The intervals are not sorted. Two intervals may be identical.

Examples

Input
starts = [3, 1, 5, 2]ends = [6, 4, 7, 3]
Output
2
Explanation
In start order the intervals are [1,4], [2,3], [3,6] and [5,7]. Keep [2,3] and [3,6], which only touch, and remove the other 2. Three cannot stay: [1,4] overlaps [2,3], and [3,6] overlaps [5,7].
challenge icon

Follow-up

Suppose every interval has a value and you want the largest total value among intervals that do not overlap. Does keeping the interval that ends first still work?

Reset code
def eraseOverlapIntervals(starts, ends):
    # Write code here

Test #1

Test #2

Test #3

Arguments

starts = [3, 1, 5, 2]
ends = [6, 4, 7, 3]

Expected Output

2