The original answer is correct for: is a string a
a substring of b
(misread).
Using a trie, you can simply add all strings to it in a first iteration, and in the 2nd iteration, start reading each word, let it be w
. If you find a word that you finished your read, but did not reach the string terminator ($
usually), you reach some node v
in the trie.
By doing a DFS from v
, you can get all strings which w
is prefix of them.
high level pseudo code:
t <- new trie
for each word w:
t.add(w)
for each word w:
node <- t.getLastNode(w)
if node.val != $
collection<- DFS(node) (excluding w itself)
w is a prefix of each word in collection
Note: in order to optimize it, you might need to do some extra work: if a
is prefix of b
, and b
is prefix of c
, then a
is prefix of c
, so - when you do the DFS, if you reach some node that was already searched - just append its strings to the current prefix.
Still, since there could be quadric number of possibilities ("a", "aa", "aaa", ....
), getting all of them requires quadric time.
Original answer: finding if a
is a substring of b
:
The suggested solution runs in a quadric complexity, you will need to check each two pairs, giving you O(n* (n-1) * |S|)
.
You can build a suffix tree from the strings in the first iteration, and in the 2nd iteration check if each string is a non trivial entry (not itself) of another string.
This solution is O(n*|S|)