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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Next article icon

Minimize removal of substring of 0s to remove all occurrences of 0s from a circular Binary String

Last Updated : 21 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given circular binary string S of size N, the task is to count the minimum number of consecutive 0s required to be removed such that the string contains only 1s.

A circular string is a string whose first and last characters are considered to be adjacent to each other.

Examples:

Input: S = "11010001"
Output: 2
Explanation:
Remove the substring {S[2]}. Now, the string modifies to "1110001".
Remove the substring {S[3], ..., S[5]} of consecutive 0s. Now, the string modifies to "1111".
Therefore, the minimum count of removals required is 2.

Input: S = "00110000"
Output: 1

Approach: The idea to solve the given problem is to traverse the given string and count the number of substrings having the same number of 0s, say C. Now if the first and the last characters of the string are '0', then print the value of (C - 1) as the minimum number of removals required. Otherwise, print the value of C as the result.

Note: If the given string contains all 0s, then the minimum number of removals required is 1. Consider this case separately.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to count minimum number of // removal of consecutive 0s required to // make binary string consists only of 1s int minRemovals(string str, int N) {     // Stores the count of removals     int ans = 0;      bool X = false;      // Traverse the string S     for (int i = 0; i < N; i++) {          // If the current character is '0'         if (str[i] == '0') {              ans++;              // Traverse until consecutive             // characters are only '0's             while (str[i] == '0') {                 i++;             }         }          else {             X = true;         }     }      // If the binary string only     // contains 1s, then return 1     if (!X)         return 1;      // If the first and the last     // characters are 0     if (str[0] == '0'         and str[N - 1] == '0') {         ans--;     }      // Return the resultant count     return ans; }  // Driver Code int main() {     string S = "11010001";     int N = S.size();     cout << minRemovals(S, N);      return 0; } 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  class GFG{  // Function to count minimum number of // removal of consecutive 0s required to // make binary string consists only of 1s static int minRemovals(String str, int N) {          // Stores the count of removals     int ans = 0;      boolean X = false;      // Traverse the string S     for(int i = 0; i < N; i++)     {                  // If the current character is '0'         if (str.charAt(i) == '0')          {             ans++;              // Traverse until consecutive             // characters are only '0's             while (i < N && str.charAt(i) == '0')             {                 i++;             }         }          else          {             X = true;         }     }      // If the binary string only     // contains 1s, then return 1     if (!X)         return 1;      // If the first and the last     // characters are 0     if (str.charAt(0) == '0' &&          str.charAt(N - 1) == '0')     {         ans--;     }      // Return the resultant count     return ans; }  // Driver Code public static void main(String[] args) {     String S = "11010001";     int N = S.length();      System.out.println(minRemovals(S, N)); } }  // This code is contributed by Kingash 
Python3
# Python3 program for the above approach  # Function to count minimum number of # removal of consecutive 0s required to # make binary string consists only of 1s def minRemovals(str, N):          # Stores the count of removals     ans = 0     X = False          # Traverse the string S     i = 0          while i < N:                  # If the current character is '0'         if (str[i] == '0'):             ans += 1                          # Traverse until consecutive             # characters are only '0's             while (str[i] == '0'):                 i += 1         else:             X = True                      i += 1              # If the binary string only     # contains 1s, then return 1     if (not X):         return 1              # If the first and the last     # characters are 0     if (str[0] == '0' and str[N - 1] == '0'):         ans -= 1              # Return the resultant count     return ans      # Driver Code S = "11010001" N = len(S)  print(minRemovals(S, N))  # This code is contributed by rohan07 
C#
// C# program for the above approach using System; class GFG {    // Function to count minimum number of   // removal of consecutive 0s required to   // make binary string consists only of 1s   static int minRemovals(string str, int N)   {          // Stores the count of removals     int ans = 0;      bool X = false;      // Traverse the string S     for (int i = 0; i < N; i++) {        // If the current character is '0'       if (str[i] == '0') {          ans++;          // Traverse until consecutive         // characters are only '0's         while (str[i] == '0') {           i++;         }       }        else {         X = true;       }     }      // If the binary string only     // contains 1s, then return 1     if (!X)       return 1;      // If the first and the last     // characters are 0     if (str[0] == '0' && str[N - 1] == '0') {       ans--;     }      // Return the resultant count     return ans;   }    // Driver Code   public static void Main()   {     string S = "11010001";     int N = S.Length;     Console.Write(minRemovals(S, N));   } }  // This code is contributed by subham348. 
JavaScript
<script> // js program for the above approach  // Function to count minimum number of // removal of consecutive 0s required to // make binary consists only of 1s function minRemovals(str, N) {      // Stores the count of removals   let ans = 0;    let X = false;    // Traverse the S   for (i = 0; i < N; i++) {      // If the current character is '0'     if (str[i] == '0') {        ans++;        // Traverse until consecutive       // characters are only '0's       while (str[i] == '0') {         i++;       }     }      else {       X = true;     }   }    // If the binary only   // contains 1s, then return 1   if (!X)     return 1;    // If the first and the last   // characters are 0   if (str[0] == '0' && str[N - 1] == '0') {     ans--;   }    // Return the resultant count   return ans; }    // Driver Code  let S = "11010001"; let N = S.length; document.write(minRemovals(S, N));  // This code is contributed by mohit kumar 29. </script> 

Output: 
2

 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
author
subhammahato348
Improve
Article Tags :
  • Strings
  • Python
  • DSA
  • binary-string
  • substring
Practice Tags :
  • python
  • Strings

Similar Reads

  • Minimize length of a string by removing occurrences of another string from it as a substring
    Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S
    8 min read
  • Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
    Given a binary string S, the task is to partition the sequence into K non-empty subsets such that the sum of products of occurrences of 0 and 1 for all subsets is minimum. If impossible print -1.Examples: Input: S = "0001", K = 2 Output: 0 Explanation We have 3 choices {0, 001}, {00, 01}, {000, 1} T
    8 min read
  • Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
    Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str
    11 min read
  • Smallest string obtained by removing all occurrences of 01 and 11 from Binary String
    Given a binary string S , the task is to find the smallest string possible by removing all occurrences of substrings "01" and "11". After removal of any substring, concatenate the remaining parts of the string. Examples: Input: S = "0010110"Output:Length = 1 String = 0Explanation: String can be tran
    7 min read
  • Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2
    Given a binary string S of length N, the task is to find the smallest string possible by removing all occurrences of substrings “01” and “11”. After removal of any substring, concatenate the remaining parts of the string. Examples: Input: S = "1010"Output: 2Explanation: Removal of substring "01" mod
    5 min read
  • Minimum steps to remove substring 010 from a binary string
    Given a binary string, the task is to count the minimum steps to remove substring "010" from this binary string. Examples: Input: binary_string = "0101010" Output: 2 Switching 0 to 1 at index 2 and index 4 will remove the substring 010. Hence the number of steps needed is 2. Input: binary_string = "
    4 min read
  • Most frequent character in a string after replacing all occurrences of X in a Binary String
    Given a string S of length N consisting of 1, 0, and X, the task is to print the character ('1' or '0') with the maximum frequency after replacing every occurrence of X as per the following conditions: If the character present adjacently to the left of X is 1, replace X with 1.If the character prese
    15+ min read
  • Check if substring "10" occurs in the given binary string in all possible replacements of '?' with 1 or 0
    Given a string S consisting of only '0', '1' and '?', the task is to check if there exists a substring "10" in every possible replacement of the character '?' with either 1 or 0. Examples: Input: S = "1?0"Output: YesExplanation:Following are all the possible replacements of '?': Replacing the '?' wi
    7 min read
  • Minimum count of 0s to be removed from given Binary string to make all 1s occurs consecutively
    Given a binary string S of size N, the task is to find the minimum numbers of 0s that must be removed from the string S such that all the 1s occurs consecutively. Examples: Input: S = "010001011" Output: 4 Explanation: Removing the characters { S[2], S[3], S[4], S[6] } from the string S modifies the
    7 min read
  • Minimize deletions in a Binary String to remove all subsequences of the form "0101"
    Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string. Examples: Input: S = "0101101"Output: 2Explanation: Removing S[1] and S[5] modifies the string to 00111.
    6 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