KatInterview

Narrowest Window Touching Every Sorted Array

Heaps, Sorting & SearchAuto-graded · 20 test cases
HardAuto-gradedHeaps, Sorting & Searchheapk-way-mergesorted-lists

Last updated

Find the tightest inclusive interval that holds at least one value from each of several sorted arrays, using a k-way merge with a min-heap and a tracked maximum.

You are given a collection of k integer arrays, each sorted in non-decreasing order. Find an inclusive interval [lo, hi] such that every array has at least one element x with lo <= x <= hi.

Many intervals may qualify, so use this ordering to pick one. Interval [p, q] is better than [r, s] when:

  1. q - p < s - r (it is strictly narrower), or
  2. q - p == s - r and p < r (equal width, but it starts further left).

Return the best qualifying interval as [lo, hi].

Arrays may contain repeated values and negative numbers. The same value can appear in several arrays.

Input

  • lists: a list of k lists of integers. Each inner list is sorted in non-decreasing order.

Output

  • A list of two integers [lo, hi], the best interval under the ordering above.

Constraints

  • k == len(lists)
  • 1 <= k <= 3500
  • 1 <= len(lists[i]) <= 50
  • The total number of elements across all lists is at most 10^5
  • -10^5 <= lists[i][j] <= 10^5
  • Each lists[i] is sorted in non-decreasing order

Examples

Example 1

Input: narrowest_cover([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]])

Output: [20, 24]

Example 2

Input: narrowest_cover([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

Output: [1, 1]

Hints

Hint 1

Imagine choosing one element from each array. The smallest interval covering those choices is determined by their minimum and maximum.

Hint 2

Start with the first element of every array. To shrink the interval, the only move that can help is replacing the current minimum with the next element from the same array.

Hint 3

Use a min-heap to get the current minimum quickly, and keep the current maximum in a separate variable. Stop as soon as the array that supplied the minimum has no further elements.