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
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimum number of characters to be replaced to make a given string Palindrome
Next article icon

Minimum number of palindromic subsequences to be removed to empty a binary string

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 first removal string becomes 1000001 which is a palindrome.

Expected time complexity : O(n)

We strongly recommend that you click here and practice it, before moving on to the solution.

The problem is simple and can be solved easily using below two facts. 

  1. If given string is palindrome, we need only one removal. 
  2. Else we need two removals. Note that every binary string has all 1’s as a subsequence and all 0’s as another subsequence. We can remove any of the two subsequences to get a unary string. A unary string is always palindrome. 

Implementation:

C++




// C++ program to count minimum palindromic subsequences
// to be removed to make an string empty.
#include <bits/stdc++.h>
using namespace std;
 
// A function to check if a string str is palindrome
bool isPalindrome(const char *str)
{
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = strlen(str) - 1;
 
    // Keep comparing characters while they are same
    while (h > l)
        if (str[l++] != str[h--])
            return false;
 
    return true;
}
 
// Returns count of minimum palindromic subsequences to
// be removed to make string empty
int minRemovals(const char *str)
{
   // If string is empty
   if (str[0] == '\0')
      return 0;
 
   // If string is palindrome
   if (isPalindrome(str))
      return 1;
 
   // If string is not palindrome
   return 2;
}
 
// Driver code to test above
int main()
{
   cout << minRemovals("010010") << endl;
   cout << minRemovals("0100101") << endl;
   return 0;
}
 
 

Java




// Java program to count minimum palindromic
// subsequences to be removed to make
// an string empty.
import java.io.*;
 
class GFG {
     
// A function to check if a string
// str is palindrome
static boolean isPalindrome(String str)
{
    // Start from leftmost and rightmost
    // corners of str
    int l = 0;
    int h = str.length() - 1;
 
    // Keep comparing characters
    // while they are same
    while (h > l)
        if (str.charAt(l++) != str.charAt(h--))
            return false;
 
    return true;
}
 
// Returns count of minimum palindromic
// subsequences to be removed to
// make string empty
static int minRemovals(String str)
{
    // If string is empty
    if (str.charAt(0) == '')
        return 0;
 
    // If string is palindrome
    if (isPalindrome(str))
        return 1;
 
    // If string is not palindrome
    return 2;
}
 
// Driver code to test above
public static void main (String[] args)
{
    System.out.println (minRemovals("010010"));
    System.out.println (minRemovals("0100101"));
         
}
}
 
// This code is contributed by vt_m.
 
 

Python3




# Python program to count minimum
# palindromic subsequences to
# be removed to make an string
# empty.
 
# A function to check if a
# string str is palindrome
def isPalindrome(str):
     
    # Start from leftmost and
    # rightmost corners of str
    l = 0
    h = len(str) - 1
     
    # Keep comparing characters
    # while they are same
    while (h > l):
        if (str[l] != str[h]):
            return 0
        l = l + 1
        h = h - 1
         
    return 1
     
# Returns count of minimum
# palindromic subsequences to
# be removed to make string
# empty
def minRemovals(str):
     
    #If string is empty
    if (str[0] == ''):
        return 0
     
    #If string is palindrome
    if (isPalindrome(str)):
        return 1
     
    # If string is not palindrome
    return 2
     
# Driver code
print(minRemovals("010010"))
print(minRemovals("0100101"))
 
# This code is contributed by Sam007.
 
 

C#




// C# program to count minimum palindromic
// subsequences to be removed to make
// an string empty.
using System;
 
class GFG
{
     
    // A function to check if a
    // string str is palindrome
    static bool isPalindrome(String str)
    {
        // Start from leftmost and
        // rightmost corners of str
        int l = 0;
        int h = str.Length - 1;
     
        // Keep comparing characters
        // while they are same
        while (h > l)
            if (str[l++] != str[h--])
                return false;
     
        return true;
    }
     
    // Returns count of minimum palindromic
    // subsequences to be removed to
    // make string empty
    static int minRemovals(String str)
    {
        // If string is empty
        if (str[0] == '')
            return 0;
     
        // If string is palindrome
        if (isPalindrome(str))
            return 1;
     
        // If string is not palindrome
        return 2;
    }
     
    // Driver code to
    public static void Main ()
    {
        Console.WriteLine(minRemovals("010010"));
        Console.WriteLine(minRemovals("0100101"));
             
    }
     
}
 
// This code is contributed by Sam007
 
 

PHP




<?php
// PHP program to count minimum
// palindromic subsequences to
// be removed to make an string empty.
 
// A function to check if a
// string str is palindrome
function isPalindrome($str)
{
    // Start from leftmost and
    // rightmost corners of str
    $l = 0;
    $h = strlen($str) - 1;
 
    // Keep comparing characters
    // while they are same
    while ($h > $l)
        if ($str[$l++] != $str[$h--])
            return false;
 
    return true;
}
 
// Returns count of minimum
// palindromic subsequences
// to be removed to make
// string empty
function minRemovals($str)
{
// If string is empty
if ($str[0] == '')
    return 0;
 
// If string is palindrome
if (isPalindrome($str))
    return 1;
 
// If string is not palindrome
return 2;
}
 
// Driver Code
echo minRemovals("010010"), "\n";
echo minRemovals("0100101") , "\n";
 
// This code is contributed by ajit
?>
 
 

Javascript




<script>
 
    // Javascript program to count
    // minimum palindromic
    // subsequences to be removed to make
    // an string empty.
     
    // A function to check if a
    // string str is palindrome
    function isPalindrome(str)
    {
        // Start from leftmost and
        // rightmost corners of str
        let l = 0;
        let h = str.length - 1;
       
        // Keep comparing characters
        // while they are same
        while (h > l)
            if (str[l++] != str[h--])
                return false;
       
        return true;
    }
       
    // Returns count of minimum palindromic
    // subsequences to be removed to
    // make string empty
    function minRemovals(str)
    {
        // If string is empty
        if (str[0] == '')
            return 0;
       
        // If string is palindrome
        if (isPalindrome(str))
            return 1;
       
        // If string is not palindrome
        return 2;
    }
     
 // Driver Code
  
    document.write(minRemovals("010010") + "</br>");
      document.write(minRemovals("0100101"));
     
</script>
 
 
Output
1 2

Time Complexity: O(n)

Auxiliary Space : O(1)

Exercises: 

  1. Extend the above solution to count minimum number of subsequences to be removed to make it an empty string.
  2. What is the maximum count for ternary strings

This problem and solution are contributed by Hardik Gulati.



Next Article
Minimum number of characters to be replaced to make a given string Palindrome
author
kartik
Improve
Article Tags :
  • DSA
  • Strings
  • binary-string
  • palindrome
  • subsequence
Practice Tags :
  • palindrome
  • Strings

Similar Reads

  • Minimum size substring to be removed to make a given string palindromic
    Given a string S, the task is to print the string after removing the minimum size substring such that S is a palindrome or not. Examples: Input: S = "pqrstsuvwrqp"Output: pqrstsrqpExplanation:Removal of the substring "uvw" modifies S to a palindromic string. Input: S = "geeksforskeeg"Output: geeksfs
    15+ min read
  • Minimum number of characters to be replaced to make a given string Palindrome
    Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. If there are multiple answers, print t
    5 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
  • Maximum count of “010..” subsequences that can be removed from given Binary String
    Given a binary string S consisting of size N, the task is to find the maximum number of binary subsequences of the form "010.." of length at least 2 that can be removed from the given string S. Examples: Input: S = "110011010"Output: 3Explanation:Following are the subsequence removed:Operation 1: Ch
    6 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
  • Minimum number of deletions to make a string palindrome | Set 2
    Given a string A, compute the minimum number of characters you need to delete to make resulting string a palindrome. Examples: Input : baca Output : 1 Input : geek Output : 2 We have discussed one approach in below post. Minimum number of deletions to make a string palindrome Below approach will use
    9 min read
  • Form minimum number of Palindromic Strings from a given string
    Given a string S, the task is to divide the characters of S to form minimum number of palindromic strings. Note: There can be multiple correct answers. Examples: Input: S = "geeksforgeeks"Output: {eegksrskgee, o, f} Explanation: There should be at least 3 strings "eegksrskgee", "o", "f". All 3 forme
    12 min read
  • Find a palindromic string B such that given String A is a subsequence of B
    Given a string [Tex]A [/Tex]. Find a string [Tex]B [/Tex], where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For exam
    6 min read
  • Rearrange the string to maximize the number of palindromic substrings
    Given a string S consisting of lowercase characters(a-z) only, the task is to print a new string by rearranging the string in such a way that maximizes the number of palindromic substrings. In case of multiple answers, print any one. Note: even if some substrings coincide, count them as many times a
    5 min read
  • Minimum number whose binary form is not a subsequence of given binary string
    Given a binary string S of size N, the task is to find the minimum non-negative integer which is not a subsequence of the given string S in its binary form. Examples: Input: S = "0000"Output:1Explanation: 1 whose binary representation is "1" is the smallest non-negative integer which is not a subseq
    8 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