Taro Logo

Find All Numbers Disappeared in an Array II

Medium
Asked by:
Tata Consultancy Services
1 view
Topics:
Arrays

You are given an integer array nums and two integers lower and upper.

A missing integer is an integer in the inclusive range [lower, upper] that does not appear in nums.

Return a 2D integer array where each element is of the form [start, end], representing a contiguous range of missing integers. Return the ranges in increasing order. If there are no missing integers, return an empty array.

Note: Consecutive missing integers should be grouped into a single range.

Example 1:

Input: nums = [3,9,7], lower = 1, upper = 12

Output: [[1,2],[4,6],[8,8],[10,12]]

Explanation:

  • The missing integers are [1, 2, 4, 5, 6, 8, 10, 11, 12].
  • Grouping the missing integers into the minimum number of contiguous ranges, we get [1, 2], [4, 6], [8, 8], and [10, 12].
  • Therefore, the answer is [[1, 2], [4, 6], [8, 8], [10, 12]].

Example 2:

Input: nums = [1,1], lower = 5, upper = 7

Output: [[5,7]]

Explanation:

  • The missing integers are [5, 6, 7].
  • Grouping the missing integers into the minimum number of contiguous ranges, we get [5, 7].
  • Therefore, the answer is [[5, 7]].

Example 3:

Input: nums = [2,3,5], lower = 2, upper = 3

Output: []

Explanation:

  • There are no missing integers.
  • Therefore, the answer is [].

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= lower <= upper <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the exact range of numbers we are checking for missing values? For instance, is the range always from 1 to $N$ (where $N$ is the length of the array), or is it defined by a separate min and max parameter?
  2. How should we handle edge cases such as an empty input array, or an array where all numbers in the range are already present?
  3. Are duplicates allowed in the input array, and how should they be handled when determining which numbers are missing?
  4. Is there any requirement on the ordering of the numbers in the returned list of missing elements?
  5. Can I modify the input array in-place, or do I need to treat it as read-only (meaning I cannot use techniques like negating values to track visited elements)?

Brute Force Solution

Approach

The algorithm finds all contiguous missing integer ranges between a lower bound and an upper bound that do not appear in the input array. It first cleans and sorts the given numbers to inspect elements in increasing order. By maintaining a pointer for the next expected missing number, any detected gaps are recorded as valid ranges.

Here's how the algorithm would work step-by-step:

  1. Filter and sort the unique numbers from the input array.
  2. Initialize a tracking variable to the lower bound and an empty list for the missing ranges.
  3. Iterate through each sorted unique number within the interval.
  4. Add a missing range if the current unique number is strictly greater than the expected tracking value.
  5. Update the tracking variable to one past the current unique number.
  6. Add a final range up to the upper bound if the tracking variable has not exceeded the upper bound.

Code Implementation

def find_missing_ranges(nums, lower, upper):
    # Sort the array and remove duplicate values
    unique_numbers = sorted(set(nums))
    missing_ranges = []
    current_start = lower
    # Iterate through unique numbers to find gaps
    for number in unique_numbers:
        if number < current_start:
            continue
        if number > upper:
            break
        if number > current_start:
            missing_ranges.append([current_start, number - 1])
        current_start = number + 1
    # Check if there is any remaining gap before the upper bound
    if current_start <= upper:
        missing_ranges.append([current_start, upper])
    return missing_ranges

Big(O) Analysis

Time Complexity
O(N log N) – Extracting unique elements and sorting them takes O(N log N) time, where N is the number of elements in nums. The subsequent linear scan takes O(N) time.
Space Complexity
O(N) – Creating the set of unique numbers and sorting them requires additional memory proportional to the number of distinct elements, which is at most O(N).

Optimal Solution

Approach

Sort the numbers, drop duplicates, and ignore anything outside the requested span. Then walk from the lower bound to the upper bound and record every gap between the numbers that remain.

Here's how the algorithm would work step-by-step:

  1. Put the numbers in increasing order and drop duplicates.
  2. Start just before the lower bound.
  3. Skip numbers below the lower bound, and stop once a number passes the upper bound.
  4. Whenever the next in-range number leaves a gap after the previous one, record that gap as a start and an end.
  5. After the last in-range number, record the gap through the upper bound if one remains.

Code Implementation

def find_missing_ranges(nums, lower, upper):
    ordered = sorted(set(nums))
    ranges = []
    previous = lower - 1
    for value in ordered:
        if value < lower:
            continue
        if value > upper:
            break
        if previous + 1 <= value - 1:
            ranges.append([previous + 1, value - 1])
        previous = value
    if previous + 1 <= upper:
        ranges.append([previous + 1, upper])
    return ranges

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the numbers dominates. The scan that emits the gaps is linear.
Space Complexity
O(n) – The sorted copy and the list of missing ranges both grow with the input.

Edge Cases

Empty or null input array
How to Handle:
Return an empty list immediately to prevent null pointer exceptions and invalid range processing.
Array with a single element
How to Handle:
Evaluate whether that single element covers the expected range and return the remaining numbers accordingly.
Maximum-sized inputs up to array length N
How to Handle:
Use in-place index negation or cyclic sort to achieve O(N) time complexity and O(1) extra space complexity.
Inputs containing many duplicates and all identical values
How to Handle:
The state marking mechanism will safely process repeated visits to the same index without causing logic errors.
Range limits defined by the array length N
How to Handle:
Ensure the algorithm maps values strictly between 1 and N to valid array indices from 0 to N-1.
All numbers in the range are present with no missing values
How to Handle:
The traversal will find no unmarked indices and correctly return an empty list.
All numbers are missing except for one repeated value
How to Handle:
The marking phase will target only a single index, leaving all other indices positive to collect the full missing range.
Language-specific array mutation constraints
How to Handle:
Use absolute values during the lookup phase so that previously negated index markers do not corrupt subsequent reads.