Given an integer array, check if only consecutive integers form the array.

For example,

Input:  { -1, 5, 4, 2, 0, 3, 1 }
 
Output: The array contains consecutive integers from -1 to 5.
 
 
Input:  { 4, 2, 4, 3, 1 }
 
Output: The array does not contain consecutive integers as element 4 is repeated.

Practice this problem

Approach 1

For an array to contain consecutive integers,

  1. The difference between the maximum and minimum element in it should be exactly n-1.
  2. All elements in the array should be distinct (we can check this by inserting the elements in a set or using a visited array).

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

The array contains consecutive integers

Java


Download  Run Code

Output:

The array contains consecutive integers

Python


Download  Run Code

Output:

The array contains consecutive integers

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the input.

Approach 2

We can check if an array contains consecutive integers by inserting all array elements in a sorted set and

  1. Check if all elements are distinct (we can check this while inserting the elements in the set).
  2. Check if the difference between consecutive elements in the sorted set is 1.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

The array contains consecutive integers

Java


Download  Run Code

Output:

The array contains consecutive integers

Python


Download  Run Code

Output:

The array contains consecutive integers

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the input.