Length of Smallest Substring to be Replaced to make Frequency of each Character as N/3


In this problem, we need to find the smallest substring so that we can replace its character and make the frequency of each character equal to the N/3 in the given string.

We can use the sliding window technique to solve the problem. We can find the minimum window size, which contains all excess characters, that will be the answer to the problem.

Problem statement – We have given a string alpha. The size of the alpha is N which is always divisible by 3. The given task is to find the minimum length of the substring so that we can replace any of its characters and ensure that the string contains each character exactly N/3 times.

Note – The string contains at most three distinct characters.

Sample examples

Input

alpha = ‘NMM’

Output

1

Explanation – The smallest substring is ‘N’, which we need to change to make the frequency of all characters in the string equal to N/3.

Input

alpha = "BEGBBG";

Output

1

Explanation – The smallest substring is ‘E’, which we need to change to make the string equal to ‘BGGBBG’, containing all characters with a frequency equal to N/3.

Input

alpha = ‘DDDQQQ’

Output

2

Explanation – The smallest substring is ‘DQ’, which we need to replace with any character to make all characters’ frequency equal to N/3.

Approach 1

In this approach, we will find the character frequency first. Based on the character frequency, we will decide the excess characters. After that, we will find the minimum length of the window, which contains all excess characters, and we can take the substring of the same length to show in the output.

Algorithm

Step 1 – If the string length is zero, return 0, as we need a substring of length 0.

Step 2 – Define the charFreq hashmap to store the frequency of all characters. Traverse the string and store the frequency of each character in the map.

Step 3 – Define the excessChars map to store the frequency of the extra characters.

Step 4 – Traverse the charFreq map. If the value for any key is greater than len/3, add the key to the excessChars map with the value equal to its frequency – len/3.

Step 5 – If the size of excessChars is zero means there is no extra character. So, return 0.

Step 6 – Initialize the p and q variables for the sliding window. Also, initialize the minLen variable with len + 1, assuming the length of the substring is equal to len + 1.

Step 7 – In the ‘cnt’ variable, store the size of the excessChars map. Furthermore, traverse the string using the while loop.

Step 8 – If the current character exists in the excessChars map, decrease its value by 1 as we included it inside the current window.

Step 9 – If the value of the excessChars[c] is zero, decrease the ‘cnt’ value by 1 as the current window contains all extra occurrences of the character c.

Step 10 – If ‘cnt’ is equal to zero, the current window contains all the occurrences of extra characters. So, we need to start decreasing the window size to get a minimum window size.

Step 11 – Traverse the string until p < len && cnt == 0 condition becomes false.

Step 11.1 – In the minLen variable, store the minimum of minLen and q – p + 1, which is the current window size.

Step 11.2 – If the current character exists in the excessChars hashmap, increase its value by 1, and if excessChars[alpha[p]] == 1 is true, increase the value of ‘cnt’ by 1.

Step 11.3 – Increase q and p values.

Step 12 – Return the ‘minLen’ variable value.

Example

#include <bits/stdc++.h>
using namespace std;

int countSize(string alpha) {
    int len = alpha.length();
    // return 0 if the string is empty
    if (len == 0) {
        return 0;
    }
    // to store character frequency
    map<char, int> charFreq;
    // calculate the frequency of each character
    for (char c : alpha) {
        charFreq[c]++;
    }
    // Count of extra characters
    map<char, int> excessChars;
    // Calculating excess characters
    for (auto c : charFreq) {
        if (c.second > len / 3) {
            excessChars[c.first] = (c.second - len / 3);
        }
    }
    // If no extra character is present in the string, return 0 as the string is balanced.
    if (excessChars.size() == 0) {
        return 0;
    }
    // sliding window
    int p = 0, q = 0;
    // Need to find minimum window length
    int minLen = len + 1;
    // total extra characters
    int cnt = excessChars.size();
    while (q < len) {
        // character at q index
        char c = alpha[q];
        // If c is extra
        if (excessChars.find(c) != excessChars.end()) {
            // Decrease frequency of c in the current window
            excessChars[c]--;
            // If all extra chars are consumed, decrease the number of extra chars by 1
            if (excessChars[c] == 0) {
                cnt--;
            }
        }
        // If the window contains all extra characters
        if (cnt == 0) {
            // Start decreasing window size
            while (p < len && cnt == 0) {
                // Get minimum window length
                minLen = min(minLen, q - p + 1);
                // If we find extra character
                if (excessChars.find(alpha[p]) != excessChars.end()) {
                    // Change char frequency in the current window
                    excessChars[alpha[p]]++;
                    // Add 1 in extra chars count
                    if (excessChars[alpha[p]] == 1) {
                        cnt++;
                    }
                }
                p++;
            }
        }
        q++;
    }
    return minLen;
}
int main() {
    string alpha = "BEGBBG";
    cout << "The size of the smallest substring to replace characters is - " << countSize(alpha);
    return 0;
}

Output

The size of the smallest substring to replace characters is - 1

Time complexity – O(N) as we traverse the string and use the sliding window technique.

Space complexity – O(1) as we use the constant space to store character frequency in the hashmap.

Programmers should make sure that the input string contains at most distinct characters. We used the map data structure to store extra characters, and based on that, we decided on the minimum length of the sliding window.

Updated on: 25-Aug-2023

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements