Count of substrings having all distinct characters
Last Updated :
14 Jan, 2022
Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.
Examples:
Input: Str = “gffg”
Output: 6
Explanation:
All possible substrings from the given string are,
( “g“, “gf“, “gff”, “gffg”, “f“, “ff”, “ffg”, “f“, “fg“, “g” )
Among them, the highlighted ones consists of distinct characters only.
Input: str = “gfg”
Output: 5
Explanation:
All possible substrings from the given string are,
( “g“, “gf“, “gfg”, “f“, “fg“, “g” )
Among them, the highlighted consists of distinct characters only.
Naive Approach:
The simplest approach is to generate all possible substrings from the given string and check for each substring whether it contains all distinct characters or not. If the length of string is N, then there will be N*(N+1)/2 possible substrings.
Time complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach:
The problem can be solved in linear time using Two Pointer Technique, with the help of counting frequencies of characters of the string.
Detailed steps for this approach are as follows:
- Consider two pointers i and j, initially both pointing to the first character of the string i.e. i = j = 0.
- Initialize an array Cnt[ ] to store the count of characters in substring from index i to j both inclusive.
- Now, keep on incrementing j pointer until some a repeated character is encountered. While incrementing j, add the count of all the substrings ending at jth index and starting at any index between i and j to the answer. All these substrings will contain distinct characters as no character is repeated in them.
- If some repeated character is encountered in substring between index i to j, to exclude this repeated character, keep on incrementing the i pointer until repeated character is removed and keep updating Cnt[ ] array accordingly.
- Continue this process until j reaches the end of string. Once the string is traversed completely, print the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long int countSub(string str)
{
int n = ( int )str.size();
long long int ans = 0;
int cnt[26];
memset (cnt, 0, sizeof (cnt));
int i = 0, j = 0;
while (i < n) {
if (j < n && (cnt[str[j] - 'a' ]
== 0)) {
cnt[str[j] - 'a' ]++;
ans += (j - i + 1);
j++;
}
else {
cnt[str[i] - 'a' ]--;
i++;
}
}
return ans;
}
int main()
{
string str = "gffg" ;
cout << countSub(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSub(String str)
{
int n = ( int )str.length();
int ans = 0 ;
int []cnt = new int [ 26 ];
int i = 0 , j = 0 ;
while (i < n)
{
if (j < n &&
(cnt[str.charAt(j) - 'a' ] == 0 ))
{
cnt[str.charAt(j) - 'a' ]++;
ans += (j - i + 1 );
j++;
}
else
{
cnt[str.charAt(i) - 'a' ]--;
i++;
}
}
return ans;
}
public static void main(String[] args)
{
String str = "gffg" ;
System.out.print(countSub(str));
}
}
|
Python3
def countSub( Str ):
n = len ( Str )
ans = 0
cnt = 26 * [ 0 ]
i, j = 0 , 0
while (i < n):
if (j < n and
(cnt[ ord ( Str [j]) - ord ( 'a' )] = = 0 )):
cnt[ ord ( Str [j]) - ord ( 'a' )] + = 1
ans + = (j - i + 1 )
j + = 1
else :
cnt[ ord ( Str [i]) - ord ( 'a' )] - = 1
i + = 1
return ans
Str = "gffg"
print (countSub( Str ))
|
C#
using System;
class GFG{
static int countSub(String str)
{
int n = ( int )str.Length;
int ans = 0;
int []cnt = new int [26];
int i = 0, j = 0;
while (i < n)
{
if (j < n &&
(cnt[str[j] - 'a' ] == 0))
{
cnt[str[j] - 'a' ]++;
ans += (j - i + 1);
j++;
}
else
{
cnt[str[i] - 'a' ]--;
i++;
}
}
return ans;
}
public static void Main(String[] args)
{
String str = "gffg" ;
Console.Write(countSub(str));
}
}
|
Javascript
<script>
function countSub(str)
{
var n = str.length;
var ans = 0;
var cnt = Array(26).fill(0);
var i = 0, j = 0;
while (i < n) {
if (j < n && (cnt[str[j].charCodeAt(0) - 'a' .charCodeAt(0)]
== 0)) {
cnt[str[j].charCodeAt(0) - 'a' .charCodeAt(0)]++;
ans += (j - i + 1);
j++;
}
else {
cnt[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]--;
i++;
}
}
return ans;
}
var str = "gffg" ;
document.write( countSub(str));
</script>
|
Time complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...