Pattern visualizer
Non-overlapping Intervals
The insight: to keep the most intervals — and therefore remove the fewest — always keep whichever conflicting interval ends soonest. An interval that ends earlier leaves more room for everything that comes after it, so it's never a worse choice than one that ends later. Sorting by end time and greedily accepting any interval that starts at or after the last kept interval's end applies that rule automatically, so whatever gets skipped along the way is exactly the minimum set that had to be discarded. Sorted order: [[1,2], [2,3], [1,3], [3,4]] with ends 2,3,3,4 (tie at end=3 keeps [2,3] before [1,3]); minimum removals = 1. Animated on: Given an array of intervals, find the minimum number of intervals to remove to make the rest non-overlapping..
Intervals
Sort intervals by end time. Sorted order: [[1,2], [2,3], [1,3], [3,4]] (ends: 2, 3, 3, 4). Tie at end=3 keeps original relative order [2,3] before [1,3].
1FUNCTION minRemoveOverlapping(intervals):2 (sort by end time)3 sort intervals by their end value4 kept = a list holding just the first interval5 prevEnd = the end value of the first interval6 FOR i from 1 up to the length of intervals:7 start, end = the two values of intervals[i]8 IF start >= prevEnd: (no overlap with the last kept)9 add intervals[i] to kept10 prevEnd = end11 END IF12 END FOR13 RETURN (length of intervals) minus (length of kept)14END FUNCTION
← / → step · space play · Home restart