LeetCode-in-Java

4031. Find All Numbers Disappeared in an Array II

Medium

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:

Example 2:

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

Output: [[5,7]]

Explanation:

Example 3:

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

Output: []

Explanation:

Constraints:

Solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public List<List<Integer>> findDisappearedNumbers(int[] nums, int lower, int upper) {
        List<List<Integer>> res = new ArrayList<>();
        boolean[] avail = new boolean[upper + 1];
        for (int num : nums) {
            if (num >= lower && num <= upper) {
                avail[num] = true;
            }
        }
        int i = lower;
        while (i <= upper) {
            if (avail[i]) {
                i++;
                continue;
            }
            int start = i;
            while (i <= upper && !avail[i]) {
                i++;
            }
            int end = i - 1;
            res.add(Arrays.asList(start, end));
        }
        return res;
    }
}