Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count substrings made up of a single distinct character
Next article icon

Find distinct characters in distinct substrings of a string

Last Updated : 07 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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-strings Distinct characters
A 1
AB 2
ABC 3
ABCA 3
B 1
BC 2
BCA 3
C 1
CA 2

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: 
 

C++




// 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 string
int 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 code
int main()
{
    string str = "ABCA";
 
    cout << countTotalDistinct(str);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import 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




# Python3 implementation of the approach
 
# Function to return the count of distinct
# characters in all the distinct
# sub-strings of the given string
def 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 code
if __name__ == "__main__" :
 
    string = "ABCA";
 
    print(countTotalDistinct(string));
     
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using 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
 
 

Javascript




<script>
 
// js implementation of the approach
 
// Function to return the count of distinct
// characters in all the distinct
// sub-strings of the given string
function 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 code
let str = "ABCA";
document.write(countTotalDistinct(str));
 
 
</script>
 
 
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).



Next Article
Count substrings made up of a single distinct character

C

Chandan_Agrawal
Improve
Article Tags :
  • DSA
  • Strings
  • cpp-map-functions
  • cpp-strings
  • substring
Practice Tags :
  • cpp-strings
  • Strings

Similar Reads

  • Count substrings made up of a single distinct character
    Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
    5 min read
  • Count of substrings having all distinct characters
    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",
    7 min read
  • Count number of substrings of a string consisting of same characters
    Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
    6 min read
  • Count the sum of count of distinct characters present in all Substrings
    Given a string S consisting of lowercase English letters of size N where (1 <= N <= 105), the task is to print the sum of the count of distinct characters N where (1 <= N <= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings o
    8 min read
  • Count number of substrings having at least K distinct characters
    Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters. Examples: Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are: "abc": Count of dist
    7 min read
  • Count of Distinct Substrings occurring consecutively in a given String
    Given a string str, the task is to find the number of distinct substrings that are placed consecutively in the given string. Examples: Input: str = "geeksgeeksforgeeks" Output: 2 Explanation: geeksgeeksforgeeks -> {"geeks"} geeksgeeksforgeeks -> {"e"} Only one consecutive occurrence of "e" is
    14 min read
  • Count of distinct substrings of a string using Suffix Array
    Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string.  Examples:  Input : str = “ababa” Output : 10 Total number of distinct substring are 10, which are, "", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba" and "ababa"Reco
    15+ min read
  • Count of Distinct strings possible by inserting K characters in the original string
    Given a string S and an integer K, the task is to find the total number of strings that can be formed by inserting exactly K characters at any position of the string S. Since the answer can be large, print it modulo 109+7.Examples: Input: S = "a" K = 1 Output: 51 Explanation: Since any of the 26 cha
    12 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 min read
  • Find frequency of all characters across all substrings of given string
    Given a string S containing all lowercase characters and its length N. Find frequency of all characters across all substrings of the given string. Examples: Input: N = 3, S = "aba"Output: a 6b 4Explanation: The substrings are: a, b, a, ab, ba, aba. The frequency of each character: a = 6, b = 4. Henc
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences