I have an input abcde
. I’m trying to output something like this:
JavaScript
x
16
16
1
a
2
ab
3
abc
4
abcd
5
abcde
6
b
7
bc
8
bcd
9
bcde
10
c
11
cd
12
cde
13
d
14
de
15
e
16
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:
JavaScript
1
6
1
s = "abcde"
2
for i in range(len(s)):
3
for x in range(i, len(s) + 1):
4
a = s[i:x]
5
if a != "": print(a)
6
Advertisement
Answer
Lets do this without a nested loop!
This a game with random
library, but the execution time is similar to your code.
JavaScript
1
13
13
1
from random import randint
2
list1=[]
3
str1='abcde'
4
while len(list1)!=int(((len(str1)+1)*len(str1))//2):
5
i=randint(0,len(str1))
6
j=randint(0,len(str1))
7
i,j=max(i,j),min(i,j)
8
if i!=j:
9
a=str1[j:i]
10
if a not in list1:
11
list1.append(a)
12
print(a)
13
if the string, str1 = 'abcdef'
, it prints:
JavaScript
1
22
22
1
de
2
abcdef
3
cdef
4
abc
5
ef
6
d
7
c
8
abcd
9
b
10
abcde
11
def
12
bcde
13
f
14
bcdef
15
a
16
bcd
17
cd
18
e
19
ab
20
cde
21
bc
22
Now if you want your data in the order you specified, use sort
:
JavaScript
1
2
1
list1.sort()
2