
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest diminishing word chain in Python?
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- Program to find longest common prefix from list of strings in Python
- Program to find length of longest word that can be formed from given letters in python
- Program to find length of longest matrix path length in Python
- C++ program for length of the longest word in a sentence
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python

Advertisements