Find the transition point in a binary array - GeeksforGeeks

20 Apr, 2022
Given a sorted array containing only numbers 0 and 1, the task is to find the transition point efficiently. The transition point is the point where “0” ends and “1” begins.
Examples : 
Input: 0 0 0 1 1
Output: 3
Explanation: Index of first 1 is 3

Input: 0 0 0 0 1 1 1 1
Output: 4
Explanation: Index of first 1 is 4
Naive Approach: Traverse the array and print the index of the first 1.  
Traverse the array from the start to the end of the array.If the current element is 1, print the index and terminate the program.
Traverse the array from the start to the end of the array.
If the current element is 1, print the index and terminate the program.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find// the transition point#include<iostream>using namespace std; // Function to find the transition pointint 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 codeint 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;}
// Java implementation to find the transition pointimport java.util.*; class GFG{ // Function to find the transition pointstatic 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 codepublic 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
# Python3 implementation to find the transition point # Function to find the transition pointdef 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 codearr = [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
// C# implementation to find the transition pointusing System; class GFG{ // Function to find the transition pointstatic 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
<script>     // Javascript implementation to    // find the transition point         // Function to find the transition point    function findTransitionPoint(arr, n)    {        // perform a linear search and        // return the index of        // first 1        for(let i = 0; i < n ; i++)            if(arr[i] == 1)                return i;         // if no element is 1        return -1;    }         let arr = [0, 0, 0, 0, 1, 1];    let point = findTransitionPoint(arr, arr.length);     document.write(point >= 0 ? "Transition point is " +                  point : "There is no transition point");     </script>
Transition point is 4
Complexity Analysis: 
Time Complexity: O(n), Only one traversal is needed, so the time complexity is O(n)
Auxiliary Space: O(1), No extra space is required.
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.
Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer.Iterate the steps below till l <= r, the lower-bound is less than the upper-bound.Check if the element at middle index mid = (l+r)/2, is one or not.If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid.If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1.
Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer.
Iterate the steps below till l <= r, the lower-bound is less than the upper-bound.
Check if the element at middle index mid = (l+r)/2, is one or not.
If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid.
If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the transition point#include<iostream>using namespace std; // Function to find the transition pointint findTransitionPoint(int arr[], int n){    // Initialise lower and upper bounds    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 (mid == 0                    || (mid > 0 &&                       arr[mid - 1] == 0))                return mid;             // Else update upper_bound            ub = mid-1;        }    }    return -1;} // Driver Codeint 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;}
// 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 bounds        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 (mid == 0                    || (mid > 0 &&                       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");    }}
# python implementation to find the# transition point # Function to find the transition# pointdef findTransitionPoint(arr, n):    # Initialise lower and upper    # bounds    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        else if (arr[mid] == 1):                         # Check if it is the            # left most 1 Return            # mid, if yes            if (mid == 0 \                or (mid > 0 and\                arr[mid - 1] == 0)):                return mid             # Else update            # upper_bound            ub = mid-1         return -1 # Driver codearr = [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
// C# implementation to find the transition pointusing System;         class GFG{    // Method to find the transition point    static int findTransitionPoint(int []arr, int n)    {        // Initialise lower and upper bounds        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 (mid == 0                    || (mid > 0 &&                       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
<?php// PHP implementation to find// the transition point // Function to find the// transition pointfunction findTransitionPoint($arr, $n){         // Initialise lower and    // upper bounds    $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 ($mid == 0 or                ($mid > 0 and                 $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.?>
<script>    // Javascript implementation to find the transition point         // Method to find the transition point    function findTransitionPoint(arr, n)    {        // Initialise lower and upper bounds        let lb = 0, ub = n-1;              // Perform Binary search        while (lb <= ub)        {            // Find mid            let mid = parseInt((lb+ub)/2, 10);                  // 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 (mid == 0                    || (mid > 0 &&                       arr[mid - 1] == 0))                    return mid;                      // Else update upper_bound                ub = mid-1;            }        }        return -1;    }         let arr = [0, 0, 0, 0, 1, 1];    let point = findTransitionPoint(arr, arr.length);     document.write(point >= 0 ? "Transition point is " +                  point : "There is no transition point");       </script>
Transition point is 4
Complexity Analysis: 
Time Complexity: O(log n). The time complexity for binary search is O(log n).
Auxiliary Space: O(1). No extra space is required.
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
Sam007
nitin mittal
andrew1234
SHUBHAMSINGH10
shivanisinghss2110
yugi2000
divyeshrabadiya07
decode2207
surinderdawra388
simmytarika5
sweetyty
Amazon
Binary Search
binary-string
Arrays
Amazon
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)