The Wayback Machine - https://web.archive.org/web/20240811222757/https://www.geeksforgeeks.org/minimum-removal-of-subsequences-of-distinct-consecutive-characters-required-to-empty-a-given-string/
Open In App

Minimum removal of subsequences of distinct consecutive characters required to empty a given string

Last Updated : 21 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary string, str, the task is to empty the given string by minimum number of removals of a single character or a subsequence containing distinct consecutive characters from str.

Examples:

Input: str = “0100100111” 
Output: 3 
Explanation: 
Removing the subsequence “010101” from the string modifies str to “0011”. 
Removing the subsequence “01” from the string modifies str to “01”. 
Removing the subsequence “01” from the string modifies str to “” which is an empty string. 
Therefore, the required output is 3.

Input: str = “010110” 
Output: 2

 

Naive Approach: The simplest approach to solve this problem is to traverse the string repetitively and remove the longest subsequence of distinct consecutive characters from the string and increment the count after every removal. Finally, print the count. 

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

Efficient Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:

  • Initialize two variables, say cntOne and cntZero, to store the count of 1s and 0s.
  • Traverse the string using variable i and check the following conditions: 
    • If str[i] == ‘0’, then increment the value of cntZero and check if the value of cntOne is greater than 0 or not. If found to be true, then decrement the value of cntOne.
    • If str[i] == ‘1’, then increment the value of cntOne and check if the value of cntZero is greater than 0 or not. If found to be true, then decrement the value of cntZero.
  • Finally, print the value of (cntZero + cntOne).

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
//Function to count minimum operations required
// to make the string an empty string
int findMinOperationsReqEmpStr(string str)
{
    // Stores count of 1s by removing
    // consecutive distinct subsequence
    int cntOne = 0;
 
    // Stores count of 0s by removing
    // consecutive distinct subsequence
    int cntZero = 0 ;
 
    // Stores length of str
    int N = str.length();
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
        // If current character
        // is 0
        if(str[i] == '0'){
            if (cntOne) {
 
                // Update cntOne
                cntOne--;
            }
 
            // Update cntZero
            cntZero++;
        }
 
        // If current character
        // is 1
        else{
 
            //Update cntZero
            if (cntZero) {
                cntZero--;
            }
             
             
            // Update cntOne
            cntOne++;
        }
    }
     
    return (cntOne + cntZero);
}
 
 
// Driver Code
int main()
{
    string str = "0100100111";
    cout<< findMinOperationsReqEmpStr(str);
}


Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
 
//Function to count minimum operations required
// to make the string an empty string
static int findMinOperationsReqEmpStr(String str)
{
     
    // Stores count of 1s by removing
    // consecutive distinct subsequence
    int cntOne = 0;
 
    // Stores count of 0s by removing
    // consecutive distinct subsequence
    int cntZero = 0;
 
    // Stores length of str
    int N = str.length();
 
    // Traverse the string
    for(int i = 0; i < N; i++)
    {
         
        // If current character
        // is 0
        if(str.charAt(i) == '0')
        {
            if (cntOne != 0)
            {
                 
                // Update cntOne
                cntOne--;
            }
 
            // Update cntZero
            cntZero++;
        }
 
        // If current character
        // is 1
        else
        {
             
            // Update cntZero
            if (cntZero != 0)
            {
                cntZero--;
            }
             
            // Update cntOne
            cntOne++;
        }
    }
    return (cntOne + cntZero);
}
 
// Driver code
public static void main(String[] args)
{
    String str = "0100100111";
     
    System.out.print(findMinOperationsReqEmpStr(str));
}
}
 
// This code is contributed by ajaykr00kj


Python3




# Python3 program to implement
# the above approach
 
# Function to count minimum operations
# required to make the string an empty
# string
def findMinOperationsReqEmpStr(str):
     
    # Stores count of 1s by removing
    # consecutive distinct subsequence
    cntOne = 0
   
    # Stores count of 0s by removing
    # consecutive distinct subsequence
    cntZero = 0
     
    # Traverse the string
    for element in str:
         
        # If current character
        # is 0
        if element == '0':
            if cntOne > 0: 
   
                # Update cntOne
                cntOne = cntOne - 1
                 
            # Update cntZero
            cntZero = cntZero + 1
             
        # If current character
        # is 1
        else:
             
            # Update cntZero
            if cntZero > 0:
                cntZero = cntZero - 1
              
            # Update cntOne
            cntOne = cntOne + 1
     
    return cntOne + cntZero  
     
# Driver code
if __name__ == "__main__":
     
    str = "0100100111"
     
    print(findMinOperationsReqEmpStr(str))
 
# This code is contributed by ajaykr00kj


C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
 
// Function to count minimum operations required
// to make the string an empty string
static int findMinOperationsReqEmpStr(String str)
{
     
    // Stores count of 1s by removing
    // consecutive distinct subsequence
    int cntOne = 0;
 
    // Stores count of 0s by removing
    // consecutive distinct subsequence
    int cntZero = 0;
 
    // Stores length of str
    int N = str.Length;
 
    // Traverse the string
    for(int i = 0; i < N; i++)
    {
         
        // If current character
        // is 0
        if(str[i] == '0')
        {
            if (cntOne != 0)
            {
                 
                // Update cntOne
                cntOne--;
            }
 
            // Update cntZero
            cntZero++;
        }
 
        // If current character
        // is 1
        else
        {
             
            // Update cntZero
            if (cntZero != 0)
            {
                cntZero--;
            }
             
            // Update cntOne
            cntOne++;
        }
    }
    return (cntOne + cntZero);
}
 
// Driver code
public static void Main(String[] args)
{
    String str = "0100100111";
     
    Console.Write(findMinOperationsReqEmpStr(str));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to count minimum operations required
// to make the string an empty string
function findMinOperationsReqEmpStr(str)
{
     
    // Stores count of 1s by removing
    // consecutive distinct subsequence
    let cntOne = 0;
  
    // Stores count of 0s by removing
    // consecutive distinct subsequence
    let cntZero = 0;
  
    // Stores length of str
    let N = str.length;
  
    // Traverse the string
    for(let i = 0; i < N; i++)
    {
          
        // If current character
        // is 0
        if (str[i] == '0')
        {
            if (cntOne != 0)
            {
                 
                // Update cntOne
                cntOne--;
            }
  
            // Update cntZero
            cntZero++;
        }
  
        // If current character
        // is 1
        else
        {
             
            // Update cntZero
            if (cntZero != 0)
            {
                cntZero--;
            }
              
            // Update cntOne
            cntOne++;
        }
    }
    return (cntOne + cntZero);
}
     
// Driver code
let str = "0100100111";
  
document.write(findMinOperationsReqEmpStr(str));
 
// This code is contributed by code_hunt
 
</script>


Output: 

3

 

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



Similar Reads

Minimum removal of consecutive similar characters required to empty a Binary String
Given a binary string S of length N, the task is to find the minimum number of removal of adjacent similar characters required to empty the given binary string. Examples: Input: S = “1100011“Output: 2Explanation:Operation 1: Removal of all 0s modifies S to “1111“.Operation 2: Removal of all remaining 1s makes S empty.Therefore, the minimum number o
8 min read
Count removal of pairs required to be empty all Balanced Parenthesis subsequences
Given a string str, the task is to find the maximum count of pairs (str[i], str[j]) of balanced parenthesis required to be removed such that the string does not contain any subsequence of balanced parenthesis: Examples: Input: str = "{(})" Output: 2 Explanation: Removing the pair of valid parenthesis(0, 2) modified str to "()" Removing the pair of
8 min read
Minimize removal of non-equal adjacent characters required to make a given string empty
Given a string S consisting of '(' and ')', the task is to find the minimum count of bracket reversals required to make the string an empty string by repeatedly removing a pair of non-equal adjacent characters. If it is not possible to empty the string, then print -1. Examples: Input: S = ")))((("Output: 0Explanation: Removing (S[2], S[3]) from S m
7 min read
Minimize removal of alternating subsequences to empty given Binary String
Given a binary string S of length N, the task is to minimize the count of repetitive removal of alternating subsequence of the 0 and 1 from the given binary string S to make the string empty. Examples: Input: S = "0100100111"Output: 3Explanation: Remove subsequence "010101" from S to modify it to "0011". Remove "01" from "0011" to make it "01". Fin
5 min read
Minimum removal of characters required such that permutation of given string is a palindrome
Given string str consisting of lowercase letters, the task is to find the minimum number of characters to be deleted from the given string such that any permutation of the remaining string is a palindrome. Examples: Input: str="aba"Output: 1Explanation: Removing 'b' generates a palindromic string "aa". Input: "abab"Output: 0Explanation: Permutation
7 min read
Cost required to empty a given array by repeated removal of maximum obtained by given operations
Given an array arr[] consisting of N integers, the task is to find the cost to remove all array elements after performing the following operations in the specified order any number of times: Add the maximum element present in the given array to the cost.Remove the maximum element from the given array.Decrease all integers in the given array by 1.Re
10 min read
Minimum removal of K equal elements required to empty an array
Given an array arr[] consisting of N integers, the task is to count the minimum number of times at most K equal elements are required to be removed to make the array empty. Examples: Input: arr[] = {1, 3, 1, 1, 3}, K = 2Output: 3Explanation: Step 1: Remove at most 2 1s from the array. The modified array is {1, 3, 3}. Step 2: Remove at most 2 3s fro
7 min read
Count of distinct GCDs among all the non-empty subsequences of given array
Given an integer array arr[] of size N, the task is to calculate the total number of distinct Greatest Common Divisors(GCDs) among all the non-empty subsequences of arr[]. Examples: Input: arr[]={3,4,8} N=3Output:4Explanation:The different non-empty subsequences possible are {3}, {4}, {8}, {3,4}, {4,8}, {3,8}, {3,4,8} and their corresponding GCDs a
8 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read
Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2
Given a string S consisting of N lowercase alphabets, the task is to remove the characters from the string whose frequency is not a power of 2 and then sort the string in ascending order. Examples: Input: S = "aaacbb"Output: bbcExplanation: The frequencies of 'a', 'b', and 'c' in the given string are 3, 2, 1. Only the character 'a' has frequency (=
7 min read
three90RightbarBannerImg