The Wayback Machine - https://web.archive.org/web/20220923125214/https://www.geeksforgeeks.org/check-if-an-array-contains-all-elements-of-a-given-range/
Skip to content
Related Articles

Related Articles

Check if an array contains all elements of a given range

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 17 Aug, 2022
View Discussion
Improve Article
Save Article

An array containing positive elements is given. ‘A’ and ‘B’ are two numbers defining a range. Write a function to check if the array contains all elements in the given range.

Examples : 

Input : arr[] = {1 4 5 2 7 8 3}
           A : 2, B : 5
Output : Yes

Input : arr[] = {1 4 5 2 7 8 3}
          A : 2, B : 6
Output : No
Recommended Practice

Method 1 : (Intuitive)

  • The most intuitive approach is to sort the array and check from the element greater than ‘A’ to the element greater than ‘B’. If these elements are in continuous order, all elements in the range exists in the array.

Time complexity: O(n log n) 
Auxiliary space: O(1)

Method 2 : (Hashing) 

  • We can maintain a count array or a hash table that stores the count of all numbers in the array that are in the range A…B. Then we can simply check if every number occurred at least once.

Time complexity : O(n) 
Auxiliary space : O(max_element)

Method 3 : (Best):

Every element(x) in the range (A to B) has a corresponding unique index (x-A)

  • Do a linear traversal of the array. If an element is found such that in the given range, i.e., |arr[i]| >= A and |arr[i]| <=B 
  • Negate the element at  index (arr[i]-A) corresponding to this element arr[i].(do this only the element at that index is positive)
  • Now, count the number of number of elements which are negative .This count must be equal to B-A+1.
  • As, an element at an index is negative indicates that element corresponding to that index is present in array.

Implementation:

C++




#include <iostream>
using namespace std;
 
// Function to check the array for elements in
// given range
bool check_elements(int arr[], int n, int A, int B)
{
    //Array should contain atleast B-A+1 elements
    if(n<B-A+1) return false;
    // Range is the no. of elements that are
    // to be checked
    int range = B - A;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
        // If an element is in range
        if (abs(arr[i]) >= A && abs(arr[i]) <= B) {
            // Negating at index ‘element – A’
            int z = abs(arr[i]) - A;
            if (arr[z] > 0)
                arr[z] = arr[z] * -1;
        }
    }
 
    // Checking whether elements in range 0-range
    // are negative
    int count = 0;
    for (int i = 0; i <= range && i < n; i++) {
        // Element from range is missing from array
        if (arr[i] > 0)
            return false;
        else
            count++;
    }
    if (count != (range + 1))
        return false;
    // All range elements are present
    return true;
}
 
// Driver code
int main()
{
    // Defining Array and size
    int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // A is lower limit and B is the upper limit
    // of range
    int A = 2, B = 5;
    // True denotes all elements were present
    if (check_elements(arr, n, A, B))
        cout << "Yes";
    // False denotes any element was not present
    else
        cout << "No";
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

C




#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
// Function to check the array for elements in
// given range
bool check_elements(int arr[], int n, int A, int B)
{
    // Range is the no. of elements that are
    // to be checked
    int range = B - A;
 
    // Traversing the array
    for (int i = 0; i < n; i++) {
        // If an element is in range
        if (abs(arr[i]) >= A && abs(arr[i]) <= B) {
            // Negating at index ‘element – A’
            int z = abs(arr[i]) - A;
            if (arr[z] > 0)
                arr[z] = arr[z] * -1;
        }
    }
 
    // Checking whether elements in range 0-range
    // are negative
    int count = 0;
    for (int i = 0; i <= range && i < n; i++) {
        // Element from range is missing from array
        if (arr[i] > 0)
            return false;
        else
            count++;
    }
    if (count != (range + 1))
        return false;
    // All range elements are present
    return true;
}
 
// Driver code
int main()
{
    // Defining Array and size
    int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // A is lower limit and B is the upper limit
    // of range
    int A = 2, B = 5;
    // True denotes all elements were present
    if (check_elements(arr, n, A, B))
        printf("Yes");
    // False denotes any element was not present
    else
        printf("No");
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

Java




// JAVA Code for Check if an array contains
// all elements of a given range
import java.util.*;
 
class GFG {
     
    // Function to check the array for elements in
    // given range
     public static boolean check_elements(int arr[], int n,
                                             int A, int B)
    {
        // Range is the no. of elements that are
        // to be checked
        int range = B - A;
       
        // Traversing the array
        for (int i = 0; i < n; i++) {
       
            // If an element is in range
            if (Math.abs(arr[i]) >= A &&
                           Math.abs(arr[i]) <= B) {
       
                 
                int z = Math.abs(arr[i]) - A;
                if (arr[z] > 0) {
                    arr[z] = arr[z] * -1;
                }
            }
        }
       
        // Checking whether elements in range 0-range
        // are negative
        int count=0;
 
        for (int i = 0; i <= range && i<n; i++) {
       
            // Element from range is missing from array
            if (arr[i] > 0)
                return false;
            else
                count++;
        }
 
        if(count!= (range+1))
            return false;
 
        // All range elements are present
        return true;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        // Defining Array and size
        int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
        int n = arr.length;
       
        // A is lower limit and B is the upper limit
        // of range
        int A = 2, B = 5;
       
        // True denotes all elements were present
        if (check_elements(arr, n, A, B))
            System.out.println("Yes");
       
        // False denotes any element was not present
        else
            System.out.println("No");
    }
}
// This code is contributed by Arnav Kr. Mandal.

Python3




# Function to check the array for
# elements in given range
def check_elements(arr, n, A, B) :
     
    # Range is the no. of elements
    # that are to be checked
    rangeV = B - A
     
    # Traversing the array
    for i in range(0, n):
     
        # If an element is in range
        if (abs(arr[i]) >= A and
            abs(arr[i]) <= B) :
     
            # Negating at index ‘element – A’
            z = abs(arr[i]) - A
            if (arr[z] > 0) :
                arr[z] = arr[z] * -1
             
    # Checking whether elements in
    # range 0-range are negative
    count = 0
    for i in range(0, rangeV + 1):
        if i >= n:
            break
             
        # Element from range is
        # missing from array
        if (arr[i] > 0):
            return False
        else:
            count = count + 1
     
    if(count != (rangeV + 1)):
        return False
         
    # All range elements are present
    return True
 
# Driver code
 
# Defining Array and size
arr = [ 1, 4, 5, 2, 7, 8, 3 ]
n = len(arr)
     
# A is lower limit and B is
# the upper limit of range
A = 2
B = 5
     
# True denotes all elements
# were present
if (check_elements(arr, n, A, B)) :
    print("Yes")
     
# False denotes any element
# was not present
else:
    print("No")
 
# This code is contributed
# by Yatin Gupta

C#




// C# Code for Check if an array contains
// all elements of a given range
using System;
 
class GFG {
     
    // Function to check the array for
    // elements in given range
    public static bool check_elements(int []arr, int n,
                                      int A, int B)
    {
        // Range is the no. of elements
        // that are to be checked
        int range = B - A;
     
        // Traversing the array
        for (int i = 0; i < n; i++)
        {
     
            // If an element is in range
            if (Math.Abs(arr[i]) >= A &&
                Math.Abs(arr[i]) <= B)
                {
                    int z = Math.Abs(arr[i]) - A;
                    if (arr[z] > 0)
                    {
                      arr[z] = arr[z] * - 1;
                    }
                }
        }
     
        // Checking whether elements in
        // range 0-range are negative
        int count=0;
 
        for (int i = 0; i <= range
             && i < n; i++)
        {
     
            // Element from range is
            // missing from array
            if (arr[i] > 0)
                return false;
            else
                count++;
        }
 
        if(count != (range + 1))
            return false;
 
        // All range elements are present
        return true;
    }
     
    // Driver Code
    public static void Main(String []args)
    {
        // Defining Array and size
        int []arr = {1, 4, 5, 2, 7, 8, 3};
        int n = arr.Length;
     
        // A is lower limit and B is
        // the upper limit of range
        int A = 2, B = 5;
     
        // True denotes all elements were present
        if (check_elements(arr, n, A, B))
         Console.WriteLine("Yes");
     
        // False denotes any element was not present
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.

PHP




<?php
// Function to check the
// array for elements in
// given range
function check_elements($arr, $n,
                        $A, $B)
{
    // Range is the no. of
    // elements that are to
    // be checked
    $range = $B - $A;
 
    // Traversing the array
    for ($i = 0; $i < $n; $i++)
    {
 
        // If an element is in range
        if (abs($arr[$i]) >= $A &&
            abs($arr[$i]) <= $B)
        {
 
            // Negating at index
            // ‘element – A’
            $z = abs($arr[$i]) - $A;
            if ($arr[$z] > 0)
            {
                $arr[$z] = $arr[$z] * -1;
            }
        }
    }
 
    // Checking whether elements
    // in range 0-range are negative
    $count = 0;
    for ($i = 0; $i <= $range &&
                 $i< $n; $i++)
    {
 
        // Element from range is
        // missing from array
        if ($arr[$i] > 0)
            return -1;
        else
            $count++;
    }
    if($count!= ($range + 1))
        return -1;
    // All range elements
    // are present
    return true;
}
 
// Driver code
 
// Defining Array and size
$arr = array(1, 4, 5, 2,
             7, 8, 3);
$n = sizeof($arr);
 
// A is lower limit and
// B is the upper limit
// of range
$A = 2; $B = 5;
 
// True denotes all
// elements were present
if ((check_elements($arr, $n,
                    $A, $B)) == true)
 
    echo "Yes";
 
// False denotes any
// element was not present
else
    echo "No";
 
// This code is contributed by aj_36
?>

Javascript




<script>
 
    // Javascript Code for Check
    // if an array contains
    // all elements of a given range
     
    // Function to check the array for
    // elements in given range
    function check_elements(arr, n, A, B)
    {
        // Range is the no. of elements
        // that are to be checked
        let range = B - A;
       
        // Traversing the array
        for (let i = 0; i < n; i++)
        {
       
            // If an element is in range
            if (Math.abs(arr[i]) >= A &&
                Math.abs(arr[i]) <= B)
                {
                    let z = Math.abs(arr[i]) - A;
                    if (arr[z] > 0)
                    {
                      arr[z] = arr[z] * - 1;
                    }
                }
        }
       
        // Checking whether elements in
        // range 0-range are negative
        let count=0;
   
        for (let i = 0; i <= range &&
        i < n; i++)
        {
       
            // Element from range is
            // missing from array
            if (arr[i] > 0)
                return false;
            else
                count++;
        }
   
        if(count != (range + 1))
            return false;
   
        // All range elements are present
        return true;
    }
     
    // Defining Array and size
    let arr = [1, 4, 5, 2, 7, 8, 3];
    let n = arr.length;
 
    // A is lower limit and B is
    // the upper limit of range
    let A = 2, B = 5;
 
    // True denotes all elements were present
    if (check_elements(arr, n, A, B))
      document.write("Yes");
 
    // False denotes any element was not present
    else
      document.write("No");
     
</script>

Output

Yes

Time complexity : O(n) 
Auxiliary space : O(1)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!