Skip to main content
Back to problems
#1048
Medium Algorithms

Longest string chain

Array Hash Table Two Pointers String Dynamic Programming Sorting
62.8% acceptance
Feb 25, 2026
7777
272
You are given an array of words where each word consists of lowercase English letters. wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB. For example, "abc" is a predecessor of "abac", while "cba" is not a predecessor of "bcad". A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn longest_str_chain(mut words: Vec<String>) -> i32 {
    words.sort_by_key(|w| w.len());
    let mut dp: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
    let mut ans = 1;
    for w in &words {
      let mut best = 0;
      for i in 0..w.len() {
        let pred = format!("{}{}", &w[..i], &w[i+1..]);
        best = best.max(*dp.get(&pred).unwrap_or(&0));
      }
      dp.insert(w.clone(), best + 1);
      ans = ans.max(best + 1);
    }
    ans
  }
}