KatInterview

Minimum Removals for Conflict-Free Time Slots

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalsgreedyintervalssorting

Last updated

Tests the greedy earliest-finish strategy: find the fewest ranges to discard so the rest share no interior points, with touching endpoints allowed.

Minimum Removals for Conflict-Free Time Slots

You are given a list of booking requests. Each request is a pair [begin, finish] describing a segment on a number line.

Two requests conflict when their segments share more than a single point. Precisely, for requests [a, b] and [c, d] with a <= c, they conflict if and only if c < b. If c == b, the segments only touch at one point and they do not conflict.

Your task is to discard as few requests as possible so that no two of the remaining requests conflict. Return the number of requests you discard.

Identical requests (same [begin, finish]) conflict with each other, so among a group of identical requests at most one can be kept.

Function

Implement min_removals(slots), where slots is a list of [begin, finish] pairs. Return a single integer: the minimum number of requests that must be removed.

Constraints

  • 1 <= len(slots) <= 2 * 10^5
  • Each element of slots has exactly two integers [begin, finish].
  • -10^9 <= begin < finish <= 10^9
  • Duplicate requests may appear.
  • If the requests are already pairwise conflict-free, the answer is 0.

Examples

Example 1

Input: min_removals([[1, 2], [2, 3], [3, 4], [1, 3]])

Output: 1

Example 2

Input: min_removals([[1, 2], [1, 2], [1, 2]])

Output: 2

Example 3

Input: min_removals([[-50, -20], [-30, 10], [-20, 0], [0, 50]])

Output: 1

Hints

Hint 1

Removing the fewest requests is the same as keeping the largest possible set of requests that do not conflict. The answer is the total count minus the size of that set.

Hint 2

When choosing which request to keep first, which one leaves the most room for later requests? Think about sorting by one of the two endpoints.

Hint 3

Sort by finish time and scan, remembering the finish of the last kept request. Keep a request when its begin is at least that finish value (touching is fine); otherwise count it as removed. Do not initialize the tracked finish to 0, since coordinates can be negative.