An array is said to be hollow if it contains 3 or more zeros in the middle that are preceded and followed by the same number of non-zero elements. Write a function named
isHollow
that accepts an integer array and returns 1 if it is a hollow array, otherwise it returns 0. The function signature isint isHollow(int[ ] a)
.
Note: Please do not use any String functions. No sorting allowed. No additional arrays or data structures allowed.
Test Cases:
isHollow({1,2,4,0,0,0,3,4,5})
returns trueisHollow({1,2,4,0,0,0,1,0,3,4,5})
returns falseisHollow({1,2,0,0,0,3,4,5})
returns falseisHollow({1,2,4,9, 0,0,0,3,4,5})
returns falseisHollow({1,2, 0,0, 3,4})
returns false
private static int isHollow(int[] array) {
int length = array.length;
int startCount = 0;
int endCount = 0;
int zeroCount = 0;
int nonZeroCount = 0;
if (array[0] == 0 || array[length - 1] == 0) return 0;
for (int i = 0; i < length; i++) {
if (array[i] != 0) {
startCount++;
} else {
break;
}
}
for (int i = 0; i < length; i++) {
if (array[i] == 0) {
zeroCount++;
} else {
nonZeroCount++;
}
}
for (int i = length - 1; i >= 0; i--) {
if (array[i] != 0) {
endCount++;
} else {
break;
}
}
if (startCount == endCount && (startCount + endCount) == nonZeroCount && zeroCount >= 3) {
return 1;
}
return 0;
}