703159. First 1 in a Sorted Binary Array

Basic

First 1 in a Sorted Binary Array

Summary

In this problem, we are given a sorted binary array (i.e., an array containing only 0s and 1s) and asked to find the index of the first 1 in the array. This problem involves searching for an element in a sorted array, which is a basic algorithmic concept.

Detailed Explanation

To solve this problem, we can use binary search, which is a popular algorithm for finding an element in a sorted array. Binary search works by repeatedly dividing the search space in half and eliminating one half until the target element is found. Since our array is sorted, we know that all 1s will be to the right of all 0s.

Here's the step-by-step breakdown of the solution:

  1. Initialize two pointers, low and high, to the start and end of the array, respectively.
  2. Calculate the midpoint of the array using (low + high) / 2.
  3. Check if the element at the midpoint is a 1. If it is, update high to the midpoint to narrow down the search space.
  4. Repeat steps 2-3 until high points to the first 1 in the array or low and high converge.
  5. Return the index of the first 1 found.

Time complexity: O(log n), where n is the length of the array. This is because we are dividing the search space in half at each step, effectively reducing the number of comparisons needed to find the target element.

Space complexity: O(1), since we only need a few extra variables to perform the binary search.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
public int findFirstOne(int[] arr) {
    int low = 0;
    int high = arr.length - 1;
    
    while (low <= high) {
        int mid = low + (high - low) / 2;
        
        if (arr[mid] == 1) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    
    return low;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.