# 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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Examples:

Input: str = “ACBDAB”
Output:
Explanation:
Removing the substring { str, …, str } modifies str to “AAB”
Removing the substring {str } modifies str to “AA”
Since all characters of str are equal, the required output is 2.

Input: str = “ZBCDEFZ”
Output:
Explanation:
Removing the substring { str, …, str } 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 ``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 = { 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``    ``res[str] -= 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``        ``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``    ``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``;`` ` `        ``// 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``        ``res[str] -= 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

 ``
Output:
`3`

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

My Personal Notes arrow_drop_up