Big-O complexity of iterating over every substring

748 Views Asked by At

What is the Big-O complexity of iterating over every possible non-empty substring of a string of length $N$?

The simple way to do the iteration over string $S$ is:

for i in 1 .. N:
    for j in (i+1) .. N:
        S[i .. j]

Clearly this is more complex than $\mathcal{O}\left(N\right)$ but less complex than $\mathcal{O}\left(N^2\right)$, but I'm not sure how to understand the complexity of these nested loops.

1

There are 1 best solutions below

0
On

$$ S = (1+ 1+ \ldots 1) + //\text {n times}\\ (1+1+ \ldots 1) + //\text{n-1 times} \\ \ldots 1 $$ Hence $S = 1 + 2 + \ldots (n-1) +n = \frac{n(n+1)}{2}$