Find the transition point in a binary array

Given a sorted array containing only numbers 0 and 1, the task is to find the transition point efficiently. The transition point is a point where “0” ends and “1” begins.

Examples :

Input: 0 0 0 1 1
Output: 3

Explantion: Index of first 1 is 3

Input: 0 0 0 0 1 1 1 1
Output: 4

Explantion: Index of first 1 is 4

Naive Approach: Traverse the array and print the index of the first 1.

  • Algorithm:



    1. Traverse the array from start to the end of the array.
    2. If the current element is 1 print the index and terminate the program.
  • Implementation:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ implementation to find the transition point
    #include<iostream>
    using namespace std;
      
    // Function to find the transition point
    int findTransitionPoint(int arr[], int n)
    {
        //perform a linear search and return the index of 
        //first 1
        for(int i=0; i<n ;i++)
          if(arr[i]==1)
            return i;
      
        //if no element is 1
        return -1;
    }
      
    // Driver code
    int main()
    {
        int arr[] = {0, 0, 0, 0, 1, 1};
        int n = sizeof(arr) / sizeof(arr[0]);
      
        int point = findTransitionPoint(arr, n);
      
        point >= 0 ? cout<<"Transition point is " << point
                   : cout<<"There is no transition point";
        return 0;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java implementation to find the transition point
    import java.util.*;
      
    class GFG
    {
      
    // Function to find the transition point
    static int findTransitionPoint(int arr[], int n)
    {
        // perform a linear search and return the index of 
        // first 1
        for(int i = 0; i < n ; i++)
        if(arr[i] == 1)
            return i;
      
        // if no element is 1
        return -1;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = {0, 0, 0, 0, 1, 1};
        int n = arr.length;
          
        int point = findTransitionPoint(arr, n);
          
        if (point >= 0)
            System.out.print("Transition point is " + point);
        else
            System.out.print("There is no transition point");
    }
    }
      
    // This code is contributed by shivanisinghss2110

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python3 implementation to find the transition point
      
    # Function to find the transition point
    def findTransitionPoint(arr, n):
          
        # perform a linear search and return the index of 
        # first 1
        for i in range(n):
            if(arr[i] == 1):
                return i
          
        # if no element is 1
        return -1
      
    # Driver code
    arr = [0, 0, 0, 0, 1, 1]
    n = len(arr)
      
    point = findTransitionPoint(arr, n)
      
    if point >= 0:
        print("Transition point is", point)
    else
        print("There is no transition point")
          
    # This code is contributed by shubhamsingh10

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# implementation to find the transition point
    using System;
      
    class GFG 
    {
      
    // Function to find the transition point
    static int findTransitionPoint(int []arr ,int n)
    {
        // perform a linear search and return the index of 
        // first 1
        for(int i = 0; i < n ; i++)
        if(arr[i] == 1)
            return i;
      
        // if no element is 1
        return -1;
    }
      
     // Driver method
        public static void Main() 
        {
            int []arr = {0, 0, 0, 0, 1, 1};
            int point = findTransitionPoint(arr, arr.Length);
           
            Console.Write(point >= 0 ? "Transition point is " +
                       point : "There is no transition point");
        }
    }
       
      
    // This code is contributed by shivanisinghss2110

    chevron_right

    
    

  • Complexity Analysis:
    • Time Complexity: O(n).
      Only one traversal is needed, so the time complexity is O(n)
    • Space Complexity: O(1).
      No extra space is required so the space complexity is constant.

Efficient Approach: The idea is to use Binary Search, and find the smallest index of 1 in the array. As the array is sorted binary search can be performed.

  • Algorithm:
    1. Create two variables, l and r, initilize l = 0 and r = n-1 and a varibale ans = -1 to store the answer.
    2. Iterate the steps below till l <= r, lowerbound is less than the upperbound.
    3. Check if the element at middle index mid = (l+r)/2, is one or not.
    4. if the element is one then check for the least index of 1 element on the left side of middle element, i.e. update r = mid – 1 and update ans = mid.
    5. if the element is zero then check for the least index of 1 element on the right side of middle element, i.e. update l = mid + 1.
  • Implementation:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ implementation to find the transition point
    #include<iostream>
    using namespace std;
      
    // Function to find the transition point
    int findTransitionPoint(int arr[], int n)
    {
        // Initialise lower and upper bounnds
        int lb = 0, ub = n-1;
      
        // Perform Binary search
        while (lb <= ub)
        {
            // Find mid
            int mid = (lb+ub)/2;
      
            // update lower_bound if mid contains 0
            if (arr[mid] == 0)
                lb = mid+1;
      
            // If mid contains 1
            else if (arr[mid] == 1)
            {
                // Check if it is the left most 1
                // Return mid, if yes
                if (arr[mid-1]==0)
                    return mid;
      
                // Else update upper_bound
                ub = mid-1;
            }
        }
        return -1;
    }
      
    // Driver code
    int main()
    {
        int arr[] = {0, 0, 0, 0, 1, 1};
        int n = sizeof(arr) / sizeof(arr[0]);
      
        int point = findTransitionPoint(arr, n);
      
        point >= 0 ? cout<<"Transition point is " << point
                   : cout<<"There is no transition point";
        return 0;
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java implementation to find the transition point
      
    class Test
    {
        // Method to find the transition point
        static int findTransitionPoint(int arr[], int n)
        {
            // Initialise lower and upper bounnds
            int lb = 0, ub = n-1;
           
            // Perform Binary search
            while (lb <= ub)
            {
                // Find mid
                int mid = (lb+ub)/2;
           
                // update lower_bound if mid contains 0
                if (arr[mid] == 0)
                    lb = mid+1;
           
                // If mid contains 1
                else if (arr[mid] == 1)
                {
                    // Check if it is the left most 1
                    // Return mid, if yes
                    if (arr[mid-1]==0)
                        return mid;
           
                    // Else update upper_bound
                    ub = mid-1;
                }
            }
            return -1;
        }
           
          
        // Driver method
        public static void main(String args[]) 
        {
            int arr[] = {0, 0, 0, 0, 1, 1};
           
            int point = findTransitionPoint(arr, arr.length);
           
            System.out.println(point >= 0 ? "Transition point is " + point
                                           : "There is no transition point");
        }
    }

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # python implementation to find the
    # transition point
      
    # Function to find the transition
    # point
    def findTransitionPoint(arr, n):
        # Initialise lower and upper
        # bounnds
        lb = 0
        ub = n - 1
      
        # Perform Binary search
        while (lb <= ub):
            # Find mid
            mid = (int)((lb + ub) / 2)
      
            # update lower_bound if
            # mid contains 0
            if (arr[mid] == 0):
                lb = mid + 1
      
            # If mid contains 1
            elif (arr[mid] == 1):
                  
                # Check if it is the 
                # left most 1 Return
                # mid, if yes
                if (arr[mid - 1] == 0):
                    return mid
      
                # Else update 
                # upper_bound
                ub = mid-1
          
        return -1
      
    # Driver code
    arr = [0, 0, 0, 0, 1, 1]
    n = len(arr)
    point = findTransitionPoint(arr, n);
    if(point >= 0):
        print("Transition point is ", point)
    else:
        print("There is no transition point")
      
    # This code is contributed by Sam007

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# implementation to find the transition point
    using System;
              
    class GFG 
    {
        // Method to find the transition point
        static int findTransitionPoint(int []arr, int n)
        {
            // Initialise lower and upper bounnds
            int lb = 0, ub = n-1;
          
            // Perform Binary search
            while (lb <= ub)
            {
                // Find mid
                int mid = (lb+ub)/2;
          
                // update lower_bound if mid contains 0
                if (arr[mid] == 0)
                    lb = mid+1;
          
                // If mid contains 1
                else if (arr[mid] == 1)
                {
                    // Check if it is the left most 1
                    // Return mid, if yes
                    if (arr[mid-1]==0)
                        return mid;
          
                    // Else update upper_bound
                    ub = mid-1;
                }
            }
            return -1;
        }
          
          
        // Driver method
        public static void Main() 
        {
            int []arr = {0, 0, 0, 0, 1, 1};
            int point = findTransitionPoint(arr, arr.Length);
          
            Console.Write(point >= 0 ? "Transition point is " +
                       point : "There is no transition point");
        }
    }
      
    // This code is contributed by Sam007

    chevron_right

    
    

    PHP

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    // PHP implementation to find
    // the transition point
      
    // Function to find the 
    // transition point
    function findTransitionPoint($arr, $n)
    {
          
        // Initialise lower and
        // upper bounnds
        $lb = 0; $ub = $n-1;
      
        // Perform Binary search
        while ($lb <= $ub)
        {
              
            // Find mid
            $mid = floor(($lb + $ub) / 2);
      
            // update lower_bound
            // if mid contains 0
            if ($arr[$mid] == 0)
                $lb = $mid + 1;
      
            // If mid contains 1
            else if ($arr[$mid] == 1)
            {
                  
                // Check if it is the 
                // left most 1
                // Return mid, if yes
                if ($arr[$mid - 1] == 0)
                    return $mid;
      
                // Else update upper_bound
                $ub = $mid - 1;
            }
        }
        return -1;
    }
      
        // Driver Code
        $arr = array(0, 0, 0, 0, 1, 1);
        $n = sizeof($arr);
        $point = findTransitionPoint($arr, $n);
      
        if($point >= 0) 
            echo "Transition point is " , $point;
        else
            echo"There is no transition point";
        return 0;
      
    // This code is contributed by nitin mittal.
    ?>

    chevron_right

    
    

  • Output:
    Transition point is 4
  • Complexity Analysis:
    • Time Complexity: O(log n).
      The time complexity for binary search is O(log n).
    • Space Complexity: O(1).
      No extra space is required, so the space complexity is constant.

This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up