Position of leftmost set bit in given binary string where all 1s appear at end
Last Updated :
15 Feb, 2022
Given a binary string S of length N, such that all 1s appear on the right. The task is to return the index of the first set bit found from the left side else return -1.
Examples:
Input: s = 00011, N = 5
Output: 3
Explanation: The first set bit from the left side is at index 3.
Input: s = 0000, N = 4
Output: -1
Approach: This problem can be solved using Binary Search.
- Apply Binary search in the range [1, N] to find the first set bit as follows:
- Update mid as (l+r)/2
- If s[mid] is set bit, update ans as mid and r as mid-1
- else update l as mid + 1
- Return the last stored value in ans.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool isSetBit(string& s, int i)
{
return s[i] == '1' ;
}
int firstSetBit(string& s, int n)
{
long l = 0, r = n, m, ans = -1;
while (l <= r) {
m = (l + r) / 2;
if (isSetBit(s, m)) {
ans = m;
r = m - 1;
}
else {
l = m + 1;
}
}
return ans;
}
int main()
{
string s = "111" ;
int n = s.length();
cout << firstSetBit(s, n);
return 0;
}
|
Java
class GFG
{
static boolean isSetBit(String s, int i)
{
return s.charAt(i) == '1' ? true : false ;
}
static int firstSetBit(String s, int n)
{
int l = 0 , r = n, m, ans = - 1 ;
while (l <= r) {
m = (l + r) / 2 ;
if (isSetBit(s, m)) {
ans = m;
r = m - 1 ;
}
else {
l = m + 1 ;
}
}
return ans;
}
public static void main(String args[])
{
String s = "111" ;
int n = s.length();
System.out.print(firstSetBit(s, n));
}
}
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool isSetBit( string s, int i)
{
return s[i] == '1' ;
}
static int firstSetBit( string s, int n)
{
int l = 0, r = n, m, ans = -1;
while (l <= r) {
m = (l + r) / 2;
if (isSetBit(s, m)) {
ans = m;
r = m - 1;
}
else {
l = m + 1;
}
}
return ans;
}
public static void Main()
{
string s = "111" ;
int n = s.Length;
Console.Write(firstSetBit(s, n));
}
}
|
Javascript
<script>
function isSetBit(s, i) {
return s[i] == '1' ;
}
function firstSetBit(s, n) {
let l = 0, r = n, m, ans = -1;
while (l <= r) {
m = Math.floor((l + r) / 2);
if (isSetBit(s, m)) {
ans = m;
r = m - 1;
}
else {
l = m + 1;
}
}
return ans;
}
let s = "111" ;
let n = s.length;
document.write(firstSetBit(s, n));
</script>
|
Python
def isSetBit(s, i):
return s[i] = = '1'
def firstSetBit(s, n):
l = 0
r = n
m = 0
ans = - 1
while (l < = r):
m = (l + r) / / 2
if (isSetBit(s, m)):
ans = m
r = m - 1
else :
l = m + 1
return ans
s = "111"
n = len (s)
print (firstSetBit(s, n))
|
Time Complexity: O(LogN)
Auxiliary Space: o(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...