KatInterview

Largest Set of Compatible Time Slots on One Worker

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

Last updated

Find the largest subset of half-open time intervals that can run on one worker without overlap, testing greedy interval selection by earliest finish.

Largest Set of Compatible Time Slots on One Worker

A single worker can handle only one job at a time. You are given a list of jobs, where each job is a pair [start, end] describing the half-open time range from start up to, but not including, end.

Two jobs conflict if their time ranges share any moment. A job that ends at time t does not conflict with a job that begins at time t, so [1, 3] and [3, 5] can both be chosen.

Choose a subset of the jobs so that no two chosen jobs conflict, and make that subset as large as possible. Return the number of jobs in it.

Input

  • jobs: a list of [start, end] pairs of integers, with start < end for each pair.

Output

  • An integer: the maximum number of pairwise non-conflicting jobs. Return 0 if jobs is empty.

Rules and edge cases

  • Jobs may be given in any order, and identical jobs may appear more than once. Identical jobs conflict with each other, so at most one copy of them can be chosen.
  • Times may be negative or large.
  • Do not rely on the input being sorted. Avoid assuming the caller's list may be modified.

Constraints

  • 0 <= len(jobs) <= 10^5
  • Each job is [start, end] with start < end.
  • start and end are integers that fit in a standard 64-bit signed integer.

Examples

Example 1

Input: max_compatible_jobs([[1, 3], [1, 5], [4, 6]])

Output: 2

Example 2

Input: max_compatible_jobs([[0, 2], [2, 4], [1, 3], [4, 5]])

Output: 3

Example 3

Input: max_compatible_jobs([[1, 10], [2, 3], [3, 4], [4, 5]])

Output: 3

Hints

Hint 1

Think about which job to commit to first so that the most time remains for the others. Sorting by one of start, end, or length gives different strategies; only one is always right.

Hint 2

Sort the jobs by end time. Keep track of the moment the worker becomes free, and accept a job whenever its start is at or after that moment.

Hint 3

Because intervals are half-open, a job starting exactly when the last chosen one ends is allowed, so compare with >= rather than >.