Sunday 24 December 2017

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;
        }

2 comments:

  1. 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

    public 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;
    }
    }

    ReplyDelete
    Replies
    1. Sorry KC i think your second last condition to check the followCount is not correct.

      You can use this instead to count the followCount
      **********************************************
      for (int i = followIndex; i < n; i++)
      {
      if (a[i] != 0) followCount++;
      }

      Delete

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page