Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Friday, October 20, 2017

first 1 in array


idea is to Bsearch and check if we have 1 before find index.

Code:

int search(int arr[],int low,int high)
    {
        while(low<=high)
        {
            int mid=low+(high-low)/2;
            if(arr[mid]==1)
            {
                if(mid==0 || arr[mid-1]==0)
                return mid;
                high=mid-1;
            }
            else
            low=mid+1;
        }
        return -1;
    }

0 Comments:

Post a Comment

Stats