Find the index of first 1 in an infinite sorted array of 0s and 1s
Last Updated :
18 Jul, 2022
Given an infinite sorted array consisting 0s and 1s. The problem is to find the index of first ‘1’ in that array. As the array is infinite, therefore it is guaranteed that number '1' will be present in the array.
Examples:
Input : arr[] = {0, 0, 1, 1, 1, 1}
Output : 2
Input : arr[] = {1, 1, 1, 1,, 1, 1}
Output : 0
Approach: The problem is closely related to the problem of finding position of an element in a sorted array of infinite numbers. As the array is infinite, therefore we do not know the upper and lower bounds between which we have to find the occurrence of first '1'.
Below is an algorithm to find the upper and lower bounds.
Algorithm:
posOfFirstOne(arr)
Declare l = 0, h = 1
while arr[h] == 0
l = h
h = 2*h;
return indexOfFirstOne(arr, l, h)
}
Here h and l are the required upper and lower bounds. indexOfFirstOne(arr, l, h) is used to find the index of occurrence of first '1' between these two bounds. Refer this post.
C++
// C++ implementation to find the index of first 1
// in an infinite sorted array of 0's and 1's
#include <bits/stdc++.h>
using namespace std;
// function to find the index of first '1'
// binary search technique is applied
int indexOfFirstOne(int arr[], int low, int high)
{
int mid;
while (low <= high) {
mid = (low + high) / 2;
// if true, then 'mid' is the index of first '1'
if (arr[mid] == 1 &&
(mid == 0 || arr[mid - 1] == 0))
break;
// first '1' lies to the left of 'mid'
else if (arr[mid] == 1)
high = mid - 1;
// first '1' lies to the right of 'mid'
else
low = mid + 1;
}
// required index
return mid;
}
// function to find the index of first 1 in
// an infinite sorted array of 0's and 1's
int posOfFirstOne(int arr[])
{
// find the upper and lower bounds between
// which the first '1' would be present
int l = 0, h = 1;
// as the array is being considered infinite
// therefore 'h' index will always exist in
// the array
while (arr[h] == 0) {
// lower bound
l = h;
// upper bound
h = 2 * h;
}
// required index of first '1'
return indexOfFirstOne(arr, l, h);
}
// Driver program to test above
int main()
{
int arr[] = { 0, 0, 1, 1, 1, 1 };
cout << "Index = "
<< posOfFirstOne(arr);
return 0;
}
Java
// JAVA Code For Find the index of first 1
// in an infinite sorted array of 0s and 1s
import java.util.*;
class GFG {
// function to find the index of first '1'
// binary search technique is applied
public static int indexOfFirstOne(int arr[],
int low, int high)
{
int mid=0;
while (low <= high) {
mid = (low + high) / 2;
// if true, then 'mid' is the index of
// first '1'
if (arr[mid] == 1 &&
(mid == 0 || arr[mid - 1] == 0))
break;
// first '1' lies to the left of 'mid'
else if (arr[mid] == 1)
high = mid - 1;
// first '1' lies to the right of 'mid'
else
low = mid + 1;
}
// required index
return mid;
}
// function to find the index of first 1 in
// an infinite sorted array of 0's and 1's
public static int posOfFirstOne(int arr[])
{
// find the upper and lower bounds
// between which the first '1' would
// be present
int l = 0, h = 1;
// as the array is being considered
// infinite therefore 'h' index will
// always exist in the array
while (arr[h] == 0) {
// lower bound
l = h;
// upper bound
h = 2 * h;
}
// required index of first '1'
return indexOfFirstOne(arr, l, h);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = { 0, 0, 1, 1, 1, 1 };
System.out.println("Index = " +
posOfFirstOne(arr));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python 3 implementation to find the
# index of first 1 in an infinite
# sorted array of 0's and 1's
# function to find the index of first
# '1' binary search technique is applied
def indexOfFirstOne(arr, low, high) :
while (low <= high) :
mid = (low + high) // 2
# if true, then 'mid' is the index
# of first '1'
if (arr[mid] == 1 and (mid == 0 or
arr[mid - 1] == 0)) :
break
# first '1' lies to the left of 'mid'
elif (arr[mid] == 1) :
high = mid - 1
# first '1' lies to the right of 'mid'
else :
low = mid + 1
# required index
return mid
# function to find the index of first
# 1 in an infinite sorted array of 0's
# and 1's
def posOfFirstOne(arr) :
# find the upper and lower bounds between
# which the first '1' would be present
l = 0
h = 1
# as the array is being considered infinite
# therefore 'h' index will always exist in
# the array
while (arr[h] == 0) :
# lower bound
l = h
# upper bound
h = 2 * h
# required index of first '1'
return indexOfFirstOne(arr, l, h)
# Driver program
arr = [ 0, 0, 1, 1, 1, 1 ]
print( "Index = ", posOfFirstOne(arr))
# This code is contributed by Nikita Tiwari.
C#
// C# Code For Find the index of first 1
// in an infinite sorted array of 0's and 1's
using System;
class GFG {
// function to find the index of first '1'
// binary search technique is applied
public static int indexOfFirstOne(int[] arr,
int low, int high)
{
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
// if true, then 'mid' is the index of
// first '1'
if (arr[mid] == 1 && (mid == 0 || arr[mid - 1] == 0))
break;
// first '1' lies to the left of 'mid'
else if (arr[mid] == 1)
high = mid - 1;
// first '1' lies to the right of 'mid'
else
low = mid + 1;
}
// required index
return mid;
}
// function to find the index of first 1 in
// an infinite sorted array of 0's and 1's
public static int posOfFirstOne(int[] arr)
{
// find the upper and lower bounds
// between which the first '1' would
// be present
int l = 0, h = 1;
// as the array is being considered
// infinite therefore 'h' index will
// always exist in the array
while (arr[h] == 0) {
// lower bound
l = h;
// upper bound
h = 2 * h;
}
// required index of first '1'
return indexOfFirstOne(arr, l, h);
}
/* Driver program to test above function */
public static void Main()
{
int[] arr = { 0, 0, 1, 1, 1, 1 };
Console.Write("Index = " + posOfFirstOne(arr));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to find
// the index of first 1 in an
// infinite sorted array of
// 0's and 1's
// function to find the index
// of first '1' binary search
// technique is applied
function indexOfFirstOne($arr, $low, $high)
{
$mid;
while ($low <= $high)
{
$mid = ($low + $high) / 2;
// if true, then 'mid' is
// the index of first '1'
if ($arr[$mid] == 1 and
($mid == 0 or $arr[$mid - 1] == 0))
break;
// first '1' lies to
// the left of 'mid'
else if ($arr[$mid] == 1)
$high = $mid - 1;
// first '1' lies to
// the right of 'mid'
else
$low = $mid + 1;
}
// required index
return ceil($mid);
}
// function to find the index of
// first 1 in an infinite sorted
// array of 0's and 1's
function posOfFirstOne($arr)
{
// find the upper and lower
// bounds between which the
// first '1' would be present
$l = 0; $h = 1;
// as the array is being considered
// infinite therefore 'h' index will
// always exist in the array
while ($arr[$h] == 0)
{
// lower bound
$l = $h;
// upper bound
$h = 2 * $h;
}
// required index
// of first '1'
return indexOfFirstOne($arr,
$l, $h);
}
// Driver Code
$arr = array(0, 0, 1, 1, 1, 1);
echo "Index = " ,
posOfFirstOne($arr);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript implementation to find the index of first 1
// in an infinite sorted array of 0's and 1's
// function to find the index of first '1'
// binary search technique is applied
function indexOfFirstOne(arr, low, high)
{
var mid;
while (low <= high) {
mid = parseInt((low + high) / 2);
// if true, then 'mid' is the index of first '1'
if (arr[mid] == 1 &&
(mid == 0 || arr[mid - 1] == 0))
break;
// first '1' lies to the left of 'mid'
else if (arr[mid] == 1)
high = mid - 1;
// first '1' lies to the right of 'mid'
else
low = mid + 1;
}
// required index
return mid;
}
// function to find the index of first 1 in
// an infinite sorted array of 0's and 1's
function posOfFirstOne(arr)
{
// find the upper and lower bounds between
// which the first '1' would be present
var l = 0, h = 1;
// as the array is being considered infinite
// therefore 'h' index will always exist in
// the array
while (arr[h] == 0) {
// lower bound
l = h;
// upper bound
h = 2 * h;
}
// required index of first '1'
return indexOfFirstOne(arr, l, h);
}
// Driver program to test above
var arr = [0, 0, 1, 1, 1, 1];
document.write( "Index = "
+ posOfFirstOne(arr));
// This code is contributed by rrrtnx.
</script>
Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read