Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print all substrings of a string in O(n) time?

I have an input abcde. I'm trying to output something like this:

a
ab
abc
abcd
abcde
b
bc
bcd
bcde
c
cd
cde
d
de
e

I can't make a code which is without nested loops. My question is what is the solution of this problem with O(n) time complexity?

My code is given below:

s = "abcde"  
for i in range(len(s)):
    for x in range(i, len(s) + 1):
        a = s[i:x]
        if a != "": print(a)
like image 375
Azmain1234 Avatar asked Nov 07 '22 08:11

Azmain1234


1 Answers

Is there a way to print all substrings of a string in O(N) time?

No there isn't. It is mathematically impossible.

There are O(N^2) substrings of a string of length N. You cannot print O(N^2) strings in O(N) time. Not even if the strings were all (individually) O(1) to print. (Which they aren't. The average substring length is also a function of N.)

Even parallelism won't get you to O(N). If (hypothetically) had a P > N processors to generate the strings, printing them is a process that you cannot parallelize.


For the record, it is possible to code this in ways that avoid explicit nested loops. But this doesn't alter the fundamental mathematical impossibility of a solution that is better than O(N^3).

like image 84
Stephen C Avatar answered Nov 15 '22 01:11

Stephen C