FastPrepLongest String Chain

Longest String Chain

LinkedIn logoLinkedIn● MediumFULLTIMEOA
Learn

Problem statement

You are given an array of words consisting of lowercase English letters.

A word first is a predecessor of second when inserting exactly one letter anywhere in first, without changing the order of its existing letters, produces second. For example, abc is a predecessor of abac, but cba is not a predecessor of bcaa.

A word chain is a sequence in which every word is a predecessor of the next word. A single word is a valid chain of length one.

Return the greatest possible length of a chain formed from the given words.

Function

longestStrChain(words: String[]) → int

Examples

Example 1

words = ["a","b","ba","bca","bda","bdca"]return = 4

One longest chain is ["a", "ba", "bda", "bdca"], which has length 4.

Example 2

words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]return = 5

All five words form the chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].

Example 3

words = ["abcd","dbqca"]return = 1

No word is a predecessor of the other, so a single-word chain such as ["abcd"] is longest.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 16
  • Every word contains only lowercase English letters.

More LinkedIn problems

See LinkedIn hiring insights
public int longestStrChain(String[] words) {
  // write your code here
}
words["a","b","ba","bca","bda","bdca"]
expected4
Checking account…