Check if array elements are consecutive | Added Method 4 - GeeksforGeeks

29 Apr, 2022
Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers. Examples: a) If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.b) If the array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.c) If the array is {34, 23, 52, 12, 3}, then the function should return false because the elements are not consecutive.d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.Time Complexity: O(nLogn)Method 2 (Use visited array) The idea is to check for the following two conditions. If the following two conditions are true, then return true. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input array arr[] to the visited array by using arr[i] – min as the index in visited[].  
C++
Java
Python3
C#
PHP
Javascript
#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive  If elements are consecutive, then returns true, else returns  false */bool areConsecutive(int arr[], int n){  if ( n <  1 )    return false;   /* 1) Get the minimum element in array */  int min = getMin(arr, n);   /* 2) Get the maximum element in array */  int max = getMax(arr, n);   /* 3) max - min + 1 is equal to n,  then only check all elements */  if (max - min  + 1 == n)  {      /* Create a temp array to hold visited flag of all elements.         Note that, calloc is used here so that all values are initialized         as false */      bool *visited = (bool *) calloc (n, sizeof(bool));      int i;      for (i = 0; i < n; i++)      {         /* If we see an element again, then return false */         if ( visited[arr[i] - min] != false )           return false;          /* If visited first time, then mark the element as visited */         visited[arr[i] - min] = true;      }       /* If all elements occur once, then return true */      return true;  }   return false; // if (max - min  + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){  int min = arr[0];  for (int i = 1; i < n; i++)   if (arr[i] < min)     min = arr[i];  return min;} int getMax(int arr[], int n){  int max = arr[0];  for (int i = 1; i < n; i++)   if (arr[i] > max)     max = arr[i];  return max;} /* Driver program to test above functions */int main(){    int arr[]= {5, 4, 2, 3, 1, 6};    int n = sizeof(arr)/sizeof(arr[0]);    if(areConsecutive(arr, n) == true)        printf(" Array elements are consecutive ");    else        printf(" Array elements are not consecutive ");    getchar();    return 0;}
class AreConsecutive{    /* The function checks if the array elements are consecutive       If elements are consecutive, then returns true, else returns       false */    boolean areConsecutive(int arr[], int n)    {        if (n < 1)            return false;         /* 1) Get the minimum element in array */        int min = getMin(arr, n);         /* 2) Get the maximum element in array */        int max = getMax(arr, n);         /* 3) max - min + 1 is equal to n,  then only check all elements */        if (max - min + 1 == n)        {            /* Create a temp array to hold visited flag of all elements.               Note that, calloc is used here so that all values are initialized               as false */            boolean visited[] = new boolean[n];            int i;            for (i = 0; i < n; i++)            {                /* If we see an element again, then return false */                if (visited[arr[i] - min] != false)                    return false;                 /* If visited first time, then mark the element as visited */                visited[arr[i] - min] = true;            }                         /* If all elements occur once, then return true */            return true;        }        return false; // if (max - min  + 1 != n)    }     /* UTILITY FUNCTIONS */    int getMin(int arr[], int n)    {        int min = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] < min)                min = arr[i];        }        return min;    }     int getMax(int arr[], int n)    {        int max = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];        }        return max;    }     /* Driver program to test above functions */    public static void main(String[] args)    {        AreConsecutive consecutive = new AreConsecutive();        int arr[] = {5, 4, 2, 3, 1, 6};        int n = arr.length;        if (consecutive.areConsecutive(arr, n) == true)            System.out.println("Array elements are consecutive");        else            System.out.println("Array elements are not consecutive");    }} // This code has been contributed by Mayank Jaiswal
# Helper functions to get Minimum and# Maximum in an array # The function checks if the array elements# are consecutive. If elements are consecutive,# then returns true, else returns falsedef areConsecutive(arr, n):     if ( n < 1 ):        return False         # 1) Get the Minimum element in array */    Min = min(arr)         # 2) Get the Maximum element in array */    Max = max(arr)         # 3) Max - Min + 1 is equal to n,    # then only check all elements */    if (Max - Min + 1 == n):                 # Create a temp array to hold visited        # flag of all elements. Note that, calloc        # is used here so that all values are        # initialized as false        visited = [False for i in range(n)]             for i in range(n):                         # If we see an element again,            # then return false */            if (visited[arr[i] - Min] != False):                return False                 # If visited first time, then mark            # the element as visited */            visited[arr[i] - Min] = True             # If all elements occur once,        # then return true */        return True         return False # if (Max - Min + 1 != n) # Driver Codearr = [5, 4, 2, 3, 1, 6]n = len(arr)if(areConsecutive(arr, n) == True):    print("Array elements are consecutive ")else:    print("Array elements are not consecutive ") # This code is contributed by mohit kumar
using System; class GFG {         /* The function checks if the array elements    are consecutive If elements are consecutive,    then returns true, else returns    false */    static bool areConsecutive(int []arr, int n)    {        if (n < 1)            return false;         /* 1) Get the minimum element in array */        int min = getMin(arr, n);         /* 2) Get the maximum element in array */        int max = getMax(arr, n);         /* 3) max - min + 1 is equal to n, then        only check all elements */        if (max - min + 1 == n)        {                         /* Create a temp array to hold visited            flag of all elements. Note that, calloc            is used here so that all values are            initialized as false */            bool []visited = new bool[n];            int i;                         for (i = 0; i < n; i++)            {                                 /* If we see an element again, then                return false */                if (visited[arr[i] - min] != false)                    return false;                 /* If visited first time, then mark                the element as visited */                visited[arr[i] - min] = true;            }                         /* If all elements occur once, then            return true */            return true;        }        return false; // if (max - min + 1 != n)    }     /* UTILITY FUNCTIONS */    static int getMin(int []arr, int n)    {        int min = arr[0];                 for (int i = 1; i < n; i++)        {            if (arr[i] < min)                min = arr[i];        }                 return min;    }     static int getMax(int []arr, int n)    {        int max = arr[0];                 for (int i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];        }                 return max;    }     /* Driver program to test above functions */    public static void Main()    {        int []arr = {5, 4, 2, 3, 1, 6};        int n = arr.Length;                 if (areConsecutive(arr, n) == true)            Console.Write("Array elements are"                              + " consecutive");        else            Console.Write("Array elements are"                         + " not consecutive");    }} // This code is contributed by nitin mittal.
<?php// PHP Program for above approach // The function checks if the array elements// are consecutive. If elements are consecutive,// then returns true, else returns falsefunction areConsecutive($arr, $n){    if ( $n < 1 )        return false;         // 1) Get the minimum element in array    $min = getMin($arr, $n);         // 2) Get the maximum element in array    $max = getMax($arr, $n);         // 3) $max - $min + 1 is equal to $n,    // then only check all elements    if ($max - $min + 1 == $n)    {                 // Create a temp array to hold        // visited flag of all elements.        $visited = array();        for ($i = 0; $i < $n; $i++)        {            $visited[$i] = false;        }        for ($i = 0; $i < $n; $i++)        {            // If we see an element again,            // then return false            if ( $visited[$arr[$i] - $min] != false )            return false;                 // If visited first time, then mark            // the element as visited            $visited[$arr[$i] - $min] = true;        }             // If all elements occur once,        // then return true        return true;    }         return false; // if ($max - $min + 1 != $n)} // UTILITY FUNCTIONSfunction getMin($arr, $n){    $min = $arr[0];    for ($i = 1; $i < $n; $i++)        if ($arr[$i] < $min)            $min = $arr[$i];    return $min;} function getMax($arr, $n){    $max = $arr[0];    for ($i = 1; $i < $n; $i++)        if ($arr[$i] > $max)            $max = $arr[$i];    return $max;} // Driver Code$arr = array(5, 4, 2, 3, 1, 6);$n = count($arr);if(areConsecutive($arr, $n) == true)    echo "Array elements are consecutive ";else    echo "Array elements are not consecutive ";     // This code is contributed by rathbhupendra?>
<script>         /* The function checks if the array elements are consecutive       If elements are consecutive, then returns true, else returns       false */    function areConsecutive(arr,n)    {        if (n < 1)            return false;                     /* 1) Get the minimum element in array */        let min = getMin(arr, n);                  /* 2) Get the maximum element in array */        let max = getMax(arr, n);                 /* 3) max - min + 1 is equal to n,  then only check all elements */        if (max - min + 1 == n)         {            /* Create a temp array to hold visited flag of all elements.               Note that, calloc is used here so that all values are initialized                as false */            let visited = new Array(n);            for(let i=0;i<n;i++)            {                visited[i]=false;            }            let i;            for (i = 0; i < n; i++)             {                /* If we see an element again, then return false */                if (visited[arr[i] - min] != false)                {                    return false;                }                /* If visited first time, then mark the element as visited */                visited[arr[i] - min] = true;            }            /* If all elements occur once, then return true */            return true;        }        return false; // if (max - min  + 1 != n)    }         /* UTILITY FUNCTIONS */    function getMin(arr, n)     {        let min = arr[0];        for (let i = 1; i < n; i++)         {            if (arr[i] < min)                min = arr[i];        }        return min;    }    function getMax(arr,n)    {        let max = arr[0];        for (let i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];                      }        return max;    }         /* Driver program to test above functions */    let arr=[5, 4, 2, 3, 1, 6]    let  n = arr.length;    if (areConsecutive(arr, n))    {        document.write("Array elements are consecutive");    }    else    {        document.write("Array elements are not consecutive");    }    // This code is contributed by avanitrachhadiya2155     </script>
 Array elements are consecutive 
Time Complexity: O(n) Extra Space: O(n) 
Output:
Array elements are consecutive
Method 3 (Mark visited array elements as negative) This method is O(n) time complexity and O(1) extra space, but it changes the original array, and it works only if all numbers are positive. We can get the original array by adding an extra step though. It is an extension of method 2, and it has the same two steps. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.In this method, the implementation of step 2 differs from method 2. Instead of creating a new array, we modify the input array arr[] to keep track of visited elements. The idea is to traverse the array and for each index i (where 0 ≤ i < n), make arr[arr[i] – min]] as a negative value. If we see a negative value again then there is repetition.  
C++
Java
Python 3
C#
PHP
Javascript
#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive  If elements are consecutive, then returns true, else returns  false */bool areConsecutive(int arr[], int n){     if ( n <  1 )        return false;     /* 1) Get the minimum element in array */    int min = getMin(arr, n);     /* 2) Get the maximum element in array */    int max = getMax(arr, n);     /* 3) max - min + 1 is equal to n then only check all elements */    if (max - min  + 1 == n)    {        int i;        for(i = 0; i < n; i++)        {            int j;             if (arr[i] < 0)                j = -arr[i] - min;            else                j = arr[i] - min;             // if the value at index j is negative then            // there is repetition            if (arr[j] > 0)                arr[j] = -arr[j];            else                return false;        }         /* If we do not see a negative value then all elements           are distinct */        return true;    }     return false; // if (max - min  + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){    int min = arr[0];    for (int i = 1; i < n; i++)        if (arr[i] < min)            min = arr[i];    return min;} int getMax(int arr[], int n){    int max = arr[0];    for (int i = 1; i < n; i++)        if (arr[i] > max)            max = arr[i];    return max;} /* Driver program to test above functions */int main(){    int arr[]= {1, 4, 5, 3, 2, 6};    int n = sizeof(arr)/sizeof(arr[0]);    if(areConsecutive(arr, n) == true)        printf(" Array elements are consecutive ");    else        printf(" Array elements are not consecutive ");    getchar();    return 0;}
class AreConsecutive{    /* The function checks if the array elements are consecutive       If elements are consecutive, then returns true, else returns       false */    boolean areConsecutive(int arr[], int n)    {        if (n < 1)            return false;         /* 1) Get the minimum element in array */        int min = getMin(arr, n);         /* 2) Get the maximum element in array */        int max = getMax(arr, n);         /* 3) max-min+1 is equal to n then only check all elements */        if (max - min + 1 == n)        {            int i;            for (i = 0; i < n; i++)            {                int j;                 if (arr[i] < 0)                    j = -arr[i] - min;                else                    j = arr[i] - min;                 // if the value at index j is negative then                // there is repetition                if (arr[j] > 0)                    arr[j] = -arr[j];                else                    return false;            }             /* If we do not see a negative value then all elements               are distinct */            return true;        }         return false; // if (max-min+1 != n)    }     /* UTILITY FUNCTIONS */    int getMin(int arr[], int n)    {        int min = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] < min)                min = arr[i];        }        return min;    }     int getMax(int arr[], int n)    {        int max = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];        }        return max;    }     /* Driver program to test above functions */    public static void main(String[] args)    {        AreConsecutive consecutive = new AreConsecutive();        int arr[] = {5, 4, 2, 3, 1, 6};        int n = arr.length;        if (consecutive.areConsecutive(arr, n) == true)            System.out.println("Array elements are consecutive");        else            System.out.println("Array elements are not consecutive");    }} // This code is contributed by Mayank Jaiswal
# Helper functions to get minimum and# maximum in an array # The function checks if the array# elements are consecutive. If elements# are consecutive, then returns true,# else returns falsedef areConsecutive(arr, n):     if ( n < 1 ):        return False     # 1) Get the minimum element in array    min = getMin(arr, n)     # 2) Get the maximum element in array    max = getMax(arr, n)     # 3) max - min + 1 is equal to n    # then only check all elements    if (max - min + 1 == n):         for i in range(n):             if (arr[i] < 0):                j = -arr[i] - min            else:                j = arr[i] - min             # if the value at index j is negative            # then there is repetition            if (arr[j] > 0):                arr[j] = -arr[j]            else:                return False         # If we do not see a negative value        # then all elements are distinct        return True     return False     # if (max - min + 1 != n) # UTILITY FUNCTIONSdef getMin(arr, n):         min = arr[0]    for i in range(1, n):        if (arr[i] < min):            min = arr[i]    return min def getMax(arr, n):    max = arr[0]    for i in range(1, n):        if (arr[i] > max):            max = arr[i]    return max # Driver Codeif __name__ == "__main__":         arr = [1, 4, 5, 3, 2, 6]    n = len(arr)    if(areConsecutive(arr, n) == True):        print(" Array elements are consecutive ")    else:        print(" Array elements are not consecutive ") # This code is contributed by ita_c
using System; class GFG {         /* The function checks if the array    elements are consecutive If elements    are consecutive, then returns true,    else returns false */    static bool areConsecutive(int []arr, int n)    {        if (n < 1)            return false;         /* 1) Get the minimum element in        array */        int min = getMin(arr, n);         /* 2) Get the maximum element in        array */        int max = getMax(arr, n);         /* 3) max-min+1 is equal to n then        only check all elements */        if (max - min + 1 == n)        {            int i;            for (i = 0; i < n; i++)            {                int j;                 if (arr[i] < 0)                    j = -arr[i] - min;                else                    j = arr[i] - min;                 // if the value at index j                // is negative then                // there is repetition                if (arr[j] > 0)                    arr[j] = -arr[j];                else                    return false;            }             /* If we do not see a negative            value then all elements            are distinct */            return true;        }         // if (max-min+1 != n)        return false;    }     /* UTILITY FUNCTIONS */    static int getMin(int []arr, int n)    {        int min = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] < min)                min = arr[i];        }        return min;    }     static int getMax(int []arr, int n)    {        int max = arr[0];        for (int i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];        }        return max;    }     /* Driver program to test above    functions */    public static void Main()    {        int []arr = {5, 4, 2, 3, 1, 6};        int n = arr.Length;                 if (areConsecutive(arr, n) == true)            Console.Write("Array elements "                      + "are consecutive");        else            Console.Write("Array elements "                  + "are not consecutive");    }} // This code is contributed by nitin mittal.
<?php /* The function checks if the array elementsare consecutive If elements are consecutive,then returns true, else returns false */function areConsecutive( $arr, $n){     if ( $n < 1 )        return false;     /* 1) Get the minimum element in array */    $min = getMin($arr, $n);     /* 2) Get the maximum element in array */    $max = getMax($arr, $n);     /* 3) max - min + 1 is equal to n then          only check all elements */    if ($max - $min + 1 == $n)    {    $i;        for($i = 0; $i < $n; $i++)        {            $j;             if ($arr[$i] < 0)                $j = -$arr[$i] - $min;            else                $j = $arr[$i] - $min;             // if the value at index j is            // negative then there is            // repetition            if ($arr[$j] > 0)                $arr[$j] = -$arr[$j];            else                return false;        }         /* If we do not see a negative value        then all elements are distinct */        return true;    }     return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */function getMin( $arr, $n){    $min = $arr[0];    for ( $i = 1; $i < $n; $i++)        if ($arr[$i] < $min)            $min = $arr[$i];    return $min;} function getMax( $arr, $n){    $max = $arr[0];    for ( $i = 1; $i < $n; $i++)        if ($arr[$i] > $max)            $max = $arr[$i];    return $max;} /* Driver program to test above functions */    $arr= array(1, 4, 5, 3, 2, 6);    $n = count($arr);    if(areConsecutive($arr, $n) == true)        echo " Array elements are consecutive ";    else        echo " Array elements are not consecutive ";  // This code is contributed by anuj_67.?>
<script>         /* The function checks if the array elements are consecutive       If elements are consecutive, then returns true, else returns       false */    function areConsecutive(arr,n)    {        if (n < 1)            return false;          /* 1) Get the minimum element in array */        let min = getMin(arr, n);          /* 2) Get the maximum element in array */        let max = getMax(arr, n);          /* 3) max-min+1 is equal to n then only check all elements */        if (max - min + 1 == n)        {            let i;            for (i = 0; i < n; i++)            {                let j;                  if (arr[i] < 0)                    j = -arr[i] - min;                else                    j = arr[i] - min;                  // if the value at index j is negative then                // there is repetition                if (arr[j] > 0)                    arr[j] = -arr[j];                else                    return false;            }              /* If we do not see a negative value then all elements               are distinct */            return true;        }          return false; // if (max-min+1 != n)    }         /* UTILITY FUNCTIONS */    function getMin(arr,n)    {         let min = arr[0];        for (let i = 1; i < n; i++)        {            if (arr[i] < min)                min = arr[i];        }        return min;       }         function getMax(arr,n)    {        let max = arr[0];        for (let i = 1; i < n; i++)        {            if (arr[i] > max)                max = arr[i];        }        return max;             }         /* Driver program to test above functions */    let arr=[5, 4, 2, 3, 1, 6];    let n = arr.length;    if (areConsecutive(arr, n) == true)        document.write("Array elements are consecutive");    else        document.write("Array elements are not consecutive");                  // This code is contributed by unknown2108</script>
 Array elements are consecutive 
Note that this method might not work for negative numbers. For example, it returns false for {2, 1, 0, -3, -1, -2}.Time Complexity: O(n) Extra Space: O(1)  
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
Method 4 (Using XOR property)
This method is O(n) time complexity and O(1) extra space, does not changes the original array, and it works everytime.
As elements should be consecutive, let’s find minimum element or maximum element in array.Now if we take xor of two same elements it will result in zero (a^a = 0).Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive 
As elements should be consecutive, let’s find minimum element or maximum element in array.
Now if we take xor of two same elements it will result in zero (a^a = 0).
Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive 
C
C++
//Code  is contributed by Dhananjay Dhawale @chessnoobdj #include<stdio.h>#include<stdlib.h> /* UTILITY FUNCTIONS */int getMin(int arr[], int n){    int min = arr[0];    for (int i = 1; i < n; i++)        if (arr[i] < min)            min = arr[i];    return min;}int areConsecutive(int arr[], int n){    int min_ele = getMin(arr, n), num = 0;    for(int i=0; i<n; i++){        num ^= min_ele^arr[i];        min_ele += 1;    }    if(num == 0)        return 1;    return 0;} /* Driver program to test above functions */int main(){    int arr[]= {1, 4, 5, 3, 2, 6};    int n = sizeof(arr)/sizeof(arr[0]);    if(areConsecutive(arr, n) == 1)        printf(" Array elements are consecutive ");    else        printf(" Array elements are not consecutive ");    getchar();    return 0;}
//Code  is contributed by Dhananjay Dhawale @chessnoobdj #include <iostream>#include <algorithm>using namespace std; bool areConsecutive(int arr[], int n){    int min_ele = *min_element(arr, arr+n), num = 0;    for(int i=0; i<n; i++){        num ^= min_ele^arr[i];        min_ele += 1;    }    if(num == 0)        return 1;    return 0;} /* Driver program to test above functions */int main(){    int arr[]= {1, 4, 5, 3, 2, 6};    int n = sizeof(arr)/sizeof(arr[0]);    if(areConsecutive(arr, n) == true)        printf(" Array elements are consecutive ");    else        printf(" Array elements are not consecutive ");    getchar();    return 0;}
 Array elements are consecutive 
nitin mittal
vt_m
ukasp
rathbhupendra
mohit kumar 29
avanitrachhadiya2155
unknown2108
chessnoobdj
surinderdawra388
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Multidimensional Arrays in Java
Introduction to Arrays