VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-distinct-characters-in-distinct-substrings-of-a-string/

⇱ Find distinct characters in distinct substrings of a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find distinct characters in distinct substrings of a string

Last Updated : 12 Jul, 2025

Given a string str, the task is to find the count of distinct characters in all the distinct sub-strings of the given string.
Examples: 
 

Input: str = "ABCA" 
Output: 18 
 

Distinct sub-stringsDistinct characters
A1
AB2
ABC3
ABCA3
B1
BC2
BCA3
C1
CA2


Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18
Input: str = "AAAB" 
Output: 10 
 


 


Approach: Take all possible sub-strings of the given string and use a set to check whether the current sub-string has been processed before. Now, for every distinct sub-string, count the distinct characters in it (again set can be used to do so). The sum of this count for all the distinct sub-strings is the final answer.
Below is the implementation of the above approach: 
 


Output: 
18

 

Time complexity: O(n^2) 

As the nested loop is used the complexity is order if n^2

Space complexity: O(n)

two sets of size n are used so the complexity would be O(2n) nothing but O(n).

Comment