VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-index-first-1-sorted-array-0s-1s/

⇱ Find the index of first 1 in a sorted array of 0's and 1's - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the index of first 1 in a sorted array of 0's and 1's

Last Updated : 21 Apr, 2026

Given a sorted array consisting 0's and 1's. The problem is to find the index of first '1' in the sorted array. It could be possible that the array consists of only 0's or only 1's. If 1's are not present in the array then print "-1".

Examples : 

Input : arr[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1}
Output : 6
Explanation: The index of first 1 in the array is 6.

Input : arr[] = {0, 0, 0, 0}
Output : -1
Explanation: 1's are not present in the array.

[Naive Approach] Using Linear Search - O(n) Time O(1) Space

Traverse the array from left to right and return the index of first '1'. If 1's are not present in the array, then print "-1"


Output
6

[Efficient Approach] Using Binary Search - O(Log n)Time O(1) Space

Use the technique of binary search on the sorted array, so as to find the index of first '1'.

Algorithm:

  • Initialize low = 0 and high = n - 1.
  • Find mid = (low + high) / 2 and check the value at mid.
  • If arr[mid] == 1 and it is the first occurrence, return mid.
  • If arr[mid] == 1, move left (high = mid - 1); else move right (low = mid + 1).
  • Repeat until found; if not, return -1.

Output
6
Comment