Question :
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 numberof
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 is
int isHollow(int[ ] a).
Examples: isHollow({1,2,4,0,0,0,3,4,5}) returns true.
isHollow ({1,2,0,0,0,3,4,5}) returns false. : isHollow ({1,2,4,9,
0,0,0,3,4, 5}) returns false. isHollow ({1,2, 0,0, 3,4}) returns
false.
Solution :
public static int
isHollow(int[] a)
{
int
precCount = 0, zeroCount = 0, zeroIndex = 0,
followCount = 0, followIndex = 0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] ==
0)
precCount++;
if (a[i]
!= 0)
zeroIndex = i;
break;
}
for (int i = zeroIndex; i < a.Length; i++)
{
if (a[i]
== 0)
zeroCount++;
if (a[i]
!= 0)
followIndex = i;
break;
}
for (int i = 0; i < a.Length; i++)
{
if (a[i]
!= 0)
followCount++;
if (a[i] == 0)
break;
}
if
(followCount == precCount && zeroCount > 2)
return 1;
else
return 0;
}
The above solution seems to be wrong to me, this is my solution, this also takes care of the edge case ({0,0,0}) which should return 0 not 1
ReplyDeletepublic static int isHollow(int []a){
int n = a.Length;
int precCount = 0, zeroCount = 0, zeroIndex = 0,
followCount = 0, followIndex = 0;
for (int i = 0; i < n; i++)
{
if (a[i] != 0) precCount++;
if (a[i] == 0) {
zeroIndex = i;
break;
}
}
for (int i = zeroIndex; i < n; i++)
{
if (a[i] == 0) zeroCount++;
if (a[i] != 0){
followIndex = i;
break;
}
}
for (int i = 0; i < n; i++)
{
if (a[i] != 0) followCount++;
if (a[i] == 0) break;
}
if (followCount == precCount && zeroCount > 2 && precCount>0 && followCount>0){
return 1;
}
else{
return 0;
}
}
Sorry KC i think your second last condition to check the followCount is not correct.
DeleteYou can use this instead to count the followCount
**********************************************
for (int i = followIndex; i < n; i++)
{
if (a[i] != 0) followCount++;
}