0

The interleaving rule is to form a new word by inserting one word into another, in a letter by letter fashion, like showing below:

a p p l e
 o l d
   =
aoplpdle

It does not matter which word goes first. (oalpdple is also valid)

The problem is given a vector of strings {old, apple, talk, aoplpdle, otladlk}, find all the words that are valid interleavings of two word from the vector.

The simplest solution asks for at least O(n^2) time complexity, taking every two word and form a interleaving word, check if it is in the vector.

Is there better solutions?

Amit
  • 45,440
  • 9
  • 78
  • 110
  • What does the O(n^2) algorithm look like? – Thomas Matthews May 18 '16 at 22:04
  • Check out this beautiful answer - Solution is designed using a non-deterministic finite state machine http://stackoverflow.com/questions/37243991/determine-if-a-sequence-is-an-interleaving-of-a-repetition-of-two-strings – Tejash Desai May 19 '16 at 09:45

1 Answers1

1

Sort by length. You only need to check combinations where the sum of lengths of 2 entries (words...) is equal to the length of existing entry(ies).

This will reduce your average complexity. I didn't take the time to compute the worst complexity, but it's probably lower then O(n^2) as well.

You can also optimize the "inner loop" by rejecting matches early - you don't really need to construct the entire interleaved word to reject a match - iterate the candidate word alongside the 2 input words till you find a mismatch. This won't reduce your worst complexity, but will have a positive effect on overall performance.

Amit
  • 45,440
  • 9
  • 78
  • 110