Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find winner in the game of Binary Array
Next article icon

Find the transition point in a binary array

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a sorted array, arr[], containing only 0s and 1s, find the transition point, i.e., the first index where 1 was observed, and before that, only 0 was observed. If arr does not have any 1, return -1. If the array does not have any 0, return 0.

Examples : 

Input: 0 0 0 1 1
Output: 3
Explanation: Index 3 is the transition point where first 1 was observed.

Input: arr[] = [0, 0, 0, 0]
Output: -1
Explanation: Since, there is no “1”, the answer is -1.

Input: 0 0 0 0 1 1 1 1
Output: 4
Explanation: Index 4 is the transition point where first 1 was observed.

Input: arr[] = [1, 1, 1]
Output: 0
Explanation: There are no 0s in the array, so the transition point is 0.

[Naive Approach] Using a for Loop – O(n) Time and O(1) Space

The idea for this approach is to use a loop to traverse the array and print the index of the first 1.  

C++
#include<bits/stdc++.h> using namespace std;  // Function to find the transition point int transitionPoint(vector<int> arr) {     int n = arr.size();          //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; }  int main() {     vector<int> arr = {0, 0, 0, 0, 1, 1};      cout<<transitionPoint(arr);     return 0; } 
Java
import java.util.*;  class GfG {  // Function to find the transition point static int transitionPoint(int arr[]) {     int n = arr.length;          // 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; }  public static void main (String[] args)     {         int arr[] = {0, 0, 0, 0, 1, 1};                  System.out.print(transitionPoint(arr));     } } 
Python
def transitionPoint(arr):     n = len(arr)          # 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   arr = [0, 0, 0, 0, 1, 1]  print(transitionPoint(arr)) 
C#
using System;  class GfG  {  // Function to find the transition point static int transitionPoint(int []arr) {     int n = arr.Length;          // 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; }     public static void Main()      {         int []arr = {0, 0, 0, 0, 1, 1};         Console.Write(transitionPoint(arr));     } } 
JavaScript
function transitionPoint(arr)     {         let n =  arr.length;                  // 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];     console.log(transitionPoint(arr));      

Output
4

[Expected Approach] – Using Binary Search – O(log n) Time and O(1) Space

The idea is to use Binary Search, and find the smallest index of 1 in the array. As the array is sorted.

  • Use two variables (l, r) to point left end and right end of the array and 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 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.
C++
#include<bits/stdc++.h> using namespace std;  // Function to find the transition point int findTransitionPoint(vector<int> arr) {     int n = arr.size();          // 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; }  int main() {     vector<int> arr = {0, 0, 0, 0, 1, 1};     cout<<findTransitionPoint(arr);     return 0; } 
Java
class GfG {     // Method to find the transition point     static int transitionPoint(int arr[])     {         int n = arr.length;          // 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;     }      public static void main(String args[])     {         int arr[] = { 0, 0, 0, 0, 1, 1 };          System.out.println(transitionPoint(arr));     } } 
Python
def transitionPoint(arr):     n = len(arr)     # 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         elif(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  arr = [0, 0, 0, 0, 1, 1] print(transitionPoint(arr)); 
C#
using System;          class GfG  {     // Method to find the transition point     static int transitionPoint(int []arr)     {         int n = arr.Length;         // 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;     }          public static void Main()      {         int []arr = {0, 0, 0, 0, 1, 1};         Console.Write(transitionPoint(arr));     } } 
JavaScript
function transitionPoint(arr)     {         let n = arr.length         // 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];     console.log(transitionPoint(arr)); 

Output
4


Next Article
Find winner in the game of Binary Array

S

Sahil Chhabra
Improve
Article Tags :
  • Arrays
  • DSA
  • Amazon
  • Binary Search
  • binary-string
Practice Tags :
  • Amazon
  • Arrays
  • Binary Search

Similar Reads

  • Find winner in the game of Binary Array
    Given a binary array X[] of size N. Two players A and B are playing games having the following rules, then the task is to determine the winner if B starts first and both players play optimally. The rules are: In the first turn, a player selects any index i (1 ≤ i ≤ N) such that A[i] = 0.After their
    7 min read
  • Find the unvisited positions in Array traversal
    Given an array A[] of N positive integers where A[i] represent the units each i can traverse in one step. You can start from position 0 and need to reach destination d. The goal is to find the number of positions that are not visited when all of them have reached position d. Examples: Input: N = 3,
    6 min read
  • POTD Solutions | 4 Nov’ 23 | Find Transition Point
    View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search algorithm but will also help you build up
    4 min read
  • Range Update Queries to XOR with 1 in a Binary Array.
    Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [
    15+ min read
  • Minimum number of 1's to be replaced in a binary array
    Given a binary array arr[] of zero's and one's only. The task is to find the minimum number of one's to be changed to zero such if there exist any index [Tex]i [/Tex]in the array such that arr[i] = 0 then arr[i-1] and arr[i+1] both should not be equals to [Tex]1 [/Tex]at the same time. That is, for
    5 min read
  • Minimum time required to cover a Binary Array
    Given an integer N which represents the size of a boolean array that is initially filled with 0, and also given an array arr[] of size K consisting of (1-based) indices at which '1' are present in the boolean array. Now, at one unit of time the adjacent cells of the arr[i] in the boolean array becom
    8 min read
  • Count and Toggle Queries on a Binary Array
    Given a size n in which initially all elements are 0. The task is to perform multiple queries of following two types. The queries can appear in any order. 1. toggle(start, end) : Toggle (0 into 1 or 1 into 0) the values from range 'start' to 'end'. 2. count(start, end) : Count the number of 1's with
    15+ min read
  • Minimum length subarray of 1s in a Binary Array
    Given binary array. The task is to find the length of subarray with minimum number of 1s.Note: It is guaranteed that there is atleast one 1 present in the array.Examples : Input : arr[] = {1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} Output : 3 Minimum length subarray of 1s is {1, 1}.Input : arr[] = {0, 0, 1
    8 min read
  • Find Equal (or Middle) Point in a sorted array with duplicates
    Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn't exist, return -1.
    9 min read
  • Find the Target number in an Array
    Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities. Examples: Input: Array: {10, 20, 30, 40, 50} , Target: 30Output: "Target found at index 2" Input: A
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences