KatInterview

Identify Gaps in a Sorted Array Within Bounds

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsarraysintervalsedge-cases

Last updated

Tests interval reasoning, array traversal, edge case handling with boundaries, and formatting output for missing number ranges.

You are given a sorted array nums containing distinct integers, along with two integers lower and upper that define an inclusive range [lower, upper].

Your task is to identify all contiguous sequences of integers within [lower, upper] that do not appear in nums, and return them as formatted strings.

Important Rules:

  • Only consider the interval [lower, upper] (both endpoints inclusive)
  • Ignore any elements in nums that fall outside [lower, upper]
  • A number is "missing" if it lies within [lower, upper] and does not appear in nums
  • Group consecutive missing numbers into ranges

Output Format:

  • For a single missing number, return it as a string: "5"
  • For a contiguous sequence of two or more missing numbers, use range notation: "5->10" (meaning 5, 6, 7, 8, 9, 10 are all missing)
  • Return all missing ranges in ascending order

Constraints:

  • 0 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums is sorted in strictly increasing order (all elements are unique)
  • -2^31 <= lower <= upper <= 2^31 - 1

Examples

Example 1

Input: identify_missing_ranges([0, 1, 3, 50, 75], 0, 99)

Output: ['2', '4->49', '51->74', '76->99']

Example 2

Input: identify_missing_ranges([0, 1, 2, 3, 4], 0, 4)

Output: []

Example 3

Input: identify_missing_ranges([], 1, 1)

Output: ['1']

Example 4

Input: identify_missing_ranges([2, 4, 6], 1, 7)

Output: ['1', '3', '5', '7']

Hints

Hint 1

Use a sentinel value just before the interval starts (lower - 1) to handle the leading edge uniformly with gaps between array elements.

Hint 2

Process each number in the array and check if there's a gap between it and the last covered position. Skip elements outside [lower, upper] entirely.

Hint 3

After processing all array elements, check if there's a trailing gap between the last covered position and the upper bound.