# given a string s and a number k, find the number of substrings of length k such that each character in the substring is present only once.

### Mohammed

Guys, does anyone know the answer?

get given a string s and a number k, find the number of substrings of length k such that each character in the substring is present only once. from screen.

## string

Source: https://www.geeksforgeeks.org/number-substrings-count-character-k/ Given a string and an integer k, find number of substrings in which all the different characters occurs exactly k times.

## Number of substrings with count of each character as k

Ask Question

Asked 2 years, 6 months ago

Modified 1 year ago Viewed 15k times -1

Source: https://www.geeksforgeeks.org/number-substrings-count-character-k/

Given a string and an integer k, find number of substrings in which all the different characters occurs exactly k times.

Looking for a solution in O(n), using two pointers/sliding window approach. I'm able to find only longest substrings satisfying this criteria but not substrings within that long substring.

For ex: ababbaba, k = 2

My solution finds abab, ababba etc, but not bb within ababba.

Can someone help me with the logic?

stringdata-structuressubstring

Share

Improve this question

edited Jun 12, 2020 at 18:13

asked Jun 12, 2020 at 17:55

NewDev 511 1 gold badge 2 2 silver badges 7 7 bronze badges

Also, would like to know if this can be done in O(n) or need O(n2) algorithm –

NewDev

Jun 12, 2020 at 18:07

Add a comment

## 7 Answers

5

If you could edit your question to include your solution code, I'd be happy to help you with that.

For now **I'm sharing my solution code (in java) which runs in O(n2)**. I've added enough comments to make the code self explanatory. Nonetheless the logic for the solution is as follows:

As you correctly pointed out, the problem can be solved using sliding window approach (with variable window size). The solution below considers all possible sub-strings, using nested for loops for setting start and end indices. For each sub-string, we check if every element in the sub-string occurs exactly k times.

To avoid recalculating the count for every sub-string, we maintain the count in a map, and keep putting new elements in the map as we increment the end index (slide the window). This ensures that our solution runs in O(n2) and not O(n3).

To further improve efficiency, we only check the count of individual elements if the sub-string's size matches our requirement. e.g. for n unique elements (keys in the map), the size of required sub-string would be n*k. If the sub-string's size doesn't match this value, there's no need to check how many times the individual characters occur.

import java.util.*; /**

* Java program to count the number of perfect substrings in a given string. A

* substring is considered perfect if all the elements within the substring

* occur exactly k number of times.

* * @author Codextor */

public class PerfectSubstring {

public static void main(String[] args) {

String s = "aabbcc";

int k = 2;

System.out.println(perfectSubstring(s, k));

s = "aabccc"; k = 2;

System.out.println(perfectSubstring(s, k));

} /**

* Returns the number of perfect substrings in the given string for the

* specified value of k

*

* @param s The string to check for perfect substrings

* @param k The number of times every element should occur within the substring

* @return int The number of perfect substrings

*/

public static int perfectSubstring(String s, int k) {

int finalCount = 0; /*

* Set the initial starting index for the subarray as 0, and increment it with

* every iteration, till the last index of the string is reached.

*/

for (int start = 0; start < s.length(); start++) {

/*

* Use a HashMap to store the count of every character in the subarray. We'll

* start with an empty map everytime we update the starting index

Map*/

/*

* Set the initial ending index for the subarray equal to the starting index and

* increment it with every iteration, till the last index of the string is

* reached. */

for (int end = start; end < s.length(); end++) {

/*

* Get the count of the character at end index and increase it by 1. If the

* character is not present in the map, use 0 as the default count

*/

char c = s.charAt(end);

int count = frequencyMap.getOrDefault(c, 0);

frequencyMap.put(c, count + 1);

/*

* Check if the length of the subarray equals the desired length. The desired

* length is the number of unique characters we've seen so far (size of the map)

* multilied by k (the number of times each character should occur). If the

* length is as per requiremets, check if each element occurs exactly k times

*/

if (frequencyMap.size() * k == (end - start + 1)) {

if (check(frequencyMap, k)) {

finalCount++; } } } } return finalCount; } /**

* Returns true if every value in the map is equal to k

*

* @param map The map whose values are to be checked

* @param k The required value for keys in the map

* @return true if every value in the map is equal to k

public static boolean check(Map*/

/*

* Iterate through all the values (frequency of each character), comparing them

* with k */

for (Integer i : map.values()) {

if (i != k) { return false; } } return true; } } Share Improve this answer

## How many substrings can be formed from a character string of length n?

Answer (1 of 9): Let us solve this problem in segments. let the string be 1234. The substring of lenght 1 is 1, 2, 3, and 4. The substring of lenght 2 is 12, 23, 34. The substring of length 3 is 123, 234. and at last substring of lenght 4 is 1234. so it is simply 4 + 3 + 2 + 1. Or you can say n*(...

How many substrings can be formed from a character string of length n?

Ad by Adclickersbot

Make Money Easy And Safe Way.

Adclickersbot is a Telegram earning platform that allows you to earn money by performing simple tasks.

Sort

Leticia Lorena Rodriguez

Studied Computer Science at University of Buenos Aires5y

Originally Answered: how many substrings can be formed from a character string of length n ?

To solve this problem, we can first think in: “how many substrings of length 1 can be formed from a character string of length n?”

It’s a simple answer. If we take step of 1 character, we can from n substrings from the original string (we are going to call it s).

For example, if s = “abcde”, s with length n = 5, we can form these substrings of length 1 : “a”, “b”, “c”, “d”, “e” (5). So, we formed n substrings.

But in the original question, we want to know how many substrings of any length. This answer is not enough.

Let see how many substrings of length 2 can be formed. We are going to take 1 char

Related questions

How many substrings of "aabbbccdd" can be formed?

How do I find the number of occurrences of all the distinct substrings of a string?

How many substrings and k-length substrings are conceivable from an n-length string?

Given a string, how can I find all substrings of length N (that should be taken as input) in that string?

How do I generate all possible substrings of a string?

Satyarth Agrahari

Former SDE at Amazon (company) (2019–2021)Author has 111 answers and 263.3K answer views6y

Originally Answered: how many substrings can be formed from a character string of length n ?

Let us solve this problem in segments. let the string be 1234. The substring of lenght 1 is 1, 2, 3, and 4. The substring of lenght 2 is 12, 23, 34. The substring of length 3 is 123, 234. and at last substring of lenght 4 is 1234. so it is simply 4 + 3 + 2 + 1. Or you can say n*(n+1) / 2 where n is lenght of string

Sponsored by Aspose

What is Aspose.OCR for C++ library?

OCR API capable of extracting text from BMP, JPEG and other images having different fonts and styles.

Varun Sharma

Data EnthusiastAuthor has 485 answers and 150.4K answer viewsMay 31

How many substrings can be formed from a character string of length n? Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = “abcb”, K = 2, charArray[] = {‘a’, ‘b’} Output: 4 Explanation: The substrings are “a”, “ab”, “b”, “b” using the available charactersInput: S = “aabdbbtr”, K = 4, charArray[] = {‘e’, ‘a’, ‘r’, ‘t’} Output: 6 Explanation: The substrings “a”, “aa”, “a”, “t”, “tr”, “r”

Ramakant Chhangani

B.Tech in Cse from Shri Ramdeobaba College of Engineering and Management, NagpurAuthor has 249 answers and 284.4K answer views2y

Take the example of the string “abcd”.The substrings forming will be a b c d ab abc abcd bc bcd cd i.e 4*(4+1)/2 . Similarily, if we take n as the string length no. Of strings formed will be n*(n+1)/2.

Related questions

Given a string, how do I find the number of distinct substrings of the string?

If A/B = 10, B * C = 50, and C/ A = 0.2, what is A + B +C?

Given a number N (length of the string) and a set of characters ('A', 'B' and 'C'), find the number of strings possible if each character occurs at least once in the string. How do you do it?

Find the integers m and n, solution of 1102m + 399n=19?

What is the length of a substring in C++?

Visvam Jaganathan

Software Engineer at Growfin.ai (2021–present)Author has 129 answers and 175K answer views4y

Originally Answered: how many substrings can be formed from a character string of length n ?

There is a formula for finding substring count .

Say the length of string is a=7

Then, length=(a*(a+1))/2

which is (7*6)/2=21

Your response is private

Was this worth your time?

This helps us sort answers on the page.

Absolutely not Definitely yes JetBrains

The drive to developApr 15

Promoted

What are the most popular software development tools?

There are many good software development tools available on the market right now, but the problem is that none of them integrate the complete toolchain for the software development pipeline with organizational and communication tools. Using different tools often creates silos, leading to miscommunication, less efficient collaboration, and a loss of information. JetBrains decided to solve this problem and created a single platform, Space, for the entire development pipeline and communication process.

JetBrains Space

is a unified platform that covers the entire software development pipeline, from

Sumit Gaurav Former Student4y

Originally Answered: how many substrings can be formed from a character string of length n ?

it will be 1(for string of length n)+2(for string of length n-1)+3…….+n(for 1 element sub string)=n*(n-1)/2;

Amarnath Karthi

Second year Computer Science student at DA-IICT6y

Originally Answered: how many substrings can be formed from a character string of length n ?

In the simplest case, if all characters are distinct one can form

## Number of substrings with count of each character as k

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

## Number of substrings with count of each character as k

Difficulty Level : Easy

Last Updated : 12 Dec, 2022

Read Discuss(8) Courses Practice Video

Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times.

**Examples:**

**Input :**s = "aabbcc"

k = 2

**Output :**6

The substrings are aa, bb, cc,

aabb, bbcc and aabbcc.

**Input :**s = "aabccc"

k = 2 Output : 3

There are three substrings aa,

cc and cc

Recommended: Please try your approach on first, before moving on to the solution.

**Naive Approach:**The idea is to traverse through all substrings. We fix a starting point, traverse through all substrings starting with the picked point, we keep incrementing frequencies of all characters. If all frequencies become k, we increment the result. If the count of any frequency becomes more than k, we break and change starting point.

Below is the implementation of the above approach:

## C++

// C++ program to count number of substrings

// with counts of distinct characters as k.

#includeusing namespace std;

const int MAX_CHAR = 26;

// Returns true if all values

// in freq[] are either 0 or k.

bool check(int freq[], int k)

{

for (int i = 0; i < MAX_CHAR; i++)

if (freq[i] && freq[i] != k)

return false; return true; }

// Returns count of substrings where frequency

// of every present character is k

int substrings(string s, int k)

{

int res = 0; // Initialize result

// Pick a starting point

for (int i = 0; s[i]; i++) {

// Initialize all frequencies as 0

// for this starting point

int freq[MAX_CHAR] = { 0 };

// One by one pick ending points

for (int j = i; s[j]; j++) {

// Increment frequency of current char

int index = s[j] - 'a';

freq[index]++;

// If frequency becomes more than

// k, we can't have more substrings

// starting with i

if (freq[index] > k)

break;

// If frequency becomes k, then check

// other frequencies as well.

else if (freq[index] == k &&

check(freq, k) == true)

res++; } } return res; } // Driver code int main() {

string s = "aabbcc";

int k = 2;

cout << substrings(s, k) << endl;

s = "aabbc"; k = 2;

cout << substrings(s, k) << endl;

}

## Java

// Java program to count number of substrings

// with counts of distinct characters as k.

import java.io.*; class GFG {

static int MAX_CHAR = 26;

// Returns true if all values

// in freq[] are either 0 or k.

static boolean check(int freq[], int k)

{

for (int i = 0; i < MAX_CHAR; i++)

if (freq[i] !=0 && freq[i] != k)

return false; return true; }

// Returns count of substrings where frequency

// of every present character is k

static int substrings(String s, int k)

{

int res = 0; // Initialize result

// Pick a starting point

for (int i = 0; i< s.length(); i++)

{

// Initialize all frequencies as 0

// for this starting point

int freq[] = new int[MAX_CHAR];

// One by one pick ending points

for (int j = i; j{

// Increment frequency of current char

int index = s.charAt(j) - 'a';

freq[index]++;

// If frequency becomes more than

// k, we can't have more substrings

// starting with i

if (freq[index] > k)

break;

// If frequency becomes k, then check

// other frequencies as well.

else if (freq[index] == k &&

check(freq, k) == true)

res++; } } return res; } // Driver code

public static void main(String[] args)

{

String s = "aabbcc";

int k = 2;

System.out.println(substrings(s, k));

s = "aabbc"; k = 2;

System.out.println(substrings(s, k));

} }

// This code has been contributed by 29AjayKumar

## Python3

# Python3 program to count number of substrings

# with counts of distinct characters as k.

MAX_CHAR = 26

# Returns true if all values

# in freq[] are either 0 or k.

def check(freq, k):

for i in range(0, MAX_CHAR):

if(freq[i] and freq[i] != k):

return False return True

# Returns count of substrings where

# frequency of every present character is k

def substrings(s, k):

res = 0 # Initialize result

# Pick a starting point

for i in range(0, len(s)):

# Initialize all frequencies as 0

# for this starting point

freq = [0] * MAX_CHAR

# One by one pick ending points

for j in range(i, len(s)):

# Increment frequency of current char

index = ord(s[j]) - ord('a')

freq[index] += 1

# If frequency becomes more than

# k, we can't have more substrings

# starting with i

if(freq[index] > k):

break

# If frequency becomes k, then check

# other frequencies as well

elif(freq[index] == k and

check(freq, k) == True):

res += 1 return res # Driver Code

if __name__ == "__main__":

Guys, does anyone know the answer?