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.
publicbooleanareConsecutive(int[] nums) {
// this method with work even if numbers are negativeint[] aux =newint[nums.length];
int max = findMax(nums);
int min = findMin(nums);
if (nums.length!= max - min + 1) {
returnfalse;
}
for (int i = 0; i < nums.length; i++) {
nums[i]= nums[i]- min;
aux[i]= 0;
}
for (int i = 0; i < nums.length; i++) {
if (aux[nums[i]]== 0) {
aux[nums[i]]= 1;
} else {
returnfalse;
}
}
//If we have reached till here means , we satisfied all the requirementsreturntrue;
}
publicintfindMax(int[] arrA) {
// find the maximum in arrayint max = arrA[0];
for (int i = 1; i < arrA.length; i++) {
if (max < arrA[i]) {
max = arrA[i];
}
}
return max;
}
publicintfindMin(int[] arrA) {
// find the minimum in arrayint min = arrA[0];
for (int i = 1; i < arrA.length; i++) {
if (min > arrA[i]) {
min = arrA[i];
}
}
return min;
}