count
Problem
Given a array of unsorted numbers, check if all the numbers in the array are consecutive numbers.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
What if all the elements are positive: Check if Array is Consecutive Positive Integers.
Solution
Method 1 - Sorting
Sort the array, and check if consecutive number differ by 1.
Complexity
- Time Complexity – O(nlogn)
- Space Complexity - O(1)
Method 2 - Subtract Min from array elements and check duplicates and bounds
Algorithm
- Find the Maximum and minimum elements in array (Say the array is arrA)
- Check if array length = max-min+1
- Subtract the min from every element of the array.
- Check if array doesn’t have duplicates OR if index is out bound from (0 - max-min+1)
for Step 4 - checking the duplicates. Also, the solution assumes that numbers like in range [0, max-min+1)
. But if they are out of the range, then we again know, that elements can’t be consecutive.
For Step 4 - checking the duplicates
As, the array contains negative
elements, we may have to use aux
array.
- Create an
aux
array and put0
at every position - Navigate the main array and update the aux array as
aux[arrA[i]]=1
- During step 2 if we find any index position already filled with 1, we have duplicates, return false
Code
|
|
|
|
|
|
Complexity
- Time Complexity – O(n)
- Space Complexity - O(n)