Skip to content
Advertisement

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:

JavaScript

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

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

if the string, str1 = 'abcdef', it prints:

JavaScript

Now if you want your data in the order you specified, use sort:

JavaScript
Advertisement