I have a Long array with these numbers:
long[] = {1,2,3,5,6,7};
Notice that 4
is missing.
What's the best way to test this array if any such gaps exist or not?
I have a Long array with these numbers:
long[] = {1,2,3,5,6,7};
Notice that 4
is missing.
What's the best way to test this array if any such gaps exist or not?
If you're guaranteed that arrays is ordered without any duplicate then you could check that in O(1)
I think this code should work in this specific case :)
//assume that given array is ordered and has no duplicated value
long[] myarray = {5,6,7}; //no gap
long[] myarray1 = {1,2,4}; //has gap
long[] myarray2 = {10,11,12,13,14,15}; //no gap
//return true if has gap
//return false if no gap
//throw null-pointer if empty
public static boolean checkIfHasGap(long[] array) {
if (array.length == 0) {
throw new NullPointerException("Given Array is empty");
} else {
return array[0] + array.length != array[array.length - 1] + 1;
}
}
Loop through the array and check, if the current item is exactly x
more than the current index, where x
is the first element in your array.
public boolean hasGaps(long[] array) {
if(array == null || array.length == 0) {
return false;
}
long start = array[0];
for(int i = 0; i < array.length; i++) {
if(array[i] != i + start) {
return true;
}
}
return false;
}
public static boolean hasGaps(long[] array) {
if (array == null || array.length == 0) {
return false;
}
if (array[array.length - 1] - array[0] + 1 != array.length) {
return true;
}
for (int i = 1; i < array.length; i++) {
if (array[i] != array[i - 1] + 1) {
return true;
}
}
return false;
}
This method first check for the "easy" cases, then iterate the array to check the more complex cases.
A simpler and reliable way:
const getMissingNumbers = (list) => {
if (!list || list.length === 0) return [];
const missing = [];
// sort the list
list.sort((a, b) => a - b);
// pin start and end points in the list
const step = list[0];
const last = list[list.length - 1];
for (let i = step; i < last; i++) {
if (list.indexOf(i) === -1) missing.push(i);
}
return missing;
}