The number of substrings (of all lengths inclusive) that can be formed from a character string of length n is: A. n B. n^2 C. n(n+1)/2 D. 2^n
GATE 1994 · Discrete Mathematics · Counting · medium
Answer: n(n+1)/2
- Count substrings of a fixed length k: A substring of length k starts at some position i where 1 <= i <= n-k+1. So there are (n - k + 1) substrings of length k.
- Sum over all possible lengths k = 1 to n: Total = sum_{k=1}^{n} (n-k+1) = n + (n-1) + (n-2) + ... + 2 + 1 = n(n+1)/2