Menu
CoddyTech

Non-overlapping Intervals

You get a list of intervals as two arrays: interval i runs from starts[i] to ends[i]. Remove as few intervals as you can so that no two of the ones left overlap. Two intervals that only touch, where one ends at the exact point the other starts, do not overlap.

Write a function named eraseOverlapIntervals that returns the smallest number of intervals you have to remove.

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. You cannot keep three: [1,4] overlaps [2,3] and [3,6] overlaps [5,7], and any three of the four contain one of those pairs.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Suppose every interval also 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? What would you use instead?

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

Case 1

Case 2

Case 3

Input

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

Expected

2