Open In App

Elements to be added so that all elements of a range are present in array

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of size N. Let A and B be the minimum and maximum in the array respectively. Task is to find how many number should be added to the given array such that all the element in the range [A, B] occur at-least once in the array.
Examples: 
 

Input : arr[] = {4, 5, 3, 8, 6}
Output : 1
Only 7 to be added in the list.

Input : arr[] = {2, 1, 3}
Output : 0
Recommended Practice

Method 1 (Sorting):

  1. Sort the array. 
  2. Compare arr[i] == arr[i+1]-1 or not. If not, update count = arr[i+1]-arr[i]-1. 
  3. Return count. 

Implementation:

C++




// C++ program for above implementation
#include <bits/stdc++.h>
using namespace std;
  
// Function to count numbers to be added
int countNum(int arr[], int n)
{
    int count = 0;
  
    // Sort the array
    sort(arr, arr + n);
  
    // Check if elements are consecutive
    //  or not. If not, update count
    for (int i = 0; i < n - 1; i++)
        if (arr[i] != arr[i+1] && 
            arr[i] != arr[i + 1] - 1)
            count += arr[i + 1] - arr[i] - 1;
  
    return count;
}
  
// Drivers code
int main()
{
    int arr[] = { 3, 5, 8, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countNum(arr, n) << endl;
    return 0;
}


Java




// java program for above implementation
import java.io.*;
import java.util.*;
  
public class GFG {
      
    // Function to count numbers to be added
    static int countNum(int []arr, int n)
    {
        int count = 0;
      
        // Sort the array
        Arrays.sort(arr);
      
        // Check if elements are consecutive
        // or not. If not, update count
        for (int i = 0; i < n - 1; i++)
            if (arr[i] != arr[i+1] && 
                arr[i] != arr[i + 1] - 1)
                count += arr[i + 1] - arr[i] - 1;
      
        return count;
    }
      
    // Drivers code
    static public void main (String[] args)
    {
          
        int []arr = { 3, 5, 8, 6 };
        int n = arr.length;
          
        System.out.println(countNum(arr, n));
    }
}
  
// This code is contributed by vt_m.


Python3




# python program for above implementation
  
# Function to count numbers to be added
def countNum(arr, n): 
      
    count = 0
  
    # Sort the array
    arr.sort()
  
    # Check if elements are consecutive
    # or not. If not, update count
    for i in range(0, n-1):
        if (arr[i] != arr[i+1] and
            arr[i] != arr[i + 1] - 1):
            count += arr[i + 1] - arr[i] - 1;
  
    return count
  
# Drivers code
arr = [ 3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
  
# This code is contributed by Sam007


C#




// C# program for above implementation
using System;
  
public class GFG {
      
    // Function to count numbers to be added
    static int countNum(int []arr, int n)
    {
        int count = 0;
      
        // Sort the array
        Array.Sort(arr);
      
        // Check if elements are consecutive
        // or not. If not, update count
        for (int i = 0; i < n - 1; i++)
            if (arr[i] != arr[i+1] && 
                arr[i] != arr[i + 1] - 1)
                count += arr[i + 1] - arr[i] - 1;
      
        return count;
    }
      
    // Drivers code
    static public void Main ()
    {
          
        int []arr = { 3, 5, 8, 6 };
        int n = arr.Length;
          
        Console.WriteLine(countNum(arr, n));
    }
}
  
// This code is contributed by vt_m.


PHP




<?php
// PHP program for 
// above implementation
  
// Function to count 
// numbers to be added
function countNum($arr, $n)
{
  
    $count = 0;
  
    // Sort the array
    sort($arr);
  
    // Check if elements are 
    // consecutive or not. 
    // If not, update count
    for ($i = 0; $i < $n - 1; $i++)
        if ($arr[$i] != $arr[$i + 1] && 
            $arr[$i] != $arr[$i + 1] - 1)
            $count += $arr[$i + 1] - 
                      $arr[$i] - 1;
  
    return $count;
}
  
// Driver code
$arr = array(3, 5, 8, 6);
$n = count($arr);
echo countNum($arr, $n) ;
  
// This code is contributed
// by anuj_67.
?>


Javascript




<script>
// Javascript program for above implementation
  
    // Function to count numbers to be added
       function countNum(arr, n)
    {
        let count = 0;
        
        // Sort the array
        arr.sort();
        
        // Check if elements are consecutive
        // or not. If not, update count
        for (let i = 0; i < n - 1; i++)
            if (arr[i] != arr[i+1] && 
                arr[i] != arr[i + 1] - 1)
                count += arr[i + 1] - arr[i] - 1;
        
        return count;
    }
      
// Driver code
        let arr = [ 3, 5, 8, 6 ];
        let n = arr.length;
            
        document.write(countNum(arr, n));
        
      // This code is contributed by sanjoy_62.
</script>


Output

2

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

Method 2 (Use Hashing):

  1. Maintain a hash of array elements. 
  2. Store minimum and maximum element. 
  3. Traverse from minimum to maximum element in hash 
    And count if element is not in hash. 
  4. Return count. 

Implementation:

C++




// C++ program for above implementation
#include <bits/stdc++.h>
using namespace std;
  
// Function to count numbers to be added
int countNum(int arr[], int n)
{
    unordered_set<int> s;
    int count = 0, maxm = INT_MIN, minm = INT_MAX;
  
    // Make a hash of elements
    // and store minimum and maximum element
    for (int i = 0; i < n; i++) {
        s.insert(arr[i]);
        if (arr[i] < minm)
            minm = arr[i];
        if (arr[i] > maxm)
            maxm = arr[i];
    }
  
    // Traverse all elements from minimum
    // to maximum and count if it is not
    // in the hash
    for (int i = minm; i <= maxm; i++)
        if (s.find(arr[i]) == s.end())
            count++;
    return count;
}
  
// Drivers code
int main()
{
    int arr[] = { 3, 5, 8, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countNum(arr, n) << endl;
    return 0;
}


Java




// Java implementation of the approach
import java.util.HashSet;
  
class GFG 
{
  
// Function to count numbers to be added
static int countNum(int arr[], int n)
{
    HashSet<Integer> s = new HashSet<>();
    int count = 0
        maxm = Integer.MIN_VALUE, 
        minm = Integer.MAX_VALUE;
  
    // Make a hash of elements
    // and store minimum and maximum element
    for (int i = 0; i < n; i++) 
    {
        s.add(arr[i]);
        if (arr[i] < minm)
            minm = arr[i];
        if (arr[i] > maxm)
            maxm = arr[i];
    }
  
    // Traverse all elements from minimum
    // to maximum and count if it is not
    // in the hash
    for (int i = minm; i <= maxm; i++)
        if (!s.contains(i))
            count++;
    return count;
}
  
// Drivers code
public static void main(String[] args) 
{
    int arr[] = { 3, 5, 8, 6 };
    int n = arr.length;
    System.out.println(countNum(arr, n));
}
}
  
// This code is contributed by Rajput-Ji


Python3




# Function to count numbers to be added
def countNum(arr, n):
  
    s = dict()
    count, maxm, minm = 0, -10**9, 10**9
  
    # Make a hash of elements and store 
    # minimum and maximum element
    for i in range(n):
        s[arr[i]] = 1
        if (arr[i] < minm):
            minm = arr[i]
        if (arr[i] > maxm):
            maxm = arr[i]
      
    # Traverse all elements from minimum
    # to maximum and count if it is not
    # in the hash
    for i in range(minm, maxm + 1):
        if i not in s.keys():
            count += 1
    return count
  
# Driver code
arr = [3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
      
# This code is contributed by mohit kumar


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
  
class GFG 
{
  
// Function to count numbers to be added
static int countNum(int []arr, int n)
{
    HashSet<int> s = new HashSet<int>();
    int count = 0, 
        maxm = int.MinValue, 
        minm = int.MaxValue;
  
    // Make a hash of elements
    // and store minimum and maximum element
    for (int i = 0; i < n; i++) 
    {
        s.Add(arr[i]);
        if (arr[i] < minm)
            minm = arr[i];
        if (arr[i] > maxm)
            maxm = arr[i];
    }
  
    // Traverse all elements from minimum
    // to maximum and count if it is not
    // in the hash
    for (int i = minm; i <= maxm; i++)
        if (!s.Contains(i))
            count++;
    return count;
}
  
// Drivers code
public static void Main(String[] args) 
{
    int []arr = { 3, 5, 8, 6 };
    int n = arr.Length;
    Console.WriteLine(countNum(arr, n));
}
}
  
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript implementation of the approach
      
    // Function to count numbers to be added
    function countNum(arr,n)
    {
        let s = new Set();
    let count = 0,
        maxm = Number.MIN_VALUE,
        minm = Number.MAX_VALUE;
   
    // Make a hash of elements
    // and store minimum and maximum element
    for (let i = 0; i < n; i++)
    {
        s.add(arr[i]);
        if (arr[i] < minm)
            minm = arr[i];
        if (arr[i] > maxm)
            maxm = arr[i];
    }
   
    // Traverse all elements from minimum
    // to maximum and count if it is not
    // in the hash
    for (let i = minm; i <= maxm; i++)
        if (!s.has(i))
            count++;
    return count;
    }
      
    // Drivers code
    let arr=[3, 5, 8, 6 ];
    let n = arr.length;
    document.write(countNum(arr, n));
      
      
  
// This code is contributed by unknown2108
</script>


Output

5

Time Complexity: O(n + max – min + 1)
Auxiliary Space: O(n), for use of set

Method 3 (Use Boolean array ):

  • We can initialize this array to all false.
  • Then, we can iterate through the input array and mark each number that falls within the range [A,B] as true in the boolean array.
  • we can count the number of false values in the boolean array, which will give us the number of missing numbers in the range [A,B].
  • This count will be the number of elements that we need to add to the input array to ensure that all numbers in the range [A,B] appear at least once.

C++




#include <iostream>
#include <climits> // Required for INT_MAX and INT_MIN constants
  
using namespace std;
  
// Function to count the number of elements to add to the array
int countToAdd(int arr[], int N) {
    // Find the minimum and maximum values in the array
    int A = INT_MAX, B = INT_MIN;
    for (int i = 0; i < N; i++) {
        A = min(A, arr[i]);
        B = max(B, arr[i]);
    }
  
    // Create a boolean array called present to keep track of which elements are in the range
    bool present[B - A + 1] = {false};
  
    // Loop over the input array, and set the corresponding element in the present array to true for each element
    for (int i = 0; i < N; i++) {
        if (!present[arr[i] - A]) { // Check if the element is in the range [A, B]
            present[arr[i] - A] = true;
        }
    }
  
    // Count the number of elements that are not yet present in the present array
    int count = 0;
    for (int i = A; i <= B; i++) {
        if (!present[i - A]) { // Check if the element is in the range [A, B]
            count++;
        }
    }
  
    // Return the count
    return count;
}
  
int main() {
    int arr[] = {4, 7, 2, 8, 5};
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Call the countToAdd function to find the number of elements to add to the array
    int count = countToAdd(arr, N);
  
    // Output the result
    cout << "Number of elements to be added: " << count << endl;
  
    return 0;
}


Java




import java.util.*;
  
class Main {
    // Function to count the number of elements to add to
    // the array
    static int countToAdd(int[] arr, int N)
    {
        // Find the minimum and maximum values in the array
        int A = Integer.MAX_VALUE, B = Integer.MIN_VALUE;
        for (int i = 0; i < N; i++) {
            A = Math.min(A, arr[i]);
            B = Math.max(B, arr[i]);
        }
  
        // Create a boolean array called present to keep
        // track of which elements are in the range
        boolean[] present = new boolean[B - A + 1];
  
        // Loop over the input array, and set the
        // corresponding element in the present array to
        // true for each element
        for (int i = 0; i < N; i++) {
            if (!present[arr[i]
                         - A]) { // Check if the element is
                                 // in the range [A, B]
                present[arr[i] - A] = true;
            }
        }
  
        // Count the number of elements that are not yet
        // present in the present array
        int count = 0;
        for (int i = A; i <= B; i++) {
            if (!present[i - A]) { // Check if the element
                                   // is in the range [A, B]
                count++;
            }
        }
  
        // Return the count
        return count;
    }
  
    public static void main(String[] args)
    {
        int[] arr = { 4, 7, 2, 8, 5 };
        int N = arr.length;
  
        // Call the countToAdd function to find the number
        // of elements to add to the array
        int count = countToAdd(arr, N);
  
        // Output the result
        System.out.println(
            "Number of elements to be added: " + count);
    }
}


Python3




import sys
  
# Function to count the number of elements to add to the array
  
  
def countToAdd(arr, N):
    # Find the minimum and maximum values in the array
    A = sys.maxsize
    B = -sys.maxsize - 1
    for i in range(N):
        A = min(A, arr[i])
        B = max(B, arr[i])
  
    # Create a boolean array called present to keep track of which elements are in the range
    present = [False] * (B - A + 1)
  
    # Loop over the input array, and set the corresponding element in the present array to true for each element
    for i in range(N):
        if not present[arr[i] - A]:  # Check if the element is in the range [A, B]
            present[arr[i] - A] = True
  
    # Count the number of elements that are not yet present in the present array
    count = 0
    for i in range(A, B + 1):
        if not present[i - A]:  # Check if the element is in the range [A, B]
            count += 1
  
    # Return the count
    return count
  
  
arr = [4, 7, 2, 8, 5]
N = len(arr)
  
# Call the countToAdd function to find the number of elements to add to the array
count = countToAdd(arr, N)
  
# Output the result
print("Number of elements to be added:", count)


C#




using System;
  
class GFG {
    // Function to count the number of elements to add to
    // the array
    static int countToAdd(int[] arr, int N)
    {
        // Find the minimum and maximum values in the array
        int A = int.MaxValue, B = int.MinValue;
        for (int i = 0; i < N; i++) {
            A = Math.Min(A, arr[i]);
            B = Math.Max(B, arr[i]);
        }
  
        // Create a boolean array called present to keep
        // track of which elements are in the range
        bool[] present = new bool[B - A + 1];
  
        // Loop over the input array, and set the
        // corresponding element in the present array to
        // true for each element
        for (int i = 0; i < N; i++) {
            if (!present[arr[i]
                         - A]) // Check if the element is in
                               // the range [A, B]
            {
                present[arr[i] - A] = true;
            }
        }
  
        // Count the number of elements that are not yet
        // present in the present array
        int count = 0;
        for (int i = A; i <= B; i++) {
            if (!present[i - A]) // Check if the element is
                                 // in the range [A, B]
            {
                count++;
            }
        }
  
        // Return the count
        return count;
    }
  
    static void Main()
    {
        int[] arr = { 4, 7, 2, 8, 5 };
        int N = arr.Length;
  
        // Call the countToAdd function to find the number
        // of elements to add to the array
        int count = countToAdd(arr, N);
  
        // Output the result
        Console.WriteLine("Number of elements to be added: "
                          + count);
    }
}


Javascript




function countToAdd(arr, N) {
  // Find the minimum and maximum values in the array
  let A = Number.MAX_SAFE_INTEGER;
  let B = Number.MIN_SAFE_INTEGER;
  for (let i = 0; i < N; i++) {
    A = Math.min(A, arr[i]);
    B = Math.max(B, arr[i]);
  }
  
  // Create a boolean array called present to keep track of which elements are in the range
  const present = new Array(B - A + 1).fill(false);
  
  // Loop over the input array, and set the corresponding element in the present array to true for each element
  for (let i = 0; i < N; i++) {
    if (!present[arr[i] - A]) {  // Check if the element is in the range [A, B]
      present[arr[i] - A] = true;
    }
  }
  
  // Count the number of elements that are not yet present in the present array
  let count = 0;
  for (let i = A; i <= B; i++) {
    if (!present[i - A]) {  // Check if the element is in the range [A, B]
      count += 1;
    }
  }
  
  // Return the count
  return count;
}
  
const arr = [4, 7, 2, 8, 5];
const N = arr.length;
  
// Call the countToAdd function to find the number of elements to add to the array
const count = countToAdd(arr, N);
  
// Output the result
console.log("Number of elements to be added:", count);


Output

Number of elements to be added: 2

Time Complexity: O(N + B – A), where N is the size of the input array and B – A is the size of the range [A, B]. The algorithm involves looping over the input array once to find the minimum and maximum values, and then looping over the range [A, B] to count the number of elements that are not present in the input array.

Auxiliary Space: O(B – A), as we are using a boolean array called present of size B – A + 1 to keep track of which elements are in the range [A, B]. This additional space is required to solve the problem without modifying the input array.

 



Previous Article
Next Article

Similar Reads

Smallest possible integer to be added to N-1 elements in array A such that elements of array B are present in A
Given two arrays A[] of length N and B[] of length N-1, the task is to find the smallest positive integer X that is added to every element of A[] except one element, so that all the elements of array B[] are present in array A[]. Assume that finding X is always possible. Examples: Input: A[] = {1, 4, 3, 8}, B[] = {15, 8, 11}Output: 7Explanation: Ad
7 min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Count of elements in Array which are present K times &amp; their double isn't present
Given an array arr[] of N integers, the task is to find the count of elements in the array that are present K times and their double are not present in the array. Examples: Input: arr[] = {10, 6, 12, 8, 10, 8}, K = 2Output: 2Explanation: 10 is a valid number since it appears exactly two times and 20 does not appear in array.8 is a valid number sinc
9 min read
Minimum elements to be added in a range so that count of elements is divisible by K
Given three integer K, L and R (range [L, R]), the task is to find the minimum number of elements the range must be extended by so that the count of elements in the range is divisible by K. Examples: Input: K = 3, L = 10, R = 10 Output: 2 Count of elements in L to R is 1. So to make it divisible by 3 , increment it by 2. Input: K = 5, L = 9, R = 12
4 min read
Find GCD of each element of array B[] added to all elements of array A[]
Given two arrays a[] and b[] of length n and m respectively, the task is to find Greatest Common Divisor(GCD) of {a[0] + b[i], a[1] + b[i], a[2] + b[i], ..., a[n - 1] + b[i]} ( where 0 &lt;= i &lt;= m - 1). Input: a[] = {1, 10, 22, 64}, b[] = {5, 23, 14, 13}Output: 3 3 3 1 Explanation: i = 1 : GCD(5+1, 5+10, 5+22, 5+64) = GCD(6, 15, 27, 69) = 3i =
6 min read
Find all numbers in range [1, N] that are not present in given Array
Given an array arr[] of size N, where arr[i] is natural numbers less than or equal to N, the task is to find all the numbers in the range [1, N] that are not present in the given array. Examples: Input: arr[ ] = {5, 5, 4, 4, 2}Output: 1 3Explanation: For all numbers in the range [1, 5], 1 and 3 are not present in the array. Input: arr[ ] = {3, 2, 3
4 min read
Print all unique digits present in concatenation of all array elements in the order of their occurrence
Given an array arr[] consisting of N integers, the task is to print all unique digits of the number formed by concatenating all array elements in the order of their occurrence after excluding leading zeroes. Examples: Input: arr[] = {122, 474, 612, 932}Output: 7 6 9 3Explanation:The number formed by concatenating array elements is “122474612932”.Un
10 min read
Minimize elements to be added to a given array such that it contains another given array as its subsequence
Given an array A[] consisting of N distinct integers and another array B[] consisting of M integers, the task is to find the minimum number of elements to be added to the array B[] such that the array A[] becomes the subsequence of the array B[]. Examples: Input: N = 5, M = 6, A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6, 4, 9, 12} Output: 3Explanation:Be
15+ min read
Minimize elements to be added to a given array such that it contains another given array as its subsequence | Set 2
Given an array A[] consisting of N distinct integers and another array B[] consisting of M integers, the task is to find the minimum number of elements to be added to the array B[] such that the array A[] becomes the subsequence of the array B[]. Examples: Input: N = 5, M = 6, A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6, 4, 9, 12}Output: 3Explanation:Bel
9 min read
Minimize consecutive elements to be added for each element to make Array of at least C length
Given a sorted array arr[] of size N, where arr[i] denotes the starting position of a sequence, the task is to find the minimum number of consecutive elements (say K) that can be added for each Array element to make the Array length at least C. Note: The consecutive numbers can be added till minimum of arr[i]+K or (arr[i+1]-1). Examples: Input: arr
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg