Find total number of non-empty substrings of a string with N characters. Here we use the word proper because we do not consider string itself as part of output.
Input : str = “abc”
Output : 6
Proper substrings are “a”, “b”, “c”, “ab”, “bc”, “abc”
Input : str = “abcd”
Output : 10
Proper substrings are “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 + 1
How 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, mumber 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)/2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Generate a string whose all K-size substrings can be concatenated to form the given string
- Lexicographically smallest permutation of a string that contains all substrings of another string
- Given a binary string, count number of substrings that start and end with 1.
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings divisible by 6 in a string of integers
- Number of even substrings in a string of digits
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Number of substrings divisible by 4 in a string of integers
- Number of substrings with odd decimal value in a binary string
- Number of substrings of one string present in other
- Rearrange the string to maximize the number of palindromic substrings
- Count the number of vowels occurring in all the substrings of given string
- Repeat substrings of the given String required number of times
- Count number of substrings of a string consisting of same characters
- Minimum number of substrings the given string can be splitted into that satisfy the given conditions
- Split the binary string into substrings with equal number of 0s and 1s
- Number of substrings with length divisible by the number of 1's in it
- Count of distinct substrings of a string using Suffix Trie
- Count of distinct substrings of a string using Suffix Array
- Print Kth character in sorted concatenated substrings of a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.