Program to find length longest prefix sequence of a word array in Python

Suppose we have a list of words called w, with lowercase strings. We have to find the length of the longest sequence of w where each previous word is the prefix of the next word and the next word has just one new character appended.

So, if the input is like w = ["pqr", "pq", "m", "mn", "pqrs"], then the output will be 3 because we can get the sequence: ["pq", "pqr", "pqrs"], whose length is 3.

To solve this, we will follow these steps −

  • sort the list w
  • dp := a map, where default value for a key is 0
  • res := 0
  • for each word in w, do
    • dp[word] := dp[substring of word up to second last element] + 1
    • res := maximum of res and dp[word]
  • return res


Let us see the following implementation to get better understanding −

from collections import defaultdict
def solve(w):
   dp = defaultdict(int)
   res = 0
   for word in w:
      dp[word] = dp[word[:-1]] + 1
      res = max(res, dp[word])
   return res

w = ["pqr", "pq", "m", "mn", "pqrs"]


["pqr", "pq", "m", "mn", "pqrs"]



Updated on: 19-Oct-2021


Kickstart Your Career

Get certified by completing the course

Get Started