KatInterview

Peak Concurrent Shifts Across Half-Open Time Ranges

Greedy & IntervalsAuto-graded · 19 test cases
MediumAuto-gradedGreedy & Intervalssweep-lineintervalssorting

Last updated

Find the largest number of half-open time ranges that overlap at one instant, handling shared endpoints, empty ranges and large inputs with a sweep over sorted boundaries.

A delivery platform records the periods during which each of its couriers was active. Every period is a half-open range [start, end): the courier counts as active at time start and at every moment up to, but not including, end.

You are given a list shifts, where each element is a two-element list [start, end] of integers. Return the largest number of shifts that are active at the same single moment.

Rules

  • A shift is active at time t exactly when start <= t < end.
  • Because the end is excluded, two shifts that touch (one ends at t, another begins at t) are not active together at t.
  • A shift with start >= end covers no moment and must be ignored. This includes empty ranges like [5, 5] and malformed ranges where the end is before the start.
  • Identical shifts are counted separately. Ten copies of [0, 10] give a peak of 10.
  • If there are no valid shifts (including an empty list), return 0.

Constraints

  • 0 <= len(shifts) <= 10^5 (the input may be large, so aim for better than quadratic time).
  • Each shift is [start, end] with integer values; values may be negative or very large, and only their relative order matters.
  • Many shifts may share the same start or end values.
  • Return a single integer.

Examples

Example 1

Input: max_concurrent_shifts([[1, 5], [2, 6], [4, 8]])

Output: 3

Example 2

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

Output: 1

Example 3

Input: max_concurrent_shifts([[0, 10], [1, 5], [2, 7], [5, 9], [10, 12]])

Output: 3

Hints

Hint 1

Think of each valid shift as two events: the active count goes up by one at its start and down by one at its end.

Hint 2

Group events by timestamp and add up all changes at the same timestamp before looking at the running count. This handles touching ranges without any special tie-break rule.

Hint 3

Sort the distinct timestamps, sweep through them while maintaining the running count, and track the maximum. Skip shifts where start >= end before creating events.