Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I generate all substrings in complexity < O(n^2)

Currently I am using two nested for loop to generate all the substrings of a string. I heard about Suffix Tree but AFAIK Suffix Tree generates suffix not the substrings. Following is the code which currently i am using-

        String s = "abacbccca";
        int l = s.length();
        for (short c = 0; c < l; c++) {
            for (short r = 0; r < l - c; r++){
                Sting ss=s.substring(c, c + r + 1);                                        
                if(!t.contains(ss));
                    t.add(ss);
            }
        }

I want a way which can generate all the substrings in less than O(n^2). Although by seeing my code, anyone can suggest me that it's impossible, as i am adding every substring to a list. But my objective is not to store all the substrings, my objective is to find a string which is lexicographically ith smallest string.

like image 448
Ravi Joshi Avatar asked Apr 11 '12 12:04

Ravi Joshi


People also ask

Is there a way to print all substrings of a string in O n time?

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 .

What is the time complexity of finding all possible substrings of a string?

The time complexity to generate all substring is O(N^3) time and there are O(N^2) sub-strings for a string of length N.

How many substrings can be formed?

The total number of substrings formed by string of length N is (N*(N+1))/2, initialise count as (N*(N+1))/2.

How do you find all substrings in length K?

If the length of a string is N, then there can be N – K + 1 substring of length K. Generating these substrings will require O(N) complexity, and checking each substring requires O(K) complexity, hence making the overall complexity like O(N*K). Efficient approach: The idea is to use Window Sliding Technique.


1 Answers

There are O(n^2) different substrings, so no algorithm can enumerate them all with a complexity better than O(n^2)!

The problem of finding the lexicographically smallest substring is a totally different one, though. It's always the empty string, so that's an O(1) operation (and a very pointless one, too).

like image 188
Niklas B. Avatar answered Sep 22 '22 07:09

Niklas B.