Minimum substring removals required to make all remaining characters of a string same
Last Updated :
18 May, 2021
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: 2
Explanation:
Removing the substring { str[1], ..., str[3] } modifies str to "AAB"
Removing the substring {str[2] } modifies str to "AA"
Since all characters of str are equal, the required output is 2.
Input: str = "ZBCDEFZ"
Output: 1
Explanation:
Removing the substring { str[1], ..., str[5] } modifies str to "ZZ"
Since all characters of str are equal, the required output is 1.
Approach: The idea is to first remove all the consecutive duplicate characters of the string and count the frequency of each distinct character of the string. Finally, remove all the characters of the string except the character having minimum frequency. Follow the steps below to solve the problem:
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 all characters equal
// by repeatedly removing substring
void minOperationNeeded(string str)
{
// Remove consecutive duplicate
// characters from str
str = string(str.begin(),
unique(str.begin(), str.end()));
// Stores length of the string
int N = str.length();
// Stores frequency of each distinct
// characters of the string str
int res[256] = { 0 };
// Iterate over all the characters
// of the string str
for (int i = 0; i < N; ++i) {
// Update frequency of str[i]
res[str[i]] += 1;
}
// Decrementing the frequency
// of the string str[0]
res[str[0]] -= 1;
// Decrementing the frequency
// of the string str[N - 1]
res[str[N - 1]] -= 1;
// Stores the required count
int ans = INT_MAX;
// Iterate over all characters
// of the string str
for (int i = 0; i < N; ++i) {
// Update ans
ans = min(ans, res[str[i]]);
}
cout << (ans + 1) << endl;
}
// Driver Code
int main()
{
// Given string
string str = "ABCDABCDABCDA";
minOperationNeeded(str);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG {
// Function to count minimum operations
// required to make all characters equal
// by repeatedly removing subString
static void minOperationNeeded(char[] str)
{
// Remove consecutive duplicate
// characters from str
str = modstring(str);
// Stores length of the String
int N = str.length;
// Stores frequency of each distinct
// characters of the String str
int res[] = new int[256];
// Iterate over all the characters
// of the String str
for (int i = 0; i < N; ++i) {
// Update frequency of str[i]
res[str[i]] += 1;
}
// Decrementing the frequency
// of the String str[0]
res[str[0]] -= 1;
// Decrementing the frequency
// of the String str[N - 1]
res[str[N - 1]] -= 1;
// Stores the required count
int ans = Integer.MAX_VALUE;
// Iterate over all characters
// of the String str
for (int i = 0; i < N; ++i) {
// Update ans
ans = Math.min(ans, res[str[i]]);
}
System.out.print((ans + 1) + "\n");
}
private static char[] modstring(char[] str) {
String s = "";
boolean b = true;
for (int i = 1; i < str.length; ++i) {
if (str[i - 1] != str[i])
b = true;
if (b) {
s += str[i-1];
b = false;
}
}
return s.toCharArray();
}
// Driver Code
public static void main(String[] args)
{
// Given String
String str = "ABCDABCDABCDA";
minOperationNeeded(str.toCharArray());
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program to implement
# the above approach
import re, sys
# Function to count minimum operations
# required to make all characters equal
# by repeatedly removing substring
def minOperationNeeded(s):
# Remove consecutive duplicate
# characters from str
d = {}
str = re.sub(r"(.)\1 + ",'', s)
# Stores length of the string
N = len(str)
# Stores frequency of each distinct
# characters of the string str
res = [0 for i in range(256)]
# Iterate over all the characters
# of the string str
for i in range(N):
# Update frequency of str[i]
res[ord(str[i])] += 1
# Decrementing the frequency
# of the string str[0]
res[ord(str[0])] -= 1
# Decrementing the frequency
# of the ord(string ord(str[N - 1]
res[ord(str[N - 1])] -= 1
# Stores the required count
ans = sys.maxsize
# Iterate over all characters
# of the string str
for i in range(N):
# Update ans
ans = min(ans, res[ord(str[i])])
print ((ans + 1))
# Driver Code
if __name__ == '__main__':
# Given string
str = "ABCDABCDABCDA"
minOperationNeeded(str)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG{
// Function to count minimum operations
// required to make all characters equal
// by repeatedly removing subString
static void minOperationNeeded(char[] str)
{
// Remove consecutive duplicate
// characters from str
str = modstring(str);
// Stores length of the String
int N = str.Length;
// Stores frequency of each distinct
// characters of the String str
int[] res = new int[256];
// Iterate over all the characters
// of the String str
for (int i = 0; i < N; ++i)
{
// Update frequency of str[i]
res[str[i]] += 1;
}
// Decrementing the frequency
// of the String str[0]
res[str[0]] -= 1;
// Decrementing the frequency
// of the String str[N - 1]
res[str[N - 1]] -= 1;
// Stores the required count
int ans = Int32.MaxValue;
// Iterate over all characters
// of the String str
for (int i = 0; i < N; ++i)
{
// Update ans
ans = Math.Min(ans, res[str[i]]);
}
Console.WriteLine((ans + 1) + "\n");
}
private static char[] modstring(char[] str)
{
string s = "";
bool b = true;
for (int i = 1; i < str.Length; ++i)
{
if (str[i - 1] != str[i])
b = true;
if (b)
{
s += str[i - 1];
b = false;
}
}
return s.ToCharArray();
}
// Driver Code
public static void Main()
{
// Given String
string str = "ABCDABCDABCDA";
minOperationNeeded(str.ToCharArray());
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// JavaScript program for the above approach
// Function to count minimum operations
// required to make all characters equal
// by repeatedly removing subString
function minOperationNeeded(str) {
// Remove consecutive duplicate
// characters from str
str = modstring(str);
// Stores length of the String
var N = str.length;
// Stores frequency of each distinct
// characters of the String str
var res = new Array(256).fill(0);
// Iterate over all the characters
// of the String str
for (var i = 0; i < N; ++i) {
// Update frequency of str[i]
res[str[i].charCodeAt(0)] += 1;
}
// Decrementing the frequency
// of the String str[0]
res[str[0].charCodeAt(0)] -= 1;
// Decrementing the frequency
// of the String str[N - 1]
res[str[N - 1].charCodeAt(0)] -= 1;
// Stores the required count(Max Integer value)
var ans = 2147483647;
// Iterate over all characters
// of the String str
for (var i = 0; i < N; ++i) {
// Update ans
ans = Math.min(ans, res[str[i].charCodeAt(0)]);
}
document.write(ans + 1 + "<br>");
}
function modstring(str) {
var s = "";
var b = true;
for (var i = 1; i < str.length; ++i) {
if (str[i - 1] !== str[i]) b = true;
if (b) {
s += str[i - 1];
b = false;
}
}
return s.split("");
}
// Driver Code
// Given String
var str = "ABCDABCDABCDA";
minOperationNeeded(str.split(""));
</script>
Time Complexity: O(N)
Auxiliary Space: O(256)
Similar Reads
Minimize cost of removals required to make all remaining characters of the string unique Given a string str and an array cost[] of size N where cost[i] denotes the cost to remove the ith character from the string str, the task is to find the minimum cost of removals required to make every character of the string unique. Examples: Input: str = "AAABBB", cost = {1, 2, 3, 4, 5, 6} Output:
14 min read
Count minimum substring removals required to reduce string to a single distinct character Given a string S consisting of 'X', 'Y' and 'Z' only, the task is to convert S to a string consisting of only a single distinct character by selecting a character and removing substrings that does not contain that character, minimum number of times. Note: Once a character is chosen, no other charact
7 min read
Number of ways to remove a sub-string from S such that all remaining characters are same Given a string str consisting only of lowercase English alphabets, the task is to count the number of ways to remove exactly one sub-string from str such that all remaining characters are same. Note: There are at least two different characters in str and we can remove the whole string as well. Examp
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 replacements by previous or next alphabet required to make all characters of a string the same Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations required to make all the characters of the string S the same. In each operation, choose any character and replace it with its next or previous alphabet. Note: The alphabets are consid
6 min read