Count substrings with each character occurring at most k times
Last Updated :
23 Mar, 2023
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets.
Examples:
Input : S = ab
k = 1
Output : 3
All the substrings a, b, ab have
individual character count less than 1.
Input : S = aaabb
k = 2
Output : 12
Substrings that have individual character
count at most 2 are: a, a, a, b, b, aa, aa,
ab, bb, aab, abb, aabb.
Brute Force Approach:
A simple solution is to first find all the substrings and then check if the count of each character is at most k in each substring. The time complexity of this solution is O(n^3). We can check all the possible substrings ranges from i to j and in this substring we have to check whether the maximum frequency is greater than k or not.if it is less than or equal to k then count this substring in ans .
C++
// CPP program to count number of substrings
// in which each character has count less
// than or equal to k.
#include <bits/stdc++.h>
using namespace std;
int findSubstrings(string s, int k)
{
//
int i, j, n = s.length();
// variable to store count of substrings.
// Total non empty substring n*(n+1) /2.
int ans = n * (n + 1) / 2;
for (i = 0; i < n; i++) {
for (j = i; j < n; j++) {
bool flag = false;
// hash map storing maximum frequency of each
// character.
unordered_map<int, int> m;
for (int l = i; l <= j; l++) {
m[s[l]]++;
if (m[s[l]] > k) {
ans--;
break;
flag = true;
}
}
}
}
// return the final count of substrings.
return ans;
}
// Driver code
int main()
{
string S = "aaabb";
int k = 2;
cout << findSubstrings(S, k);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
// java code addition
public class Main {
// Javat program to count number of substrings
// in which each character has count less
// than or equal to k.
public static int findSubstrings(String s,int k) {
int n = s.length();
// variable to store count of substrings.
// Total non empty substring n*(n+1) /2.
int ans = (int)Math.floor((n * (n + 1)) / 2);
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
boolean flag = false;
// hash map storing maximum frequency of each
// character.
Map<Character,Integer> m=new HashMap<Character,Integer>();
for (int l = i; l <= j; l++) {
if(m.containsKey(s.charAt(l))){
m.put(s.charAt(l), m.get(s.charAt(l)) + 1);
}
else{
m.put(s.charAt(l), 1);
}
if (m.get(s.charAt(l)) > k) {
ans--;
break;
}
}
if (flag) {
break;
}
}
}
// return the final count of substrings.
return ans;
}
public static void main(String[] args) {
String S = "aaabb";
int k = 2;
System.out.println(findSubstrings(S, k));
}
}
// The code is contributed by Arushi Jindal.
Python3
# Python program to count number of substrings
# in which each character has count less
# than or equal to k.
def find_substrings(s, k):
# Get the length of the string
n = len(s)
# Initialize the variable to store the count of substrings
ans = n * (n + 1) // 2
# Iterate through all possible substrings
for i in range(n):
for j in range(i, n):
# Initialize a frequency list to store the count of each character
freq = [0] * 26
# Count the frequency of each character in the current substring
for l in range(i, j + 1):
freq[ord(s[l]) - ord('a')] += 1
# If any character occurs more than k times, subtract 1 from the count of substrings
if max(freq) > k:
ans -= 1
break
# Return the final count of substrings
return ans
# Example usage
S = "aaabb"
k = 2
print(find_substrings(S, k)) # Output: 12
C#
using System;
using System.Collections.Generic;
public class Gfg
{
public static int findSubstrings(string s, int k)
{
int n = s.Length;
int ans = n * (n + 1) / 2;
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
bool flag = false;
Dictionary<char, int> m = new Dictionary<char, int>();
for (int l = i; l <= j; l++)
{
if (m.ContainsKey(s[l]))
m[s[l]]++;
else
m[s[l]] = 1;
if (m[s[l]] > k)
{
ans--;
break;
flag = true;
}
}
if (flag)
break;
}
}
return ans;
}
public static void Main()
{
string S = "aaabb";
int k = 2;
Console.WriteLine(findSubstrings(S, k));
}
}
JavaScript
// JavaScript program to count number of substrings
// in which each character has count less
// than or equal to k.
function findSubstrings(s, k) {
const n = s.length;
// variable to store count of substrings.
// Total non empty substring n*(n+1) /2.
let ans = Math.floor((n * (n + 1)) / 2);
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let flag = false;
// hash map storing maximum frequency of each
// character.
const m = new Map();
for (let l = i; l <= j; l++) {
m.set(s[l], (m.get(s[l]) || 0) + 1);
if (m.get(s[l]) > k) {
ans--;
break;
flag = true;
}
}
if (flag) {
break;
}
}
}
// return the final count of substrings.
return ans;
}
const S = 'aaabb';
const k = 2;
console.log(findSubstrings(S, k));
Time Complexity:O(N3), where N is the length of the string
Space Complexity : O(N), where N is the length of the string
An efficient solution is to maintain starting and ending point of substrings. Let us fix the starting point to an index i. Keep incrementing the ending point j one at a time. When changing the ending point update the count of corresponding character. Then check for this substring that whether each character has count at most k or not. If yes then increment answer by 1 else increment the starting point and reset ending point.
The starting point is incremented because during last update on ending point character count exceed k and it will only increase further. So no subsequent substring with given fixed starting point will be a substring with each character count at most k.
Implementation:
C++
// CPP program to count number of substrings
// in which each character has count less
// than or equal to k.
#include <bits/stdc++.h>
using namespace std;
int findSubstrings(string s, int k)
{
// variable to store count of substrings.
int ans = 0;
// array to store count of each character.
int cnt[26];
int i, j, n = s.length();
for (i = 0; i < n; i++) {
// Initialize all characters count to zero.
memset(cnt, 0, sizeof(cnt));
for (j = i; j < n; j++) {
// increment character count
cnt[s[j] - 'a']++;
// check only the count of current character
// because only the count of this
// character is changed. The ending point is
// incremented to current position only if
// all other characters have count at most
// k and hence their count is not checked.
// If count is less than k, then increase ans
// by 1.
if (cnt[s[j] - 'a'] <= k)
ans++;
// if count is less than k, then break as
// subsequent substrings for this starting
// point will also have count greater than
// k and hence are reduntant to check.
else
break;
}
}
// return the final count of substrings.
return ans;
}
// Driver code
int main()
{
string S = "aaabb";
int k = 2;
cout << findSubstrings(S, k);
return 0;
}
Java
import java.util.Arrays;
// Java program to count number of substrings
// in which each character has count less
// than or equal to k.
class GFG {
static int findSubstrings(String s, int k) {
// variable to store count of substrings.
int ans = 0;
// array to store count of each character.
int cnt[] = new int[26];
int i, j, n = s.length();
for (i = 0; i < n; i++) {
// Initialize all characters count to zero.
Arrays.fill(cnt, 0);
for (j = i; j < n; j++) {
// increment character count
cnt[s.charAt(j) - 'a']++;
// check only the count of current character
// because only the count of this
// character is changed. The ending point is
// incremented to current position only if
// all other characters have count at most
// k and hence their count is not checked.
// If count is less than k, then increase ans
// by 1.
if (cnt[s.charAt(j) - 'a'] <= k) {
ans++;
} // if count is less than k, then break as
// subsequent substrings for this starting
// point will also have count greater than
// k and hence are reduntant to check.
else {
break;
}
}
}
// return the final count of substrings.
return ans;
}
// Driver code
static public void main(String[] args) {
String S = "aaabb";
int k = 2;
System.out.println(findSubstrings(S, k));
}
}
// This code is contributed by 29AjayKumar
Python 3
# Python 3 program to count number of substrings
# in which each character has count less
# than or equal to k.
def findSubstrings(s, k):
# variable to store count of substrings.
ans = 0
n = len(s)
for i in range(n):
# array to store count of each character.
cnt = [0] * 26
for j in range(i, n):
# increment character count
cnt[ord(s[j]) - ord('a')] += 1
# check only the count of current character
# because only the count of this
# character is changed. The ending point is
# incremented to current position only if
# all other characters have count at most
# k and hence their count is not checked.
# If count is less than k, then increase
# ans by 1.
if (cnt[ord(s[j]) - ord('a')] <= k):
ans += 1
# if count is less than k, then break as
# subsequent substrings for this starting
# point will also have count greater than
# k and hence are reduntant to check.
else:
break
# return the final count of substrings.
return ans
# Driver code
if __name__ == "__main__":
S = "aaabb"
k = 2
print(findSubstrings(S, k))
# This code is contributed by ita_c
C#
// C# program to count number of substrings
// in which each character has count less
// than or equal to k.
using System;
class GFG
{
public static int findSubstrings(string s, int k)
{
// variable to store count of substrings.
int ans = 0;
// array to store count of each character.
int []cnt = new int[26];
int i, j, n = s.Length;
for (i = 0; i < n; i++)
{
// Initialize all characters count to zero.
Array.Clear(cnt, 0, cnt.Length);
for (j = i; j < n; j++)
{
// increment character count
cnt[s[j] - 'a']++;
// check only the count of current character
// because only the count of this
// character is changed. The ending point is
// incremented to current position only if
// all other characters have count at most
// k and hence their count is not checked.
// If count is less than k, then increase ans
// by 1.
if (cnt[s[j] - 'a'] <= k)
ans++;
// if count is less than k, then break as
// subsequent substrings for this starting
// point will also have count greater than
// k and hence are reduntant to check.
else
break;
}
}
// return the final count of substrings.
return ans;
}
// Driver code
public static int Main()
{
string S = "aaabb";
int k = 2;
Console.WriteLine(findSubstrings(S, k));
return 0;
}
}
// This code is contributed by SoM15242.
JavaScript
<script>
// Javascript program to count number of substrings
// in which each character has count less
// than or equal to k.
function findSubstrings(s, k)
{
// variable to store count of substrings.
var ans = 0;
// array to store count of each character.
var cnt = Array(26);
var i, j, n = s.length;
for (i = 0; i < n; i++) {
cnt = Array(26).fill(0);
for (j = i; j < n; j++) {
// increment character count
cnt[(s[j].charCodeAt(0) - 'a'.charCodeAt(0))]++;
// check only the count of current character
// because only the count of this
// character is changed. The ending point is
// incremented to current position only if
// all other characters have count at most
// k and hence their count is not checked.
// If count is less than k, then increase ans
// by 1.
if (cnt[(s[j].charCodeAt(0) - 'a'.charCodeAt(0))] <= k)
ans++;
// if count is less than k, then break as
// subsequent substrings for this starting
// point will also have count greater than
// k and hence are reduntant to check.
else
break;
}
}
// return the final count of substrings.
return ans;
}
// Driver code
var S = "aaabb";
var k = 2;
document.write( findSubstrings(S, k));
// This code is contributed by rrrtnx.
</script>
Time complexity: O(n^2)
Auxiliary Space: O(1)
Another efficient solution is to use sliding window technique. In which we will maintain two pointers left and right.We initialize left and the right pointer to 0, move the right pointer until the count of each alphabet is less than k, when the count is greater than we start incrementing left pointer and decrement the count of the corresponding alphabet, once the condition is satisfied we add (right-left + 1) to the answer.
Implementation:
C++
// CPP program to count number of substrings
// in which each character has count less
// than or equal to k.
#include<bits/stdc++.h>
using namespace std;
//function to find number of substring
//in which each character has count less
// than or equal to k.
int find_sub(string s,int k){
int len=s.length();
int lp=0,rp=0; // initialize left and right pointer to 0
int ans=0;
int hash_char[26]={0}; // an array to keep track of count of each alphabet
for(;rp<len;rp++){
hash_char[s[rp]-'a']++;
while(hash_char[s[rp]-'a']>k){
hash_char[s[lp]-'a']--; // decrement the count
lp++; //increment left pointer
}
ans+=rp-lp+1;
}
return ans;
}
// Driver code
int main(){
string s="aaabb";
int k=2;
cout<<find_sub(s,k)<<endl;
}
Java
// Java program to count number of substrings
// in which each character has count less
// than or equal to k.
class GFG
{
//function to find number of substring
//in which each character has count less
// than or equal to k.
static int find_sub(String s, int k)
{
int len = s.length();
// initialize left and right pointer to 0
int lp = 0, rp = 0;
int ans = 0;
// an array to keep track of count of each alphabet
int[] hash_char = new int[26];
for (; rp < len; rp++)
{
hash_char[s.charAt(rp) - 'a']++;
while (hash_char[s.charAt(rp) - 'a'] > k)
{
// decrement the count
hash_char[s.charAt(lp) - 'a']--;
//increment left pointer
lp++;
}
ans += rp - lp + 1;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String S = "aaabb";
int k = 2;
System.out.println(find_sub(S, k));
}
}
// This code is contributed by PrinciRaj1992
Python
# Python3 program to count number of substrings
# in which each character has count less
# than or equal to k.
# function to find number of substring
# in which each character has count less
# than or equal to k.
def find_sub(s, k):
Len = len(s)
# initialize left and right pointer to 0
lp, rp = 0, 0
ans = 0
# an array to keep track of count of each alphabet
hash_char = [0 for i in range(256)]
for rp in range(Len):
hash_char[ord(s[rp])] += 1
while(hash_char[ord(s[rp])] > k):
hash_char[ord(s[lp])] -= 1 # decrement the count
lp += 1 #increment left pointer
ans += rp - lp + 1
return ans
# Driver code
s = "aaabb"
k = 2;
print(find_sub(s, k))
# This code is contributed by mohit kumar
C#
// C# program to count number of substrings
// in which each character has count less
// than or equal to k.
using System;
class GFG
{
//function to find number of substring
//in which each character has count less
// than or equal to k.
static int find_sub(string s, int k)
{
int len = s.Length;
// initialize left and right pointer to 0
int lp = 0,rp = 0;
int ans = 0;
// an array to keep track of count of each alphabet
int []hash_char = new int[26];
for(;rp < len; rp++)
{
hash_char[s[rp] - 'a']++;
while(hash_char[s[rp] - 'a'] > k)
{
// decrement the count
hash_char[s[lp] - 'a']--;
//increment left pointer
lp++;
}
ans += rp - lp + 1;
}
return ans;
}
// Driver code
static public void Main()
{
String S = "aaabb";
int k = 2;
Console.WriteLine(find_sub(S, k));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to count number of substrings
// in which each character has count less
// than or equal to k.
//function to find number of substring
//in which each character has count less
// than or equal to k.
function find_sub(s,k)
{
let len = s.length;
// initialize left and right pointer to 0
let lp = 0, rp = 0;
let ans = 0;
// an array to keep track of count of each alphabet
let hash_char = new Array(26);
for(let i = 0; i < hash_char.length; i++)
{
hash_char[i] = 0;
}
for (; rp < len; rp++)
{
hash_char[s[rp].charCodeAt(0) - 'a'.charCodeAt(0)]++;
while (hash_char[s[rp].charCodeAt(0) - 'a'.charCodeAt(0)] > k)
{
// decrement the count
hash_char[s[lp].charCodeAt(0) - 'a'.charCodeAt(0)]--;
//increment left pointer
lp++;
}
ans += rp - lp + 1;
}
return ans;
}
// Driver code
let S = "aaabb";
let k = 2;
document.write(find_sub(S, k));
// This code is contributed by avanitrachhadiya2155
</script>
Time complexity: O(n)
Auxiliary Space: O(1)
Count substrings with each character occurring at most k times
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem