Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmCount of Substrings with at least K pairwise Distinct Characters having same...

Count of Substrings with at least K pairwise Distinct Characters having same Frequency

Given a string S and an integer K, the task is to find the number of substrings which consists of at least K pairwise distinct characters having same frequency.

Examples:

Input: S = “abasa”, K = 2 
Output:
Explanation: 
The substrings in having 2 pairwise distinct characters with same frequency are {“ab”, “ba”, “as”, “sa”, “bas”}.
Input: S = “abhay”, K = 3 
Output:
Explanation: 
The substrings having 3 pairwise distinct characters with same frequency are {“abh”, “bha”, “hay”, “bhay”}.

Naive Approach: The simplest approach to solve this problem is to generate all possible substrings of the given string and check if both the conditions are satisfied. If found to be true, increase count. Finally, print count.

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

Efficient Approach: To optimize the above approach, follow the steps below to solve the problem:

  • Check if the frequencies of each character is same. If found to be true, simply generate all the substrings to check if each character satisfies the condition of at least N pairwise distinct characters.
  • Precompute the frequencies of characters to check the conditions for each substring.

Below is the implementation of the above approach:

C++




// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the substring with K
// pairwise distinct characters and
// with same frequency
int no_of_substring(string s, int N)
{
    // Stores the occurrence of each
    // character in the substring
    int fre[26];
 
    int str_len;
 
    // Length of the string
    str_len = (int)s.length();
 
    int count = 0;
 
    // Iterate over the string
    for (int i = 0; i < str_len; i++) {
 
        // Set all values at each index to zero
        memset(fre, 0, sizeof(fre));
        int max_index = 0;
 
        // Stores the count of
        // unique characters
        int dist = 0;
 
        // Moving the substring ending at j
        for (int j = i; j < str_len; j++) {
 
            // Calculate the index of
            // character in frequency array
            int x = s[j] - 'a';
 
            if (fre[x] == 0)
                dist++;
 
            // Increment the frequency
            fre[x]++;
 
            // Update the maximum index
            max_index = max(max_index, fre[x]);
 
            // Check for both the conditions
            if (dist >= N && ((max_index * dist)
                              == (j - i + 1)))
                count++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
int main()
{
    string s = "abhay";
    int N = 3;
 
    // Function call
    cout << no_of_substring(s, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the subString with K
// pairwise distinct characters and
// with same frequency
static int no_of_subString(String s, int N)
{
     
    // Stores the occurrence of each
    // character in the subString
    int fre[] = new int[26];
 
    int str_len;
 
    // Length of the String
    str_len = (int)s.length();
 
    int count = 0;
 
    // Iterate over the String
    for(int i = 0; i < str_len; i++)
    {
         
        // Set all values at each index to zero
        Arrays.fill(fre, 0);
         
        int max_index = 0;
 
        // Stores the count of
        // unique characters
        int dist = 0;
 
        // Moving the subString ending at j
        for(int j = i; j < str_len; j++)
        {
             
            // Calculate the index of
            // character in frequency array
            int x = s.charAt(j) - 'a';
 
            if (fre[x] == 0)
                dist++;
 
            // Increment the frequency
            fre[x]++;
 
            // Update the maximum index
            max_index = Math.max(max_index, fre[x]);
 
            // Check for both the conditions
            if (dist >= N && ((max_index * dist) ==
                              (j - i + 1)))
                count++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "abhay";
    int N = 3;
 
    // Function call
    System.out.print(no_of_subString(s, N));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program to implement
# the above approach
 
# Function to find the substring with K
# pairwise distinct characters and
# with same frequency
def no_of_substring(s, N):
 
    # Length of the string
    str_len = len(s)
 
    count = 0
 
    # Iterate over the string
    for i in range(str_len):
 
        # Stores the occurrence of each
        # character in the substring
        # Set all values at each index to zero
        fre = [0] * 26
 
        max_index = 0
 
        # Stores the count of
        # unique characters
        dist = 0
 
        # Moving the substring ending at j
        for j in range(i, str_len):
 
            # Calculate the index of
            # character in frequency array
            x = ord(s[j]) - ord('a')
 
            if (fre[x] == 0):
                dist += 1
 
            # Increment the frequency
            fre[x] += 1
 
            # Update the maximum index
            max_index = max(max_index, fre[x])
 
            # Check for both the conditions
            if(dist >= N and
             ((max_index * dist) == (j - i + 1))):
                count += 1
 
    # Return the answer
    return count
 
# Driver Code
s = "abhay"
N = 3
 
# Function call
print(no_of_substring(s, N))
 
# This code is contributed by Shivam Singh


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the subString with K
// pairwise distinct characters and
// with same frequency
static int no_of_subString(String s, int N)
{
     
    // Stores the occurrence of each
    // character in the subString
    int []fre = new int[26];
 
    int str_len;
 
    // Length of the String
    str_len = (int)s.Length;
 
    int count = 0;
 
    // Iterate over the String
    for(int i = 0; i < str_len; i++)
    {
         
        // Set all values at each index to zero
        fre = new int[26];
         
        int max_index = 0;
 
        // Stores the count of
        // unique characters
        int dist = 0;
 
        // Moving the subString ending at j
        for(int j = i; j < str_len; j++)
        {
             
            // Calculate the index of
            // character in frequency array
            int x = s[j] - 'a';
 
            if (fre[x] == 0)
                dist++;
 
            // Increment the frequency
            fre[x]++;
 
            // Update the maximum index
            max_index = Math.Max(max_index, fre[x]);
 
            // Check for both the conditions
            if (dist >= N && ((max_index * dist) ==
                              (j - i + 1)))
                count++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
    String s = "abhay";
    int N = 3;
 
    // Function call
    Console.Write(no_of_subString(s, N));
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
 
// javascript program for the above approach
 
// Function to find the subString with K
// pairwise distinct characters and
// with same frequency
function no_of_subString(s , N)
{
     
    // Stores the occurrence of each
    // character in the subString
    var fre = Array.from({length: 26}, (_, i) => 0);
 
    var str_len;
 
    // Length of the String
    str_len = parseInt(s.length);
 
    var count = 0;
 
    // Iterate over the String
    for(i = 0; i < str_len; i++)
    {
         
        // Set all values at each index to zero
        fre = Array(26).fill(0);
         
        var max_index = 0;
 
        // Stores the count of
        // unique characters
        var dist = 0;
 
        // Moving the subString ending at j
        for(j = i; j < str_len; j++)
        {
             
            // Calculate the index of
            // character in frequency array
            var x = s.charAt(j).charCodeAt(0) - 'a'.charCodeAt(0);
 
            if (fre[x] == 0)
                dist++;
 
            // Increment the frequency
            fre[x]++;
 
            // Update the maximum index
            max_index = Math.max(max_index, fre[x]);
 
            // Check for both the conditions
            if (dist >= N && ((max_index * dist) ==
                              (j - i + 1)))
                count++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
var s = "abhay";
var N = 3;
 
// Function call
document.write(no_of_subString(s, N));
 
// This code contributed by shikhasingrajput
</script>


Output: 

4

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments