Minimize a binary string by repeatedly removing even length substrings of same characters
Last Updated :
14 Jun, 2024
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:
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>
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
Time Complexity: O(N2)
Auxiliary Space: O(N)
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
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
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.Exampl
15+ min read
Maximize minority character deletions that can be done from given Binary String substring Python Given binary string str of size, N. Select any substring from the string and remove all the occurrences of the minority character (i.e. the character having less frequency) from the substring. The task is to find out the maximum number of characters that can be removed from performing one suc
5 min read
Minimize operations to make given binary string as all 1s by repeatedly converting K consecutive characters to 1 Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1's where at each move, K consecutive characters can be converted to 1. Example: Input: str="0010", K=3Output: 2Explanation:Move 1: Select the substring f
4 min read
Minimum steps to delete a string by deleting substring comprising of same characters Given string str. You are allowed to delete only some contiguous characters if all the characters are the same in a single operation. The task is to find the minimum number of operations required to completely delete the string. Examples: Input: str = "abcddcba" Output: 4 Explanation: Delete dd, the
7 min read