# Count Substrings with at least one occurrence of first K alphabet

• Last Updated : 12 Dec, 2022

Given a string S of size N and a positive integer K. The given string only consists of the first K English lowercase alphabets. The task is to find the number of substrings that contain at least one occurrence of all these K characters.

Examples:

Input: S = “abcabc”, K = 3
Output: 10
Explanation: The substrings containing at least one occurrence of the first three characters of English lowercase alphabets (a, b and c) are “abc”, “abca”, “abcab”, “abcabc”, “bca”, “bcab”, “bcabc”, “cab”, “cabc” and “abc”.

Input: S = “aaacb”, K = 4
Output: 0
Explanation: There is no substring that contains at least one occurrence of all first K characters of English lowercase alphabets (a, b, c and d)

## An approach using Hashing and Two-Pointer approach:

The idea is to keep a two-pointer say start and end at the beginning of the string.

For every start, we’ll find the first valid substring which starts from index start and ends at index end. As this is the first valid substring starting from start but we can also include rest of the character from end index because we already satisfied the minimum criteria of validity. So there would be (N – end) total valid string for this start index.

We’ll keep adding all these count into result and finally return the result.

Follow the steps below to implement the above idea:

• Initialize a map for keeping the frequency of characters
• Initialize a variable start = 0, end = 0, and result = 0.
• Do it while the end is less than the size of the given string
• Increment the frequency of character at the end.
• Check if the size of the map becomes K
• Initiate a while loop unless the map size is equal to K.
• Increment the value of the result by N – end, because (N – end) substrings satisfy the given condition
• Decrement the frequency count of characters at the start of the map
• Check if the frequency count of the character at the start of the map becomes 0.
• If true, then remove this character from the map as this character will no longer exist in the valid substring for the new value of start.
• Move the start pointer to right by incrementing its value by 1
• Shift the end pointer to right by incrementing its value by 1.
• Otherwise, Increment the end pointer by 1.
• Return the value of the result

Below is the implementation of the above approach.

## C++

```// C++ code to implement the approach

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

// Function to find the number of substrings
int numberOfSubstrings(string s, int K)
{
// Initialize a map for keeping
// frequency of characters
unordered_map<char, int> unmap;

// Initialize a variable start = 0,
// end = 0 and result = 0
int start = 0, end = 0, n = s.size(), result = 0;

// Do while end is less than size
// of given string
while (end < n) {

// Increment the frequency of
// character at end.
unmap[s[end]]++;

// Check if the size of
// map becomes K
if (unmap.size() == K) {

// Initiate a while loop
// unless map size is
// equals to K
while (unmap.size() == K) {

// Increment the value of
// result by n - end, because (n - end)
// substring are valid that satisfy the
// given condition
result += n - end;

// Decrement the frequency
// count of character at
// start from map
unmap[s[start]]--;

// Check if frequency count
// of character at start in
// map becomes 0.
// If true, then remove this
// character from the map
if (unmap[s[start]] == 0)
unmap.erase(s[start]);

// Move the start pointer
// to right by incrementing
// its value by 1
start++;
}

// Increment the end pointer.
end++;
}

// Otherwise, Increment
// the end pointer by 1.
else {
end++;
}
}

// Return the value of result
return result;
}

// Driver code
int main()
{
string S = "abcabc";
int K = 3;

// Function Call
cout << numberOfSubstrings(S, K);

return 0;
}```

## Java

```// Java code to implement the approach

import java.io.*;
import java.util.*;

class GFG {

// Function to find the number of substrings
static int numberOfSubstrings(String s, int K)
{
// Initialize a map for keeping
// frequency of characters
HashMap<Character, Integer> unmap = new HashMap<>();

// Initialize a variable start = 0,
// end = 0 and result = 0
int start = 0, end = 0, n = s.length(), result = 0;

// Do while end is less than size
// of given string
while (end < n) {
// Increment the frequency of
// character at end.
unmap.put(s.charAt(end),
unmap.getOrDefault(s.charAt(end), 0)
+ 1);

// Check if the size of
// map becomes K
if (unmap.size() == K) {

// Initiate a while loop
// unless map size is
// equals to K
while (unmap.size() == K) {

// Increment the value of
// result by n - end, because (n - end)
// substring are valid that satisfy the
// given condition
result += n - end;

// Decrement the frequency
// count of character at
// start from map
unmap.put(s.charAt(start),
unmap.get(s.charAt(start))
- 1);

// Check if frequency count
// of character at start in
// map becomes 0.
// If true, then remove this
// character from the map
if (unmap.get(s.charAt(start)) == 0) {
unmap.remove(s.charAt(start));
}

// Move the start pointer
// to right by incrementing
// its value by 1
start++;
}

// Increment the end pointer.
end++;
}

// Otherwise, Increment
// the end pointer by 1.
else {
end++;
}
}

// Return the value of result
return result;
}

public static void main(String[] args)
{
String S = "abcabc";
int K = 3;

// Function call
System.out.print(numberOfSubstrings(S, K));
}
}

// This code is contributed by lokesh```

## Python3

```#  Python code to implement the approach

#  Function to find the number of substrings
def numberOfSubstrings(s, K):

#  Initialize a map for keeping
#  frequency of characters
unmap = {}

#  Initialize a variable start = 0,
#  end = 0 and result = 0
start = 0
end = 0
n = len(s)
result = 0

#  Do while end is less than size
#  of given string
while (end < n):

#  Increment the frequency of
#  character at end.
unmap[s[end]] = unmap.get(s[end], 0)+1

#   Check if the size of
#   map becomes K
if len(unmap) == K:

#  Initiate a while loop
#  unless map size is
#  equals to K
while len(unmap) == K:

#  Increment the value of
#  result by n - end, because (n - end)
#  substring are valid that satisfy the
#  given condition
result += n-end

#  Decrement the frequency
#  count of character at
#  start from map
unmap[s[start]] -= 1

#  Check if frequency count
#  of character at start in
#  map becomes 0.
#  If true, then remove this
#  character from the map
if unmap[s[start]] == 0:
unmap.pop(s[start])

#  Move the start pointer
#  to right by incrementing
#  its value by 1
start += 1

#  Increment the end pointer.
end += 1

#  Otherwise, Increment
#  the end pointer by 1.
else:
end += 1

#  Return the value of result
return result

#  Driver code
S = "abcabc"
K = 3
print(numberOfSubstrings(S, K))

# This Code is Contributed By Vivek Maddeshiya```

## C#

```// C# code to implement the approach
using System;
using System.Collections.Generic;

public class GFG {

// Function to find the number of substrings
static int numberOfSubstrings(string s, int K)
{

// Initialize a map for keeping
// frequency of characters
Dictionary<char, int> unmap = new Dictionary<char, int>();

// Initialize a variable start = 0,
// end = 0 and result = 0
int start = 0, end = 0, n = s.Length, result = 0;

// Do while end is less than size
// of given string
while (end < n) {
// Increment the frequency of
// character at end.
if(unmap.ContainsKey(s[end])){
int temp = unmap[s[end]] + 1;
unmap[s[end]] = temp;
}
else{
unmap[s[end]] = 1;
}

// Check if the size of
// map becomes K
if (unmap.Count == K) {

// Initiate a while loop
// unless map size is
// equals to K
while (unmap.Count == K) {

// Increment the value of
// result by n - end, because (n - end)
// substring are valid that satisfy the
// given condition
result += n - end;

// Decrement the frequency
// count of character at
// start from map
unmap[s[start]] = unmap[s[start]] - 1;

// Check if frequency count
// of character at start in
// map becomes 0.
// If true, then remove this
// character from the map
if (unmap[s[start]] == 0) {
unmap.Remove(s[start]);
}

// Move the start pointer
// to right by incrementing
// its value by 1
start++;
}

// Increment the end pointer.
end++;
}

// Otherwise, Increment
// the end pointer by 1.
else {
end++;
}
}

// Return the value of result
return result;
}

static public void Main()
{

// Code
string S = "abcabc";
int K = 3;

// Function call
Console.Write(numberOfSubstrings(S, K));
}
}

// This code is contributed by lokeshmvs21```

## Javascript

```// Javascript code

function numberOfSubstrings(s, K)
{

// Initialize a map for keeping
// frequency of characters
let unmap = {};

// Initialize a variable start = 0,
// end = 0 and result = 0
let start = 0, end = 0, n = s.length, result = 0;

// Do while end is less than size
// of given string
while (end < n)
{

// Increment the frequency of
// character at end.
if (unmap[s[end]]) {
unmap[s[end]]++;
} else {
unmap[s[end]] = 1;
}
// Check if the size of
// map becomes K
if (Object.keys(unmap).length == K)
{

// Initiate a while loop
// unless map size is
// equals to K
while (Object.keys(unmap).length == K)
{

// Increment the value of
// result by n - end, because (n - end)
// substring are valid that satisfy the
// given condition
result += n - end;

// Decrement the frequency
// count of character at
// start from map
unmap[s[start]]--;

// Check if frequency count
// of character at start in
// map becomes 0.
// If true, then remove this
// character from the map
if (unmap[s[start]] == 0)
delete unmap[s[start]];

// Move the start pointer
// to right by incrementing
// its value by 1
start++;
}

// Increment the end pointer.
end++;
}

// Otherwise, Increment
// the end pointer by 1.
else {
end++;
}
}

// Return the value of result
return result;
}

// Driver code
console.log(numberOfSubstrings("abcabc", 3));

// This code is contributed by ksam24000```
Output

`10`

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

My Personal Notes arrow_drop_up
Related Articles