![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
6
Time complexity: O(N)
Auxiliary Space: O(1)