Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Length of smallest substring to be replaced to make frequency of each character as N/3

  • Last Updated : 21 Jan, 2022

Given a string str of length N (divisible by 3) consisting of atmost three distinct characters, the task is to find the length of the smallest substring whose characters can be replaced so that each character occurs exactly N/3 times.

Examples:

Input: str = “ABB”
Output: 1
Explanation: One optimal way is to replace the substring “B” with any character, suppose “C”. 
Hence, the resulting is “ABC” having frequency of each character as N/3.

Input: str = “ABCBBB”
Output:

 

Approach: The given problem can be solved using the sliding window technique. Since the frequency of each character should be N/3, hence the number of excess occurrences of the characters can be calculated. The idea is to find the length of the smallest substring such that it contains all the excess characters which can then be replaced. Below are the steps to follow:

Below is the implementation of above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
int balanceString(string str){
 
  int N = str.length();
 
  // If length of str is 0
  if (N == 0) {
    return 0;
  }
 
  // Stores the frequency of
  // each char in str
  map<char, int> strFreq;
 
  for (char c : str)
    strFreq++;
 
  // Stores the characters having
  // excess occurences with count
  map<char, int> extraChars;
 
  for (auto c : strFreq) {
 
    // If there are more than N/3
    // characters in the string str
    if (c.second > N / 3)
      extraChars = (c.second - N / 3);
  }
 
  // If no characters occurs more
  // than N/3 time in the string
  if (extraChars.size() == 0) {
    return 0;
  }
 
  // Represents start of the window,
  // end of the window and the
  // required answer respectivelly
  int i = 0, j = 0;
  int minWindowLength = N + 1;
 
  // Stores the number of unique
  // characters to in substring
  int count = extraChars.size();
 
  while (j < N) {
 
    // Store current character
    char c = str[j];
 
    // Check if c is an excess char
    if (extraChars.find(c) != extraChars.end()) {
 
      // Reduce Count
      extraChars--;
 
      // If window has the
      // required count
      if (extraChars == 0)
        count--;
    }
 
    // If current window has all char
    if (count == 0) {
 
      // Reduce Window size
      while (i < N && count == 0) {
 
        // Update the minimum
        // length of window
        minWindowLength = min(minWindowLength, j - i + 1);
 
        // If character at index
        // i is an excess char
        if (extraChars.find(str[i]) != extraChars.end()) {
 
          // Update frequency
          extraChars[str[i]]++;
 
          // Update Count
          if (extraChars[str[i]] == 1)
            count++;
        }
        i++;
      }
    }
 
    j++;
  }
 
  return minWindowLength;
}
 
// Driver Code
int main() {
 
  string str = "ABCBBB";
  cout << balanceString(str); 
  return 0;
}
 
// This code is contributed by hrithikgarg03188

Java




// Java code to implement above approach
import java.io.*;
import java.util.*;
 
class GFG {
    static int balanceString(String str)
    {
        int N = str.length();
 
        // If length of str is 0
        if (N == 0) {
            return 0;
        }
 
        // Stores the frequency of
        // each char in str
        HashMap<Character, Integer> strFreq
            = new HashMap<>();
 
        for (char c : str.toCharArray())
            strFreq.put(c,
                        strFreq.getOrDefault(c, 0)
                            + 1);
 
        // Stores the characters having
        // excess occurences with count
        HashMap<Character, Integer> extraChars
            = new HashMap<>();
 
        for (char c : strFreq.keySet()) {
 
            // If there are more than N/3
            // characters in the string str
            if (strFreq.get(c) > N / 3)
                extraChars.put(c,
                               strFreq.get(c)
                                   - N / 3);
        }
 
        // If no characters occurs more
        // than N/3 time in the string
        if (extraChars.size() == 0) {
            return 0;
        }
 
        // Represents start of the window,
        // end of the window and the
        // required answer respectivelly
        int i = 0, j = 0;
        int minWindowLength = N + 1;
 
        // Stores the number of unique
        // characters to in substring
        int count = extraChars.size();
 
        while (j < N) {
 
            // Store current character
            char c = str.charAt(j);
 
            // Check if c is an excess char
            if (extraChars.containsKey(c)) {
 
                // Reduce Count
                extraChars.put(c,
                               extraChars.get(c)
                                   - 1);
 
                // If window has the
                // required count
                if (extraChars.get(c) == 0)
                    count--;
            }
 
            // If current window has all char
            if (count == 0) {
 
                // Reduce Window size
                while (i < N && count == 0) {
 
                    // Update the minimum
                    // length of window
                    minWindowLength
                        = Math.min(minWindowLength,
                                   j - i + 1);
 
                    // If character at index
                    // i is an excess char
                    if (extraChars.containsKey(
                            str.charAt(i))) {
 
                        // Update frequency
                        extraChars.put(
                            str.charAt(i),
                            extraChars.get(
                                str.charAt(i))
                                + 1);
 
                        // Update Count
                        if (extraChars.get(
                                str.charAt(i))
                            == 1)
                            count++;
                    }
                    i++;
                }
            }
 
            j++;
        }
 
        return minWindowLength;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "ABCBBB";
        System.out.println(balanceString(str));
    }
}

Javascript




<script>
        // JavaScript code for the above approach
 
        function balanceString(str) {
            let N = str.length;
 
            // If length of str is 0
            if (N == 0) {
                return 0;
            }
 
            // Stores the frequency of
            // each char in str
            let strFreq
                = new Map();
            str = str.split('')
            for (let c of str) {
 
                if (strFreq.has(c))
                    strFreq.set(c,
                        strFreq.get(c)
                        + 1);
                else
                    strFreq.set(c, 1)
            }
 
            str = str.join('')
            // Stores the characters having
            // excess occurences with count
            let extraChars
                = new Map();
 
            for (let c of strFreq.keys()) {
 
                // If there are more than N/3
                // characters in the string str
                if (strFreq.get(c) > Math.floor(N / 3))
                    extraChars.set(c,
                        strFreq.get(c)
                        - Math.floor(N / 3));
            }
 
            // If no characters occurs more
            // than N/3 time in the string
            if (extraChars.size == 0) {
                return 0;
            }
 
            // Represents start of the window,
            // end of the window and the
            // required answer respectivelly
            let i = 0, j = 0;
            let minWindowLength = N + 1;
 
            // Stores the number of unique
            // characters to in substring
            let count = extraChars.size;
 
            while (j < N) {
 
                // Store current character
                let c = str.charAt(j);
 
                // Check if c is an excess char
                if (extraChars.has(c)) {
 
                    // Reduce Count
                    extraChars.set(c,
                        extraChars.get(c)
                        - 1);
 
                    // If window has the
                    // required count
                    if (extraChars.get(c) == 0)
                        count--;
                }
 
                // If current window has all char
                if (count == 0) {
 
                    // Reduce Window size
                    while (i < N && count == 0) {
 
                        // Update the minimum
                        // length of window
                        minWindowLength
                            = Math.min(minWindowLength,
                                j - i + 1);
 
                        // If character at index
                        // i is an excess char
                        if (extraChars.has(
                            str.charAt(i))) {
 
                            // Update frequency
                            extraChars.set(
                                str.charAt(i),
                                extraChars.get(
                                    str.charAt(i))
                                + 1);
 
                            // Update Count
                            if (extraChars.get(
                                str.charAt(i))
                                == 1)
                                count++;
                        }
                        i++;
                    }
                }
 
                j++;
            }
 
            return minWindowLength;
        }
 
        // Driver Code
 
        let str = "ABCBBB";
        document.write(balanceString(str));
 
         // This code is contributed by Potta Lokesh
    </script>
Output
2

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!