Smallest index such that there are no 0 or 1 to its right
Given a binary array of N numbers. The task is to find the smallest index such that there are either no 1’s or 0’s to the right of the index.
Note: The array will have at least one 0 and one 1.
Examples:
Input: a[] = {1, 1, 1, 0, 0, 1, 0, 1, 1}
Output: 6
At 6th index, there are no 0’s to the right of the index.
Input: a[] = {0, 1, 0, 0, 0}
Output: 1
Approach: Store the rightmost occurring index of both 1 and 0 and return the minimum of both.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int smallestIndex( int a[], int n)
{
int right1 = 0, right0 = 0;
for ( int i = 0; i < n; i++) {
if (a[i] == 1)
right1 = i;
else
right0 = i;
}
return min(right1, right0);
}
int main()
{
int a[] = { 1, 1, 1, 0, 0, 1, 0, 1, 1 };
int n = sizeof (a) / sizeof (a[0]);
cout << smallestIndex(a, n);
return 0;
}
|
Java
class GFG
{
static int smallestIndex( int []a, int n)
{
int right1 = 0 , right0 = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (a[i] == 1 )
right1 = i;
else
right0 = i;
}
return Math.min(right1, right0);
}
public static void main(String[] args)
{
int []a = { 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 };
int n = a.length;
System.out.println(smallestIndex(a, n));
}
}
|
Python3
def smallestIndex(a, n):
right1 = 0
right0 = 0
for i in range (n):
if (a[i] = = 1 ):
right1 = i
else :
right0 = i
return min (right1, right0)
if __name__ = = '__main__' :
a = [ 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ]
n = len (a)
print (smallestIndex(a, n))
|
C#
using System;
class GFG
{
static int smallestIndex( int []a, int n)
{
int right1 = 0, right0 = 0;
for ( int i = 0; i < n; i++)
{
if (a[i] == 1)
right1 = i;
else
right0 = i;
}
return Math.Min(right1, right0);
}
public static void Main()
{
int []a = { 1, 1, 1, 0, 0, 1, 0, 1, 1 };
int n = a.Length;
Console.Write(smallestIndex(a, n));
}
}
|
PHP
<?php
function smallestIndex( $a , $n )
{
$right1 = 0; $right0 = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $a [ $i ] == 1)
$right1 = $i ;
else
$right0 = $i ;
}
return min( $right1 , $right0 );
}
$a = array (1, 1, 1, 0, 0, 1, 0, 1, 1);
$n = sizeof( $a );
echo smallestIndex( $a , $n );
?>
|
Javascript
<script>
function smallestIndex(a, n)
{
let right1 = 0, right0 = 0;
let i;
for (i = 0; i < n; i++)
{
if (a[i] == 1)
right1 = i;
else
right0 = i;
}
return Math.min(right1, right0);
}
var a = [ 1, 1, 1, 0, 0, 1, 0, 1, 1 ];
let n = a.length;
document.write(smallestIndex(a, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
09 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...