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)
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With