Given a list of closed intervals [[start, end], ...], find a point (an integer coordinate) at which the maximum number of intervals overlap. Return one such point; if multiple points achieve the same maximum, any one is acceptable.
Two common approaches: (A) sweep-line over start/end events, and (B) a min-heap of end times while scanning starts. The sweep-line is simpler and directly gives the point of maximum overlap.
Create start and end events for each interval. If we process start events as +1 and end events as -1 (processing starts before ends at the same coordinate), a running sum tracks how many intervals currently cover a point. The maximum running sum and its event coordinate give the desired point.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
classSolution {
publicintmaxOverlapPoint(int[][] intervals) {
List<int[]> events =new ArrayList<>();
for (int[] seg : intervals) {
events.add(newint[]{seg[0], 1});
events.add(newint[]{seg[1], -1});
}
Collections.sort(events, (a, b) -> {
if (a[0]!= b[0]) return Integer.compare(a[0], b[0]);
return Integer.compare(b[1], a[1]); // start (+1) before end (-1) });
int cnt = 0, best = 0, bestX = 0;
for (int[] e : events) {
cnt += e[1];
if (cnt > best) { best = cnt; bestX = e[0]; }
}
return bestX;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defmax_overlap_point(self, intervals: list[tuple[int,int]]) -> int:
events: list[tuple[int,int]] = []
for s, e in intervals:
events.append((s, 1))
events.append((e, -1))
events.sort(key=lambda x: (x[0], -x[1])) # start before end at same x cnt = best =0 best_x =0for x, delta in events:
cnt += delta
if cnt > best:
best = cnt
best_x = x
return best_x
Maintain a min-heap of interval end times while iterating intervals sorted by start. The heap contains the end times of intervals that cover the current start. The heap size is the number of overlapping intervals at that start — track the max and record the start where it occurs.
Use a min-heap for end times. For each interval, pop all ends less than the current start (they no longer overlap), push current end, and check heap size for maximum.
Return the start where heap size reached its maximum.