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 Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize length of a string by removing suffixes and prefixes of same characters
Next article icon

Minimize a binary string by repeatedly removing even length substrings of same characters

Last Updated : 14 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string.

Examples:

Input: str =”101001″
Output: “10”
Explanation: The string can be minimized in the following manner: “101001″ -> “1011” -> “10”.

Input: str = “00110”
Output: “0”
Explanation: The string can be minimized in the following manner: “00110″ -> “110″ -> “0”.

Approach: The idea is to use a stack to solve the problem. While traversing the string, if the current character is found to be same as the top element of the stack, pop the element from the stack. After traversal, print the stack from bottom to top. Follow the steps below to solve the problem:

  • Declare a stack and push the first character of the string str into the stack.
  • Traverse the string str over the range of indices [1, N – 1] using the variable i.
    • If the stack is empty, then push the character str[i] into the stack.
    • Otherwise, check if str[i] is equal to the top of the stack. If found to be true, pop it from the stack. Otherwise, push the character str[i] to it.
  • After completing the above steps, print the stack from bottom to top.

Below is the implementation of the above approach.

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Recursive function to print stack // elements from bottom to top without // changing their order void PrintStack(stack<char> s) {     // If stack is empty     if (s.empty())         return;      char x = s.top();      // Pop top element of the stack     s.pop();      // Recursively call the     // function PrintStack     PrintStack(s);      // Print the stack element     // from the bottom     cout << x;      // Push the same element onto the     // stack to preserve the order     s.push(x); }  // Function to minimize binary string // by removing substrings consisting // of same character void minString(string s) {     // Declare a stack of characters     stack<char> Stack;      // Push the first character of     // the string into the stack     Stack.push(s[0]);      // Traverse the string s     for (int i = 1; i < s.size(); i++) {          // If Stack is empty         if (Stack.empty()) {              // Push current character             // into the stack             Stack.push(s[i]);         }          else {              // Check if the current             // character is same as             // the top of the stack             if (Stack.top() == s[i]) {                  // If true, pop the                 // top of the stack                 Stack.pop();             }              // Otherwise, push the             // current element             else {                 Stack.push(s[i]);             }         }     }      // Print stack from bottom to top     PrintStack(Stack); }  // Driver Code int main() {     string str = "101001";     minString(str);      return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{  // Recursive function to print stack // elements from bottom to top without // changing their order static void PrintStack(Stack<Character> s) {     // If stack is empty     if (s.isEmpty())         return;      char x = s.peek();      // Pop top element of the stack     s.pop();      // Recursively call the     // function PrintStack     PrintStack(s);      // Print the stack element     // from the bottom     System.out.print(x);      // Push the same element onto the     // stack to preserve the order     s.add(x); }  // Function to minimize binary String // by removing subStrings consisting // of same character static void minString(String s) {     // Declare a stack of characters     Stack<Character> Stack = new Stack<Character>();      // Push the first character of     // the String into the stack     Stack.add(s.charAt(0));      // Traverse the String s     for (int i = 1; i < s.length(); i++) {          // If Stack is empty         if (Stack.isEmpty()) {              // Push current character             // into the stack             Stack.add(s.charAt(i));         }          else {              // Check if the current             // character is same as             // the top of the stack             if (Stack.peek() == s.charAt(i)) {                  // If true, pop the                 // top of the stack                 Stack.pop();             }              // Otherwise, push the             // current element             else {                 Stack.push(s.charAt(i));             }         }     }      // Print stack from bottom to top     PrintStack(Stack); }  // Driver Code public static void main(String[] args) {     String str = "101001";     minString(str);  } }  // This code is contributed by Amit Katiyar  
Python
# Python3 program for the above approach  # Recursive function to print stack # elements from bottom to top without # changing their order def PrintStack(s) :      # If stack is empty     if (len(s) == 0) :         return;      x = s[-1];      # Pop top element of the stack     s.pop();      # Recursively call the     # function PrintStack     PrintStack(s);      # Print the stack element     # from the bottom     print(x, end="");      # Push the same element onto the     # stack to preserve the order     s.append(x);  # Function to minimize binary string # by removing substrings consisting # of same character def minString(s) :      # Declare a stack of characters     Stack = [];      # Push the first character of     # the string into the stack     Stack.append(s[0]);      # Traverse the string s     for i in range(1, len(s)) :          # If Stack is empty         if (len(Stack) == 0) :              # Push current character             # into the stack             Stack.append(s[i]);          else:              # Check if the current             # character is same as             # the top of the stack             if (Stack[-1] == s[i]) :                  # If true, pop the                 # top of the stack                 Stack.pop();              # Otherwise, push the             # current element             else :                 Stack.append(s[i]);      # Print stack from bottom to top     PrintStack(Stack);  # Driver Code if __name__ == "__main__" :      string = "101001";     minString(string);      # This code is contributed by AnkThon 
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG {  // Recursive function to print stack // elements from bottom to top without // changing their order static void PrintStack(Stack<char> s) {     // If stack is empty     if (s.Count == 0)         return;     char x = s.Peek();      // Pop top element of the stack     s.Pop();      // Recursively call the     // function PrintStack     PrintStack(s);      // Print the stack element     // from the bottom     Console.Write((char)x);      // Push the same element onto the     // stack to preserve the order     s.Push(x); }  // Function to minimize binary String // by removing subStrings consisting // of same character static void minString(String s) {     // Declare a stack of characters     Stack<char> Stack = new Stack<char>();      // Push the first character of     // the String into the stack     Stack.Push(s[0]);      // Traverse the String s     for (int i = 1; i < s.Length; i++)      {          // If Stack is empty         if (Stack.Count == 0)          {              // Push current character             // into the stack             Stack.Push(s[i]);         }          else         {              // Check if the current             // character is same as             // the top of the stack             if (Stack.Peek() == s[i])             {                  // If true, pop the                 // top of the stack                 Stack.Pop();             }              // Otherwise, push the             // current element             else              {                 Stack.Push(s[i]);             }         }     }      // Print stack from bottom to top     PrintStack(Stack); }  // Driver Code public static void Main(String[] args) {     String str = "101001";     minString(str); } }  // This code is contributed by 29AjayKumar  
JavaScript
<script>  // js program for the above approach  // Recursive function to print stack // elements from bottom to top without // changing their order function PrintStack( s) {     // If stack is empty     if (s.length == 0)         return;      let x = s[s.length-1];      // Pop top element of the stack     s.pop();      // Recursively call the     // function PrintStack     PrintStack(s);      // Print the stack element     // from the bottom     document.write(x);      // Push the same element onto the     // stack to preserve the order     s.push(x); }  // Function to minimize binary string // by removing substrings consisting // of same character function minString( s) {     // Declare a stack of characters     let Stack = [];      // Push the first character of     // the string into the stack     Stack.push(s[0]);      // Traverse the string s     for (let i = 1; i < s.length; i++) {          // If Stack is empty         if (Stack.length==0) {              // Push current character             // into the stack             Stack.push(s[i]);         }          else {              // Check if the current             // character is same as             // the top of the stack             if (Stack[Stack.length-1] == s[i]) {                  // If true, pop the                 // top of the stack                 Stack.pop();             }              // Otherwise, push the             // current element             else {                 Stack.push(s[i]);             }         }     }      // Print stack from bottom to top     PrintStack(Stack); }  // Driver Code let str = "101001";     minString(str);  </script> 

Output
10

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

Approach : Recursive Approach

To reduce the size of the binary string, you can use a recursive algorithm to 
remove even-length sub-strings one at a time until you can no longer remove them.

Follow the steps:

  • Firstly, define a recursible function.
  • That finds & returns the first evenly sized substring of the same characters.
  • Call itself with the changed string until it can no longer contain even-sized substrings.
  • In the base case, if the sub-string is not even-length
  • Return the string.

Below is the implementation of the above approach:

Python
def remove_even_length_substrings(s):     i = 0     while i < len(s) - 1:         if s[i] == s[i + 1]:             s = s[:i] + s[i + 2:]             return remove_even_length_substrings(s)         i += 1     return s  # Example usage: print(remove_even_length_substrings("101001"))  print(remove_even_length_substrings("00110"))    
JavaScript
function removeEvenLengthSubstrings(s) {     let i = 0;     while (i < s.length - 1) {         if (s[i] === s[i + 1]) {             s = s.slice(0, i) + s.slice(i + 2);             return removeEvenLengthSubstrings(s);         }         i++;     }     return s; }  // Example usage: console.log(removeEvenLengthSubstrings("101001")); console.log(removeEvenLengthSubstrings("00110"));   // This code is contributed by Shivam  

Output
10 0 

Time Complexity: O(N2)

Auxiliary Space: O(N)




Next Article
Minimize length of a string by removing suffixes and prefixes of same characters
author
shahbazalam75508
Improve
Article Tags :
  • DSA
  • Stack
  • Strings
  • Technical Scripter
  • binary-string
  • cpp-stack-functions
  • substring
  • Technical Scripter 2020
Practice Tags :
  • Stack
  • Strings

Similar Reads

  • Minimize flips to make binary string as all 1s by flipping characters in substring of size K repeatedly
    Given a binary string S of size N and an integer K, the task is to find the minimum number of operations required to make all characters as 1s in the binary string by flipping characters in the substring of size K. If it is not possible to do so, then print "-1". Examples: Input: S = "00010110 ", K
    7 min read
  • Minimize length of a string by removing suffixes and prefixes of same characters
    Given a string S of length N consisting only of characters 'a', 'b', and 'c', the task is to minimize the length of the given string by performing the following operations only once: Divide the string into two non-empty substrings and then, append the left substring to the end of the right substring
    6 min read
  • Minimize String length by deleting Substring of same character when K flips are allowed
    Given a binary string consisting of '0' and '1' only and an integer K, the task is to minimize the string as far as possible by deleting a substring of the same character, when you can flip at most K characters. Examples: Input: S = "0110", K = 2Output: 0Explanation: We can make two '0' s into '1' o
    12 min read
  • Minimum substring removals required to make all remaining characters of a string same
    Given a string str of length N, the task is to find the minimum number of substrings required to be removed to make all the remaining characters of the string same. Note: The substring to be removed must not contain the last remaining character in the string. Examples: Input: str = "ACBDAB" Output:
    7 min read
  • Minimize the count of characters to be added or removed to make String repetition of same substring
    Given a string S consisting of N characters, the task is to modify the string S by performing the minimum number of following operations such that the modified string S is the concatenation of its half. Insert any new character at any index in the string.Remove any character from the string S.Replac
    15+ min read
  • 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 remainin
    8 min read
  • Minimize length of string by replacing K pairs of distinct adjacent characters
    Given string str of length N, the task is to find the minimum length to which the given string can be reduced by replacing any pair of non-equal adjacent characters with a single character at most K times. Examples: Input: str = "aabc", K =1Output: 3Explanation: Replace "bc" with a single character
    5 min read
  • Maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0
    Given a binary string S, the task is to find the maximum length of substrings required to be flipped repeatedly to make all the characters of a binary string equal to '0'. Examples: Input: S = "010"Output: 2Explanation:Following are the order of flipping of substring of at least K for the value of K
    6 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Minimum steps to delete a string after repeated deletion of palindrome substrings
    Given a string str, containing only digits from '0' to '9'. Your task is to find the minimum number of operations required to delete all the digits of string, where in each operation we can delete a palindromic substring. Note: After deleting the substring, the remaining parts are concatenated. Exam
    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