Check if the elements of an array are consecutive

Given an array, check whether the array has consecutive elements

Here, consecutive elements means, when we take all the elements in the array they need to form an consecutive sequence.

Example

Input :

arr[]={65,68,66,64,67}

Output :

array contains consecutive elements

here, all the elements in the array are consecutive as they are in increasing oreder ie, 64,65,66,67,68

Time Complexity : O(n)

1. First find the minimum and maximum element in the array, Assign two variables min and max to the maximum and minimum integer values respectively.
    Till less than the size of the array, pick each element in the array
    a. If the element is greater than the max element, assign max element to the picked element
    b. If the element is less than the min element, assign min element to the picked element.
2. If the number of elements between max and min including themselves equals size of array then proceed.
    Till less than the size of the array, pick each element in the array
    a. If the element is repeated, then print that all elements are not consecutive and stop.
    b. If the  Loop didn't break, then print all are consecutive elements

C++ Program

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

int main()
{
	int arr[] = {83, 78, 80, 81, 79, 82}; //array
	int N = sizeof(arr)/sizeof(arr[0]);//size of array
	
	int min = INT_MAX , max = INT_MIN ;
	for(int i = 0 ; i < N; i++) //find minimum and maximum element
	{
		if(arr[i] > max)
			max = arr[i];
		if(arr[i] < min)
			min = arr[i];
	}
	
	if(max - min + 1 == N) // if the number of elements between max and min including themselves equals size of array then proceed
	{
		bool visited_nodes[N] = {0};
		
		for(int i = 0 ; i < N; i ++)
			{
				if(visited_nodes[arr[i] -  min] == 1) //it means the element is repeated so we cant get consecutive elements
					{
					 cout << " Not all consecutive elements \n" ;
					 return 0;	
					}	
				else
					visited_nodes[arr[i] - min] = 1;
			}
		cout << "Consecutive element set\n";
		return 0;
	}
	
	cout << " Not all consecutive elements \n" ;
	
	return 0;
}
Try It

Algorithm 2(Use sorting) :

Time Complexity : O(nlogn)

1. Sort the elements in the array
2. Till the end of the sorted array, do linear scan
    a. If the difference between the current element and the next element is anything other than     1, then print all elements are not consecutive
    else,
    b. If all differences are 1, then print all elements are consecutive.

C++ Program

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

int main()
{
	int arr[] = {83, 78, 80, 81, 79, 82};
	int N = sizeof(arr)/sizeof(arr[0]);
	
	sort(arr,arr+N);
	
	for(int i=0 ; i < N - 1; i++)
		if(arr[i+1] > arr[i] + 1)
			{
				cout << "Not consecutive \n";
				return 0;
			}
	cout<<"Consecutive set\n";
	return 0;
}
Try It


Next > < Prev
Scroll to Top