HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Find All Substrings Interview Query in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
substringsallqueryinterviewfind

Problem

The following is my code for printing all the substrings of an input string. For example, with "abc", it would be "a","ab","abc","b","bc","c". Could someone please review it for efficiency (and possibly suggest alternatives)?

void findAllSubstrings(const char *s){
    int x=0;
    while(*(s+x)){
        for(int y=0; y<=x; y++)
            cout<<*(s+y);
        cout<<'\n';
        x++;
    }
    if(*(s+1))
        findAllSubstrings(s+1);
    else
        return;
}

Solution

Your problem is in O(n²), at least. This seems not to be optimizable. If you want only distinct substrings, then you will have to use a table of already encountered strings, which will make your code slower.

However, you can switch the algorithm from recursive to iterative, which is usually slightly faster. It's a micro-optimization, so do not expect a x2 improvement in speed...

void findAllSubstrings2(const char *s)
{
    while(*s)
    {
        int x=0;
        while(*(s + x))
        {
            for(int y = 0; y <= x; y++)
                std::cout << *(s + y);
            std::cout << "\n";
            x++;
        }
        s++;
    }
}


I've done a profile test, on Codepad and Ideone (different versions of same compilers + different machines). The io operations are left for the profile test, because what matters here is the comparison between the 2 functions.

Code Snippets

void findAllSubstrings2(const char *s)
{
    while(*s)
    {
        int x=0;
        while(*(s + x))
        {
            for(int y = 0; y <= x; y++)
                std::cout << *(s + y);
            std::cout << "\n";
            x++;
        }
        s++;
    }
}

Context

StackExchange Code Review Q#18684, answer score: 6

Revisions (0)

No revisions yet.