FastPrepMerge Intervals

Merge Intervals

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given closed integer intervals intervals[i] = [start, end]. Merge every group of overlapping intervals into one interval that covers the same points.

Intervals that share an endpoint overlap. Input intervals may be unsorted, nested, repeated or zero-length. Merge transitively: an interval connecting two others puts all three in the same component.

Return the disjoint merged intervals in increasing order of start. Every original interval must be covered, and no points outside the original union may be introduced. The output ordering and method name are the deterministic function-runner interface for this exercise. Do not modify the input.

Function

mergeIntervals(intervals: int[][]) → int[][]

Examples

Example 1

intervals = [[1,3],[2,6],[8,10],[15,18]]return = [[1,6],[8,10],[15,18]]

The first two intervals overlap and become [1,6]. The other two components remain separate.

Example 2

intervals = [[1,4],[4,5]]return = [[1,5]]

The shared endpoint4 belongs to both closed intervals, so their union is [1,5].

Example 3

intervals = [[4,7],[1,4]]return = [[1,7]]

Input order does not matter. Both intervals share endpoint4 and form [1,7].

Constraints

  • 1 <= intervals.length <= 10000.
  • Every row contains exactly two integers with 0 <= start <= end <= 10000.
  • All intervals are closed, including a point interval [x,x].
  • Return integer pairs; endpoint arithmetic fits a signed 32-bit integer.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int[][] mergeIntervals(int[][] intervals) {
    // write your code here
}
intervals[[1,3],[2,6],[8,10],[15,18]]
expected[[1,6],[8,10],[15,18]]
Checking account…