Number of substrings of a string
View Discussion
Improve Article
Save Article
Like Article
- Difficulty Level : Easy
- Last Updated : 12 Aug, 2022
Find total number of non-empty substrings of a string with N characters.
Input : str = “abc”
Output : 6
Every substring of the given string : “a”, “b”, “c”, “ab”, “bc”, “abc”![]()
Input : str = “abcd”
Output : 10
Every substring of the given string : “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”, “abc”, “bcd” and “abcd”Count of non-empty substrings is n*(n+1)/2
If we include empty string also as substring, the count becomes n*(n+1)/2 + 1How does above formula work?
- Number of substrings of length one is n (We can choose any of the n characters)
- Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed by adjacent)
- Number of substrings of length three is n-2
(We can choose any of the n-2 triplets formed by adjacent)- In general, number of substrings of length k is n-k+1 where 1 <= k <= n
Total number of substrings of all lengths from 1 to n =
n + (n-1) + (n-2) + (n-3) + … 2 + 1
= n * (n + 1)/2Implementation:
C++
// CPP program to count number of substrings// of a string#include <bits/stdc++.h>usingnamespacestd;intcountNonEmptySubstr(string str){intn = str.length();returnn*(n+1)/2;}// driver codeintmain(){string s ="abcde";cout << countNonEmptySubstr(s);return0;}Java
// Java program to count number of substrings// of a stringimportjava.io.*;publicclassGFG {staticintcountNonEmptySubstr(String str){intn = str.length();returnn * (n +1) /2;}// Driver codepublicstaticvoidmain(String args[]){String s ="abcde";System.out.println(countNonEmptySubstr(s));}}// This code is contributed// by Manish Shaw (manishshaw1)Python3
# Python3 program to count number# of substrings of a stringdefcountNonEmptySubstr(str):n=len(str);returnint(n*(n+1)/2);# driver codes="abcde";(countNonEmptySubstr(s));# This code is contributed by# Manish Shaw (manishshaw1)C#
// C# program to count number// of substrings of a stringusingSystem;classGFG {staticintcountNonEmptySubstr(stringstr){intn = str.Length;returnn * (n + 1) / 2;}// Driver CodepublicstaticvoidMain(){strings ="abcde";Console.Write(countNonEmptySubstr(s));}}// This code is contributed// by Manish Shaw (manishshaw1)PHP
<?php// PHP program to count number// of substrings of a stringfunctioncountNonEmptySubstr($str){$n=strlen($str);return$n* ($n+ 1) / 2;}// Driver Code$s="abcde";echocountNonEmptySubstr($s);// This code is contributed by Anuj_67?>Javascript
<script>// JavaScript program to count number of substrings// of a stringfunctioncountNonEmptySubstr(str){let n = str.length;returnn * (n + 1) / 2;}// Driver codelet s ="abcde";document.write(countNonEmptySubstr(s));// This code is contributed shivanisinghss2110</script>Output:15
Complexity Analysis:
- Time Complexity: O(1).
- Auxiliary Space: O(1).
My Personal Notes arrow_drop_upArticle Contributed By :Improved By :Article Tags :Practice Tags :


