Open In App

Smallest list of ranges that includes all the numbers which are not in array

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a range [l, r] and an array arr[] of unique integers and l <= arr[i] <= r. The task is to find the smallest list of ranges that includes all the numbers that are not in the given array within a certain range.

Example:

Input: arr = {3, 5, 10, 11, 12, 15} , l = 1, h = 20
Output: {1, 2} {4, 4} {6, 9} {13, 14} {16, 20}

Input: arr = {-1}, l = -1, h = -1
Output: {}

Approach:

First checks if the array is empty, in this case the entire range is not in array. Then, sort the array as this will ensure the number in increasing order and helps in finding the range is not in array just by checking between consecutive elements.

Steps-by-step approach:

  • If the array is empty (n == 0), add the full range [l, h] to the result and return.
  • Sort the input array arr[] for easier traversal.
  • If the first element of the array is not equal to l, add the range [l, arr[0] – 1] to the result.
  • Traverse the sorted array and find range is not in array between consecutive elements.
  • If the difference between two consecutive elements is not 1, add the range [arr[i-1] + 1, arr[i] – 1] to the result.
  • If the last element of the array is not equal to h, add the range [arr[n-1] + 1, h] to the result.
  • Return the vector result

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the range that are not in array between
// elements in a sorted array.
vector<vector<int> > findrange(vector<int>& arr, int l,
                            int h)
{

    // Result vector to store ranges that are not in array
    vector<vector<int> > result;

    int n = arr.size();

    // If the array is empty, the range that are not in
    // array is from 'l' to 'h'.
    if (n == 0)
        return { { l, h } };

    // Sort the array for easier traversal.
    sort(arr.begin(), arr.end());

    // If the first element of the array is not equal to
    // 'l', there is a range that are not in array
    if (arr[0] != l) {
        result.push_back({ l, arr[0] - 1 });
    }

    // Traverse the array to find range that are not in
    // array between consecutive elements.
    for (int i = 1; i < n; i++) {
        if (arr[i] - arr[i - 1] != 1) {
            result.push_back(
                { arr[i - 1] + 1, arr[i] - 1 });
        }
    }

    // If the last element of the array is not equal to 'h',
    // there is a range that are not in array.
    if (arr[n - 1] != h) {
        result.push_back({ arr[n - 1] + 1, h });
    }

    return result;
}

int main()
{
    vector<int> arr = { 3, 5, 10, 11, 12, 15 };
    int l = 1; // Lower bound of the range.
    int h = 20; // Upper bound of the range.

    // Call the findrange function to find list of Smallest
    // range that are not in the array.
    vector<vector<int> > result = findrange(arr, l, h);

    cout << "Ranges: ";

    for (const auto& range : result) {
        cout << "[" << range[0] << ", " << range[1] << "] ";
    }

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindRange {

    // Function to find the range that are not in array between
    // elements in a sorted array.
    static List<List<Integer>> findRange(List<Integer> arr, int l, int h) {
        // Result list to store ranges that are not in array
        List<List<Integer>> result = new ArrayList<>();

        int n = arr.size();

        // If the array is empty, the range that are not in
        // array is from 'l' to 'h'.
        if (n == 0) {
            result.add(Arrays.asList(l, h));
            return result;
        }

        // Sort the array for easier traversal.
        Collections.sort(arr);

        // If the first element of the array is not equal to
        // 'l', there is a range that is not in the array
        if (arr.get(0) != l) {
            result.add(Arrays.asList(l, arr.get(0) - 1));
        }

        // Traverse the array to find range that are not in
        // array between consecutive elements.
        for (int i = 1; i < n; i++) {
            if (arr.get(i) - arr.get(i - 1) != 1) {
                result.add(Arrays.asList(arr.get(i - 1) + 1, arr.get(i) - 1));
            }
        }

        // If the last element of the array is not equal to 'h',
        // there is a range that is not in the array.
        if (arr.get(n - 1) != h) {
            result.add(Arrays.asList(arr.get(n - 1) + 1, h));
        }

        return result;
    }

    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(3, 5, 10, 11, 12, 15);
        int l = 1; // Lower bound of the range.
        int h = 20; // Upper bound of the range.

        // Call the findRange function to find the list of the smallest
        // range that are not in the array.
        List<List<Integer>> result = findRange(arr, l, h);

        System.out.print("Ranges: ");
        for (List<Integer> range : result) {
            System.out.print("[" + range.get(0) + ", " + range.get(1) + "] ");
        }
    }
}

// This code is contributed by akshitaguprzj3
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;

public class GFG {
    // Function to find the range that are not in array
    // between elements in a sorted array.
    static List<List<int> > FindRange(List<int> arr, int l,
                                      int h)
    {
        // Result list to store ranges that are not in array
        List<List<int> > result = new List<List<int> >();

        int n = arr.Count;

        // If the array is empty, the range that are not in
        // array is from 'l' to 'h'.
        if (n == 0)
            return new List<List<int> >{ new List<int>{
                l, h } };

        // Sort the array for easier traversal.
        arr.Sort();

        // If the first element of the array is not equal to
        // 'l', there is a range that is not in the array.
        if (arr[0] != l) {
            result.Add(new List<int>{ l, arr[0] - 1 });
        }

        // Traverse the array to find range that are not in
        // array between consecutive elements.
        for (int i = 1; i < n; i++) {
            if (arr[i] - arr[i - 1] != 1) {
                result.Add(new List<int>{ arr[i - 1] + 1,
                                          arr[i] - 1 });
            }
        }

        // If the last element of the array is not equal to
        // 'h', there is a range that is not in the array.
        if (arr[n - 1] != h) {
            result.Add(new List<int>{ arr[n - 1] + 1, h });
        }

        return result;
    }

    static void Main(string[] args)
    {
        List<int> arr
            = new List<int>{ 3, 5, 10, 11, 12, 15 };
        int l = 1; // Lower bound of the range.
        int h = 20; // Upper bound of the range.

        // Call the FindRange function to find list of
        // smallest range that are not in the array.
        List<List<int> > result = FindRange(arr, l, h);

        Console.Write("Ranges: ");
        foreach(var range in result)
        {
            Console.Write($"[{range[0]}, {range[1]}] ");
        }

        Console.ReadKey();
    }
}

// This code is contributed by Susobhan Akhuli
Javascript
// Javascript program for the above approach
function findRange(arr, l, h) {
    let result = [];

    let n = arr.length;

    // If the array is empty, the range that are not in
    // array is from 'l' to 'h'.
    if (n === 0) {
        result.push([l, h]);
        return result;
    }

    // Sort the array for easier traversal.
    arr.sort((a, b) => a - b);

    // If the first element of the array is not equal to 'l', there is a range that are not in array
    if (arr[0] !== l) {
        result.push([l, arr[0] - 1]);
    }

    // Traverse the array to find range that are not in
    // array between consecutive elements.
    for (let i = 1; i < n; i++) {
        if (arr[i] - arr[i - 1] !== 1) {
            result.push([arr[i - 1] + 1, arr[i] - 1]);
        }
    }

    // If the last element of the array is not equal to 'h',
    // there is a range that are not in array.
    if (arr[n - 1] !== h) {
        result.push([arr[n - 1] + 1, h]);
    }

    return result;
}

let arr = [3, 5, 10, 11, 12, 15];
let l = 1; // Lower bound of the range.
let h = 20; // Upper bound of the range.

// Call the findrange function to find list of Smallest
// range that are not in the array.
let result = findRange(arr, l, h);

console.log("Ranges: " + result.map(range => "[" + range.join(", ") + "]").join(" "));

// This code is contributed by Susobhan Akhuli
Python3
# Python program for the above approach
def find_range(arr, l, h):
    # Result list to store ranges that are not in array
    result = []

    n = len(arr)

    # If the array is empty, the range that are not in
    # array is from 'l' to 'h'.
    if n == 0:
        return [[l, h]]

    # Sort the array for easier traversal.
    arr.sort()

    # If the first element of the array is not equal to
    # 'l', there is a range that are not in array
    if arr[0] != l:
        result.append([l, arr[0] - 1])

    # Traverse the array to find range that are not in
    # array between consecutive elements.
    for i in range(1, n):
        if arr[i] - arr[i - 1] != 1:
            result.append([arr[i - 1] + 1, arr[i] - 1])

    # If the last element of the array is not equal to 'h',
    # there is a range that are not in array.
    if arr[-1] != h:
        result.append([arr[-1] + 1, h])

    return result

# Main function
if __name__ == "__main__":
    arr = [3, 5, 10, 11, 12, 15]
    l = 1  # Lower bound of the range.
    h = 20  # Upper bound of the range.

    # Call the find_range function to find list of Smallest
    # range that are not in the array.
    result = find_range(arr, l, h)

    print("Ranges: ", end="")
    for range in result:
        print("[{}, {}] ".format(range[0], range[1]), end="")

# This code is contributed by Susobhan Akhuli

Output
Ranges: [1, 2] [4, 4] [6, 9] [13, 14] [16, 20] 



Time Complexity: O(n log(n))
Auxiliary Space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads