DEV Community

Cover image for Find all substring of a given string in O(n^2) time.
Rajesh Royal
Rajesh Royal

Posted on

8 4

Find all substring of a given string in O(n^2) time.

Below is the programmer written in JavaScript to find the all possible substrings of a given string in O(N^2) time complexity and an extra O(1) space;

Programme

function genSubstrings(inputString){
    debugger;
    let resultArray = [];
    // outer loop to run n times [n = size of string]
    for(let i = 0; i < inputString.length; i++){
        // pushing first char of string as substring
        // as we know that each char will be substring itself too.
        resultArray.push(inputString[i]);
        // inner loop to run n - 1 times;
        for(let j = i + 1; j < inputString.length; j++){
            // get last substring and append the new next char
            resultArray.push(
              resultArray[resultArray.length - 1] + inputString[j]
            );
        }
    }

    return resultArray;
}
Enter fullscreen mode Exit fullscreen mode

Output

genSubstrings("abcd");

(10) ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
Enter fullscreen mode Exit fullscreen mode

 
I searched internet for a better solution which can run in less then O(N^2) time complexity but didn't find any.

If anyone has a better solution please write in comments, It will be really helpful.
 

The thumbnail is taken from geekforgeek

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (3)

Collapse
 
mistval profile image
Randall

For any given string of length n, the number of substrings is n(n + 1) / 2.

This implies an algorithm with better than O(n^2) complexity is not possible, since at a minimum you have to insert all of those n(n + 1) / 2 substrings into an array.

Collapse
 
rajeshroyal profile image
Rajesh Royal

What if we need to print those substrings.
Do you have any code snippet of doing it.

Collapse
 
normalgui profile image
Normal GU-I • Edited

Well, I don't think there is a better way to do this except with O(N^2); But this can be helpful - Wikipedia suffix tree

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay