Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)

Given an unsorted array of distinct numbers, write a function that returns true if array consists of consecutive numbers.
Examples :

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

Input : arr[] = {2, 1, 0, -3, -1, -2}
Output : Yes

We have discussed three different approaches in below post

Check if array elements are consecutive



In above post. three methods for this problem are discussed with the best time complexity of O(n) and in O(1) extra space but that solution doesn’t handle the case of negative numbers. So, in this post, a method with time complexity of O(n) and using O(1) space will be discussed which will handle the case of negative also. An important assumption here is elements are distinct.

  1. Find the sum of the array.
  2. If given array elements are consecutive that means they are in AP. So, find min element i.e. first term of AP then calculate ap_sum = n/2 * [2a +(n-1)*d] where d = 1. So, ap_sum = n/2 * [2a +(n-1)]
  3. Compare both sums. Print Yes if equal, else No.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for above implementation
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if elements are consecutive
bool areConsecutives(int arr[], int n)
{
    // Find minimum element in array
    int first_term = *(min_element(arr, arr + n));
  
    // Calculate AP sum
    int ap_sum = (n * (2 * first_term + (n - 1) * 1)) / 2;
  
    // Calculate given array sum
    int arr_sum = 0;
    for (int i = 0; i < n; i++)
        arr_sum += arr[i];
  
    // Compare both sums and return
    return ap_sum == arr_sum;
}
  
// Drivers code
int main()
{
    int arr[] = { 2, 1, 0, -3, -1, -2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    areConsecutives(arr, n) ? cout << "Yes"
                            : cout << "No";
  
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if array elements
// are consecutive
import java.io.*;
  
class GFG {
  
    // Function to check if elements are 
    // consecutive
    static Boolean areConsecutives(int arr[],
                                      int n)
    {
        // Find minimum element in array
        int first_term = Integer.MAX_VALUE;
        for (int j = 0; j < n; j++)
        {
            if(arr[j] < first_term)
            first_term = arr[j];
        }
  
        // Calculate AP sum
        int ap_sum = (n * (2 * first_term +
                         (n - 1) * 1)) / 2;
  
        // Calculate given array sum
        int arr_sum = 0;
        for (int i = 0; i < n; i++)
            arr_sum += arr[i];
  
        // Compare both sums and return
        return ap_sum == arr_sum;
    }
  
    // Driver code
    public static void main(String[] args)
    {
    int arr[] = { 2, 1, 0, -3, -1, -2 };
    int n = arr.length;
      
    Boolean result = areConsecutives(arr, n);
    if(result == true)
    System.out.println("Yes");
    else
    System.out.println("No");
  
    }
}
// This code is contributed by Prerna Saini
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program for above
# implementation
import sys
  
# Function to check if elements
# are consecutive
def areConsecutives(arr, n):
  
    # Find minimum element in array
    first_term = sys.maxsize
    for i in range(n):
        if arr[i] < first_term:
            first_term = arr[i]
  
    # Calculate AP sum
    ap_sum = ((n * (2 * first_term + 
              (n - 1) * 1)) // 2)
  
    # Calculate given array sum
    arr_sum = 0
    for i in range( n):
        arr_sum += arr[i]
  
    # Compare both sums and return
    return ap_sum == arr_sum
  
# Driver Code
arr = [ 2, 1, 0, -3, -1, -2 ]
n = len(arr)
  
if areConsecutives(arr, n):
    print( "Yes")
else
    print( "No")
  
# This code is contributed
# by ChitraNayal
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if array 
// elements are consecutive
using System;
  
class GFG {
  
    // Function to check if elements  
    // are consecutive
    static bool areConsecutives(int []arr,
                                int n)
    {
          
        // Find minimum element in array
        int first_term = int.MaxValue;
          
        for (int j = 0; j < n; j++)
        {
            if(arr[j] < first_term)
            first_term = arr[j];
        }
  
        // Calculate AP sum
        int ap_sum = (n * (2 * first_term +
                     (n - 1) * 1)) / 2;
  
        // Calculate given array sum
        int arr_sum = 0;
        for (int i = 0; i < n; i++)
            arr_sum += arr[i];
  
        // Compare both sums and return
        return ap_sum == arr_sum;
    }
  
    // Driver code
    public static void Main()
    {
        int []arr = {2, 1, 0, -3, -1, -2};
        int n = arr.Length;
          
        bool result = areConsecutives(arr, n);
        if(result == true)
        Console.WriteLine("Yes");
        else
        Console.WriteLine("No");
  
    }
}
  
// This code is contributed by vt_m.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to check if 
// array elements are consecutive
  
// Function to check if elements 
// are consecutive
function areConsecutives($arr, $n)
{
      
    // Find minimum element in array
    $first_term = 9999999;
      
    for ($j = 0; $j < $n; $j++)
    {
        if($arr[$j] < $first_term)
            $first_term = $arr[$j];
    }
  
    // Calculate AP sum
    $ap_sum = intval(($n * (2 * $first_term
                         ($n - 1) * 1)) / 2);
  
    // Calculate given array sum
    $arr_sum = 0;
    for ($i = 0; $i < $n; $i++)
        $arr_sum += $arr[$i];
  
    // Compare both sums and return
    return $ap_sum == $arr_sum;
}
  
// Driver code
$arr = array(2, 1, 0, -3, -1, -2);
$n = count($arr);
  
$result = areConsecutives($arr, $n);
if($result == true)
echo "Yes";
else
echo "No";
  
// This code is contributed by Sam007
?>
chevron_right


Output :
Yes

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

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Improved By : vt_m, Sam007, chitranayal



Article Tags :
Practice Tags :