Skip to content
Related Articles

Related Articles

Improve Article

Counts of distinct consecutive sub-string of length two using C++ STL

  • Difficulty Level : Medium
  • Last Updated : 28 Jun, 2021

Given a string the task is to print all distinct sub-strings of length two in the given string. All substrings should be printed in lexicographical order.

Input: str = "abcab"
Output: ab-2

Input: str = "xyz"
Output: xy-1


The idea of this article is to demonstrate map and pair in C++ STL.
We declare a map d_pairs that uses a character pair key and count as value. We iterate over the given string from the starting index to store every consecutive pair if not present already and increment its count in the map. After completion of the loop, we get all distinct consecutive pairs and their corresponding occurrence count in the map container. 
Please note that map is used as we need output in sorted order. We could use a unordered_map() if output was not needed in sorted order. Time complexity of underdered_map() operations is O(1) while that of map is O(Log n)


// C++ STL based program to print all distinct
// substrings of size 2 and their counts.
using namespace std;
void printDistinctSubStrs(string str)
    // Create a map to store unique substrings of
    // size 2
    map<pair<char,char>, int> dPairs;
    // Count occurrences of all pairs
    for (int i=0; i<str.size()-1; i++)
        dPairs[make_pair(str[i], str[i+1])]++;
    // Traverse map to print sub-strings and their
    // counts.
    cout << "Distinct sub-strings with counts:\n";
    for (auto it=dPairs.begin(); it!=dPairs.end(); it++)
        cout << it->first.first << it->first.second
             << "-" << it->second << " ";
// Driver code
int main()
    string str = "abcacdcacabacaassddssklac";
    return 0;


Distinct sub-strings with counts:
aa-1 ab-2 ac-4 as-1 ba-1 bc-1 ca-4 cd-1 dc-1 dd-1 ds-1 kl-1 la-1 sd-1 sk-1 ss-2 

This article is contributed by Himanshu Gupta (Bagri). If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :