Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Find any permutation of Binary String of given size not present in Array
Next article icon

Position of leftmost set bit in given binary string where all 1s appear at end

Last Updated : 15 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// C++ Program to find Position // Of leftmost set bit #include <iostream> using namespace std;  // Function to find // A bit is set or not bool isSetBit(string& s, int i) {     return s[i] == '1'; }  // Function to find // First set bit int firstSetBit(string& s, int n) {     long l = 0, r = n, m, ans = -1;      // Applying binary search     while (l <= r) {          m = (l + r) / 2;         if (isSetBit(s, m)) {              // store the current             // state of m in ans             ans = m;             r = m - 1;         }         else {             l = m + 1;         }     }      // Returning the position     // of first set bit     return ans; }  // Driver code int main() {      string s = "111";     int n = s.length();     cout << firstSetBit(s, n);      return 0; } 
Java
// Java program for the above approach class GFG {    // Function to find   // A bit is set or not   static boolean isSetBit(String s, int i)   {     return s.charAt(i) == '1' ? true : false;   }    // Function to find   // First set bit   static int firstSetBit(String s, int n)   {     int l = 0, r = n, m, ans = -1;      // Applying binary search     while (l <= r) {        m = (l + r) / 2;       if (isSetBit(s, m)) {          // store the current         // state of m in ans         ans = m;         r = m - 1;       }       else {         l = m + 1;       }     }      // Returning the position     // of first set bit     return ans;   }    // Driver Code   public static void main(String args[])   {     String s = "111";     int n = s.length();     System.out.print(firstSetBit(s, n));   } }  // This code is contributed by gfgking 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG {    // Function to find   // A bit is set or not   static bool isSetBit(string s, int i)   {     return s[i] == '1';   }    // Function to find   // First set bit   static int firstSetBit(string s, int n)   {     int l = 0, r = n, m, ans = -1;      // Applying binary search     while (l <= r) {        m = (l + r) / 2;       if (isSetBit(s, m)) {          // store the current         // state of m in ans         ans = m;         r = m - 1;       }       else {         l = m + 1;       }     }      // Returning the position     // of first set bit     return ans;   }    // Driver Code   public static void Main()   {     string s = "111";     int n = s.Length;     Console.Write(firstSetBit(s, n));   } }  // This code is contributed by sanjoy_62. 
JavaScript
  <script>         // JavaScript code for the above approach          // Function to find         // A bit is set or not         function isSetBit(s, i) {             return s[i] == '1';         }          // Function to find         // First set bit         function firstSetBit(s, n) {             let l = 0, r = n, m, ans = -1;              // Applying binary search             while (l <= r) {                  m = Math.floor((l + r) / 2);                 if (isSetBit(s, m)) {                      // store the current                     // state of m in ans                     ans = m;                     r = m - 1;                 }                 else {                     l = m + 1;                 }             }              // Returning the position             // of first set bit             return ans;         }          // Driver code         let s = "111";         let n = s.length;         document.write(firstSetBit(s, n));         // This code is contributed by Potta Lokesh     </script> 
Python
# Python Program to find Position # Of leftmost set bit  # Function to find # A bit is set or not def isSetBit(s, i):          return s[i] == '1'  # Function to find # First set bit def firstSetBit(s, n):      l = 0     r = n     m = 0     ans = -1      # Applying binary search     while (l <= r):          m = (l + r) // 2         if (isSetBit(s, m)):              # store the current             # state of m in ans             ans = m             r = m - 1          else:             l = m + 1      # Returning the position     # of first set bit     return ans  # Driver code  s = "111" n = len(s) print(firstSetBit(s, n))  # This code is contributed by Samim Hossain Mondal. 

 
 


Output: 
0

 


 

Time Complexity: O(LogN)
Auxiliary Space: o(1)


 


Next Article
Find any permutation of Binary String of given size not present in Array

C

code_r
Improve
Article Tags :
  • Strings
  • Bit Magic
  • Geeks Premier League
  • DSA
  • Geeks-Premier-League-2022
  • binary-string
Practice Tags :
  • Bit Magic
  • Strings

Similar Reads

  • Maximize subarrays of 0s of length X in given Binary String after flipping at most one '1'
    Given a binary string str of length N and a positive integer X, the task is to maximize the count of X length subarrays consisting of only 0's by flipping at most one 1. One bit will be considered in only one subarray.Example: Input: str = "0010001", X = 2Output: 3Explanation: Flip str[2] from 1 to
    10 min read
  • Find any permutation of Binary String of given size not present in Array
    Given an array arr[] of N distinct binary strings each having N characters, the task is to find any binary string having N characters such that it doesn't occur in the given array arr[]. Example: Input: arr[] = {"10", "01"}Output: 00Explanation: String "00" does not appear in array arr[]. Another va
    5 min read
  • Find k-th bit in a binary string created by repeated invert and append operations
    You are given an initial string s starting with "0". The string keeps duplicating as follows. Invert of it is appended to it.Examples: Input : k = 2 Output : 1 Initially s = "0". First Iteration : s = s + s' = "01" Second Iteration : s = s + s' = "0110" The digit at index 2 of s is 1. Input : k = 12
    8 min read
  • Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 min read
  • Find i’th index character in a binary string obtained after n iterations | Set 2
    Given a decimal number m, convert it into a binary string and apply n iterations, in each iteration 0 becomes “01” and 1 becomes “10”. Find ith(based indexing) index character in the string after nth iteration.Examples: Input: m = 5 i = 5 n = 3Output: 1ExplanationIn the first case m = 5, i = 5, n =
    13 min read
  • Count of setbits in bitwise OR of all K length substrings of given Binary String
    Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
    8 min read
  • Sum of the shortest distance between all 0s to 1 in given binary string
    Given a binary string S, the task is to find the sum of the shortest distance between all 0s to 1 in the given string S. Examples: Input: S = "100100" Output: 5Explanation: For the '0' at index 1 the nearest '1' is at index 0 at a distance 1.For the '0' at index 2 the nearest '1' is at index 3 at a
    11 min read
  • Mth bit in Nth binary string from a sequence generated by the given operations
    Given two integers N and M, generate a sequence of N binary strings by the following steps: S0 = "0"S1 = "1"Generate remaining strings by the equation Si = reverse(Si - 2) + reverse(Si - 1) The task is to find the Mth set bit in the Nth string. Examples: Input: N = 4, M = 3Output: 0Explanation:S0 ="
    7 min read
  • Length of longest consecutive ones by at most one swap in a Binary String
    Given a Binary String of length [Tex]N [/Tex]. It is allowed to do at most one swap between any 0 and 1. The task is to find the length of the longest consecutive 1's that can be achieved. Examples: Input : str = "111011101" Output : 7 We can swap 0 at 4th with 1 at 10th position Input : str = "1110
    9 min read
  • Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
    Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0;
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences