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

PythonServer Side ProgrammingProgramming

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

Example

Let us see the following implementation to get better understanding −

from collections import defaultdict
def solve(w):
   w.sort()
   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"]
print(solve(w))

Input

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

Output

3
raja
Updated on 19-Oct-2021 10:43:22

Advertisements