FastPrepUnion of K Sorted Interval Streams

Union of K Sorted Interval Streams

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given k streams of closed integer intervals, return their union as sorted, pairwise-disjoint intervals.

  • Each stream is sorted by start value.
  • A stream may contain internal overlap.
  • Merge the next interval when its start is at most the current merged end.
  • Process the streams as a k-way merge: only one current interval from each stream needs to be active at a time.

Function

unionIntervalStreams(streams: int[][][]) → int[][]

Examples

Example 1

streams = [[[1,3],[5,7]],[[2,4],[7,9]]]return = [[1,4],[5,9]]

The first two intervals merge into [1,4]. The intervals [5,7] and [7,9] meet at 7 and merge into [5,9].

Example 2

streams = [[],[[-2,-1],[0,2]],[[2,3]]]return = [[-2,-1],[0,3]]

The empty stream contributes nothing, and the two intervals meeting at 2 merge.

Constraints

  • streams contains one or more interval streams.
  • Every interval is [start, end] with start <= end.
  • Each individual stream is sorted by nondecreasing start value.

More Google problems

See Google hiring insights
public int[][] unionIntervalStreams(int[][][] streams) {
    // TODO: merge the sorted streams and return their closed-interval union.
}
streams[[[1,3],[5,7]],[[2,4],[7,9]]]
expected[[1,4],[5,9]]
Checking account…