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 Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Smallest string which not a subsequence of the given string
Next article icon

Minimum number of alternate subsequences required to be removed to empty a Binary String

Last Updated : 22 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string S consisting of N characters, the task is to print the minimum number of operations required to remove all the characters from the given string S by removing a single character or removing any subsequence of alternate characters in each operation.

Examples:

Input: S = "010101"
Output: 1
Explanation:
Below are the operations performed:
Operation 1: Consider the subsequence S[0, 5] i.e., "010101" as it contains alternating characters. Therefore, removing this modifies the string to "".
Hence, the total number of operation required is 1.

Input: S = "00011"
Output: 3

Approach: The given problem can be solved by iterating over the string once and keep track of the maximum number of remaining 0s and 1s. Follow the steps below to solve the problem:

  • Initialize a variable, say ans to store the maximum number of 0s and 1s which are still left to be removed, a variable cnt0 to count the number of 0s, and a variable cnt1 to count the number of 1s.
  • Traverse the given string S from the beginning and perform the following steps:
    • If the current character is 0, then increment the value of cnt0 by 1 and decrement the value of cnt1 by 1 if it is greater than 0.
    • If the current character is 1, increment the value of cnt1 by 1 and decrement the value of cnt0 by 1 if it is greater than 0.
    • Update the value of ans to the maximum of ans, cnt1, and cnt0.
  • After completing the above steps, print the value of ans as the minimum number of operations required to remove all the characters.

Below is the implementation of the approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the minimum number // of operations to empty a binary string int minOpsToEmptyString(string s) {     // Stores the resultant number of     // operations     int ans = INT_MIN;      // Stores the number of 0s     int cn0 = 0;      // Stores the number of 1s     int cn1 = 0;      // Traverse the given string     for (int i = 0;          i < s.length(); i++) {          if (s[i] == '0') {              // To balance 0 with 1             // if possible             if (cn1 > 0)                 cn1--;              // Increment the value             // of cn0 by 1             cn0++;         }         else {              // To balance 1 with 0             // if possible             if (cn0 > 0)                 cn0--;              // Increment the value             // of cn1             cn1++;         }          // Update the maximum number         // of unused 0s and 1s         ans = max({ ans, cn0, cn1 });     }      // Print the resultant count     cout << ans; }  // Driver Code int main() {     string S = "010101";     minOpsToEmptyString(S);      return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{  // Function to find the minimum number // of operations to empty a binary string static void minOpsToEmptyString(String s) {          // Stores the resultant number of     // operations     int ans = Integer.MIN_VALUE;       // Stores the number of 0s     int cn0 = 0;       // Stores the number of 1s     int cn1 = 0;       // Traverse the given string     for(int i = 0; i < s.length(); i++)     {         if (s.charAt(i) == '0')         {                          // To balance 0 with 1             // if possible             if (cn1 > 0)                 cn1--;               // Increment the value             // of cn0 by 1             cn0++;         }         else          {                          // To balance 1 with 0             // if possible             if (cn0 > 0)                 cn0--;               // Increment the value             // of cn1             cn1++;         }           // Update the maximum number         // of unused 0s and 1s         ans = Math.max(ans, Math.max(cn0, cn1));     }       // Print the resultant count     System.out.print(ans); }   // Driver Code public static void main(String[] args) {     String S = "010101";     minOpsToEmptyString(S); } }  // This code is contributed by sanjoy_62 
Python3
# Python3 program for the above approach  # Function to find the minimum number # of operations to empty a binary string def minOpsToEmptyString(s):        # Stores the resultant number of     # operations     ans = -10**9      # Stores the number of 0s     cn0 = 0      # Stores the number of 1s     cn1 = 0      # Traverse the given string     for i in range(len(s)):         if (s[i] == '0'):              # To balance 0 with 1             # if possible             if (cn1 > 0):                 cn1 -= 1              # Increment the value             # of cn0 by 1             cn0 += 1         else:              # To balance 1 with 0             # if possible             if (cn0 > 0):                 cn0 -= 1              # Increment the value             # of cn1             cn1 += 1          # Update the maximum number         # of unused 0s and 1s         ans = max([ans, cn0, cn1])      # Print resultant count     print (ans)  # Driver Code if __name__ == '__main__':     S = "010101"     minOpsToEmptyString(S)  # This code is contributed by mohit kumar 29. 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{  // Function to find the minimum number // of operations to empty a binary string static void minOpsToEmptyString(string s) {          // Stores the resultant number of     // operations     int ans = 0;       // Stores the number of 0s     int cn0 = 0;       // Stores the number of 1s     int cn1 = 0;       // Traverse the given string     for(int i = 0; i < s.Length; i++)     {         if (s[i] == '0')         {                          // To balance 0 with 1             // if possible             if (cn1 > 0)                 cn1--;               // Increment the value             // of cn0 by 1             cn0++;         }         else          {                          // To balance 1 with 0             // if possible             if (cn0 > 0)                 cn0--;               // Increment the value             // of cn1             cn1++;         }           // Update the maximum number         // of unused 0s and 1s         ans = Math.Max(ans, Math.Max(cn0, cn1));     }       // Print the resultant count     Console.Write(ans); }  // Driver Code public static void Main() {     string S = "010101";     minOpsToEmptyString(S); } }  // This code is contributed by avijitmondal1998. 
JavaScript
<script> // JavaScript program for the above approach // Function to find the minimum number // of operations to empty a binary string function minOpsToEmptyString(s) {          // Stores the resultant number of     // operations     var ans = Number.MIN_VALUE;       // Stores the number of 0s     var cn0 = 0;       // Stores the number of 1s     var cn1 = 0;       // Traverse the given string     for(var i = 0; i < s.length; i++)     {         if (s.charAt(i) == '0')         {                          // To balance 0 with 1             // if possible             if (cn1 > 0)                 cn1--;               // Increment the value             // of cn0 by 1             cn0++;         }         else          {                          // To balance 1 with 0             // if possible             if (cn0 > 0)                 cn0--;               // Increment the value             // of cn1             cn1++;         }           // Update the maximum number         // of unused 0s and 1s         ans = Math.max(ans, Math.max(cn0, cn1));     }       // Print the resultant count     document.write(ans); }   // Driver Code var S = "010101"; minOpsToEmptyString(S);   //This code is contributed by shivanisinghss2110   </script> 

Output: 
1

 

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


Next Article
Smallest string which not a subsequence of the given string

S

shauryarehangfg
Improve
Article Tags :
  • Strings
  • Mathematical
  • C++ Programs
  • DSA
  • binary-string
Practice Tags :
  • Mathematical
  • Strings

Similar Reads

  • Minimize count of flips required such that no substring of 0s have length exceeding K
    Given a binary string str of length N and an integer K where K is in the range (1 ? K ? N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together. Exa
    6 min read
  • Smallest string which not a subsequence of the given string
    Given a string str, consisting of lowercase alphabets, the task is to find the shortest string which is not a subsequence of the given string. If multiple strings exist, then print any one of them. Examples: Input: str = "abaabcc" Output: d Explanation: One of the possible shortest string which is n
    6 min read
  • Minimum length of Run Length Encoding possible by removing at most K characters from a given string
    Given a string S of length N, consisting of lowercase English alphabets only, the task is to find the minimum possible length of run-length-encoding that can be generated by removing at most K characters from the string S. Examples: Input: S = "abbbcdcdd", N = 9, K = 2 Output: 5 Explanation: One pos
    10 min read
  • Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
    Given a binary string s, the task is to find the length of the longest subsequence that can be divided into three substrings such that the first and third substrings are either empty or filled with 1 and the substring at the middle is either empty or filled with 0. Examples: Input: s = "1001" Output
    7 min read
  • Check if a Binary String can be sorted in decreasing order by removing non-adjacent characters
    Given a binary string S of size N, the task is to check if the binary string S can be sorted in decreasing order by removing any number of the non-adjacent characters. If it is possible to sort the string in decreasing order, then print "Yes". Otherwise, print "No". Examples: Input: S = “10101011011
    7 min read
  • Length of longest subset consisting of A 0s and B 1s from an array of strings
    Given an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s. Examples: Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subs
    15+ min read
  • Minimum bit flips such that every K consecutive bits contain at least one set bit
    Given a binary string S, and an integer K, the task is to find the minimum number of flips required such that every substring of length K contains at least one '1'.Examples: Input: S = "10000001" K = 2 Output: 3 Explanation: We need only 3 changes in string S ( at position 2, 4 and 6 ) so that the s
    8 min read
  • Minimum number of palindromic subsequences to be removed to empty a binary string
    Given a binary string, count minimum number of subsequences to be removed to make it an empty string. Examples : Input: str[] = "10001" Output: 1 Since the whole string is palindrome, we need only one removal. Input: str[] = "10001001" Output: 2 We can remove the middle 1 as first removal, after fir
    6 min read
  • Minimum number of subsequences required to convert one string to another
    Given two strings A and B consisting of only lowercase letters, the task is to find the minimum number of subsequences required from A to form B. Examples: Input: A = "abbace" B = "acebbaae" Output: 3 Explanation: Sub-sequences "ace", "bba", "ae" from string A used to form string B Input: A = "abc"
    8 min read
  • Minimum number of characters to be removed to make a binary string alternate
    Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
    4 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