To count the number of substrings in a given string, we need to understand how substrings work.
What Is a Substring?
A substring is any sequence of characters that appears contiguously in the original string. For example, in the word "cat"
, the substrings include "c"
, "a"
, "t"
, "ca"
, "at"
, and "cat"
.
How to Count Them
For a string of length n
, the total number of substrings can be found using a simple formula: n * (n + 1) / 2
.
This formula works because:
- From index 0, you can make
n
substrings
- From index 1, you can make
n - 1
substrings
- From index 2, you can make
n - 2
substrings
- ... and so on, down to 1
Add them up and you get:
n + (n-1) + (n-2) + ... + 1 = n * (n + 1) / 2
.
Case Discussion
- Normal Case: If the input is
"abc"
, it has 3 characters, so it has 3 * 4 / 2 = 6
substrings.
- Single Character: If the input is
"a"
, there's only 1 substring: "a".
- All Characters Same: If the input is
"aaa"
, substrings can still overlap: "a", "a", "a", "aa", "aa", and "aaa" — still 6 substrings in total.
- Empty String: If the input string is empty (length 0), there are no substrings, so the answer is
0
.
This formula gives us the count only—not the actual substrings. It’s very efficient because we don’t have to generate or store anything to get the result. The time complexity is O(1)
.