KatInterview

Peak Overlap Point Across Closed Intervals

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalssweep-lineintervalsdifference-array

Last updated

Tests whether a candidate can use sweep-line event counting to locate the smallest integer covered by the greatest number of closed intervals.

Peak Overlap Point Across Closed Intervals

You are given a list of N closed integer intervals. Each interval [lo, hi] covers every integer from lo to hi, inclusive. Find the integer that is covered by the greatest number of intervals at once.

Define the coverage of an integer x as the count of intervals [lo, hi] for which lo ≤ x ≤ hi. Return the integer with the highest coverage. When multiple integers share the highest coverage, return the smallest one.

Input

  • intervals: a list of N pairs [lo, hi] with lo ≤ hi. All endpoint values are positive integers.

Output

A single integer x whose coverage is maximum. Break ties by choosing the smallest such x.

How coverage is defined

  • x is covered by [lo, hi] if and only if lo ≤ x ≤ hi (both endpoints are included).
  • Two intervals that share exactly one endpoint — for example [1, 3] and [3, 5] — both cover 3, so 3 has coverage at least 2.
  • A point interval [x, x] contributes 1 to the coverage of exactly the integer x.

Tie-breaking rule

When several integers all achieve the maximum coverage, return the smallest one. This rule is strict: there is exactly one correct answer for every input.

Constraints

  • 1 ≤ N ≤ 10^5
  • 1 ≤ lo ≤ hi ≤ 10^9 for every interval
  • Intervals may overlap, be nested, be identical, touch at endpoints, or be entirely disjoint

Examples

Example 1

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

Output: 2

Example 2

Input: peak_overlap_point([[1, 2], [4, 5], [7, 8]])

Output: 1

Example 3

Input: peak_overlap_point([[3, 10], [1, 4], [6, 8], [2, 7]])

Output: 3

Hints

Hint 1

Coverage only changes at interval boundaries. You do not need to examine every integer between the global min and max — think about what happens at the exact coordinates where intervals start and stop.

Hint 2

Model each closed interval [lo, hi] as two events: +1 at lo and -1 at hi+1. The -1 lands at hi+1 (not hi) because hi itself is still inside the interval. Summing these events at each coordinate and sweeping in sorted order gives you the coverage at every event point.

Hint 3

Walk the sorted event coordinates while keeping a running total. After applying all deltas at coordinate v, that total equals the coverage of v. Record the first coordinate where the running total reaches its all-time high — that is your answer.