Find distinct characters in distinct substrings of a string - GeeksforGeeks

07 Sep, 2021
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  
Hence, 1 + 2 + 3 + 3 + 1 + 2 + 3 + 1 + 2 = 18Input: 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:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringint countTotalDistinct(string str){    int cnt = 0;     // To store all the sub-strings    set<string> items;     for (int i = 0; i < str.length(); ++i) {         // To store the current sub-string        string temp = "";         // To store the characters of the        // current sub-string        set<char> ans;        for (int j = i; j < str.length(); ++j) {            temp = temp + str[j];            ans.insert(str[j]);             // If current sub-string hasn't            // been stored before            if (items.find(temp) == items.end()) {                 // Insert it into the set                items.insert(temp);                 // Update the count of                // distinct characters                cnt += ans.size();            }        }    }     return cnt;} // Driver codeint main(){    string str = "ABCA";     cout << countTotalDistinct(str);     return 0;}
// Java implementation of the approachimport java.util.HashSet; class geeks{     // Function to return the count of distinct    // characters in all the distinct    // sub-strings of the given string    public static int countTotalDistinct(String str)    {        int cnt = 0;         // To store all the sub-strings        HashSet<String> items = new HashSet<>();         for (int i = 0; i < str.length(); ++i)        {             // To store the current sub-string            String temp = "";             // To store the characters of the            // current sub-string            HashSet<Character> ans = new HashSet<>();            for (int j = i; j < str.length(); ++j)            {                temp = temp + str.charAt(j);                ans.add(str.charAt(j));                 // If current sub-string hasn't                // been stored before                if (!items.contains(temp))                {                     // Insert it into the set                    items.add(temp);                     // Update the count of                    // distinct characters                    cnt += ans.size();                }            }        }         return cnt;    }     // Driver code    public static void main(String[] args)    {        String str = "ABCA";        System.out.println(countTotalDistinct(str));    }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approach # Function to return the count of distinct# characters in all the distinct# sub-strings of the given stringdef countTotalDistinct(string) :     cnt = 0;     # To store all the sub-strings    items = set();     for i in range(len(string)) :         # To store the current sub-string        temp = "";         # To store the characters of the        # current sub-string        ans = set();        for j in range(i, len(string)) :            temp = temp + string[j];            ans.add(string[j]);             # If current sub-string hasn't            # been stored before            if temp not in items :                 # Insert it into the set                items.add(temp);                 # Update the count of                # distinct characters                cnt += len(ans);     return cnt;  # Driver codeif __name__ == "__main__" :     string = "ABCA";     print(countTotalDistinct(string));     # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class geeks{     // Function to return the count of distinct    // characters in all the distinct    // sub-strings of the given string    public static int countTotalDistinct(String str)    {        int cnt = 0;         // To store all the sub-strings        HashSet<String> items = new HashSet<String>();         for (int i = 0; i < str.Length; ++i)        {             // To store the current sub-string            String temp = "";             // To store the characters of the            // current sub-string            HashSet<char> ans = new HashSet<char>();            for (int j = i; j < str.Length; ++j)            {                temp = temp + str[j];                ans.Add(str[j]);                 // If current sub-string hasn't                // been stored before                if (!items.Contains(temp))                {                     // Insert it into the set                    items.Add(temp);                     // Update the count of                    // distinct characters                    cnt += ans.Count;                }            }        }         return cnt;    }     // Driver code    public static void Main(String[] args)    {        String str = "ABCA";        Console.WriteLine(countTotalDistinct(str));    }} // This code is contributed by 29AjayKumar
<script> // js implementation of the approach // Function to return the count of distinct// characters in all the distinct// sub-strings of the given stringfunction countTotalDistinct(str){    let cnt = 0;     // To store all the sub-strings    let items = new Set();     for (let i = 0; i < str.length; ++i) {         // To store the current sub-string        let temp = "";         // To store the characters of the        // current sub-string        let ans = new Set();        for (let j = i; j < str.length; ++j) {            temp = temp + str[j];            ans.add(str[j]);            // If current sub-string hasn't            // been stored before            if (!items.has(temp)) {                 // Insert it into the set                items.add(temp);                 // Update the count of                // distinct characters                cnt += ans.size;            }        }    }     return cnt;} // Driver codelet str = "ABCA";document.write(countTotalDistinct(str));  </script>
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).
ankthon
sanjeev2552
29AjayKumar
rohan07
pulamolusaimohan
cpp-map-functions
cpp-strings
substring
Strings
cpp-strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters