finding substrings of a string

Chander Shivdasani picture Chander Shivdasani · Sep 14, 2012 · Viewed 26.9k times · Source

For a string of length n, the formula to compute all the substrings are: n(n+1)/2 Can someone help me out in intuitively understanding this formula?

Wikipedia says: "The number of substrings of a string of length where symbols only occur once, is the number of ways to choose two distinct places between symbols to start/end the substring"

Answer

user586399 picture user586399 · Sep 14, 2012

To understand this, note that any substring needs two parameters: start index and end index.

For example: string str = "Hello World"; // length == 11

Lets begin by taking only one-character substring at time: H, e, l, l, o, , W, o, r, l, d. Then by taking 2 characters at time: He, el, ll, lo, o , W, Wo, or, rl, ld. Then by taking 3 chars: Hel, .. etc.

So the total substring count is 11 + 10 + 9 + .. + 1 and, in general, for i from 1 to n, we have n - i + 1 substrings. By summition:

Sigma (n + 1 - i) from i = 1 to n, yields n * (n + 1) - n * (n + 1) / 2 which is n * (n + 1) / 2