{x}
blog image

Missing Ranges

Solution Explanation: Finding Missing Ranges

This problem asks us to find all ranges of missing integers within a given range [lower, upper], given a sorted array nums containing unique integers within that range. The solution uses a simulation approach to iterate through the input and identify gaps.

Algorithm:

  1. Handle Empty Input: If nums is empty, the entire range [lower, upper] is missing, so we return [[lower, upper]].

  2. Check the Beginning: We check if there's a gap between lower and the first element of nums. If nums[0] > lower, then [lower, nums[0]-1] is a missing range, which is added to the result.

  3. Iterate and Check Gaps: We iterate through nums, comparing each element with the previous one. If the difference between consecutive elements is greater than 1 (nums[i] - nums[i-1] > 1), it means there's a missing range [nums[i-1]+1, nums[i]-1], which is added to the result.

  4. Check the End: Finally, we check if there's a gap between the last element of nums and upper. If nums[-1] < upper, then [nums[-1]+1, upper] is a missing range, and it's added to the result.

  5. Return the Result: The function returns the list of missing ranges ans.

Time Complexity: O(n), where n is the length of the input array nums. The algorithm iterates through the array once.

Space Complexity: O(k), where k is the number of missing ranges. In the worst case, k could be approximately equal to n (if there are many small gaps). If we consider only the space used besides the output, it would be O(1).

Code Examples:

The provided code demonstrates the algorithm in several programming languages. All versions follow the same logic:

  • Python: Uses pairwise from the itertools library for concise iteration between consecutive elements.
  • Java, C++, Go, TypeScript: Use standard loop constructs to iterate and compare elements.

Example Walkthrough (Python):

Let's consider the example nums = [0, 1, 3, 50, 75], lower = 0, upper = 99.

  1. nums[0] > lower (1 > 0) is false, so no initial range is added.
  2. The loop iterates:
    • nums[1] - nums[0] = 1 - 0 = 1, no gap.
    • nums[2] - nums[1] = 3 - 1 = 2 > 1, so [2, 2] is added.
    • nums[3] - nums[2] = 50 - 3 = 47 > 1, so [4, 49] is added.
    • nums[4] - nums[3] = 75 - 50 = 25 > 1, so [51, 74] is added.
  3. nums[-1] < upper (75 < 99) is true, so [76, 99] is added.
  4. The function returns [[2, 2], [4, 49], [51, 74], [76, 99]].

This detailed explanation clarifies the approach and demonstrates its efficiency. The code examples provided offer practical implementation in multiple languages.