Skip to content

1048. Longest String Chain 👍

Approach 1: Top-down

  • Time: $O(n\max(|\texttt{words[i]}|)^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  int longestStrChain(vector<string>& words) {
    const unordered_set<string> wordsSet{words.begin(), words.end()};
    unordered_map<string, int> mem;
    return accumulate(words.begin(), words.end(), 0,
                      [&](int acc, const string& word) {
      return max(acc, longestStrChain(word, wordsSet, mem));
    });
  }

 private:
  // Returns the longest string chain, where s is the last word.
  int longestStrChain(const string& s, const unordered_set<string>& wordsSet,
                      unordered_map<string, int>& mem) {
    if (const auto it = mem.find(s); it != mem.cend())
      return it->second;

    int res = 1;

    for (int i = 0; i < s.length(); ++i) {
      const string pred = s.substr(0, i) + s.substr(i + 1);
      if (wordsSet.contains(pred))
        res = max(res, longestStrChain(pred, wordsSet, mem) + 1);
    }

    return mem[s] = res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int longestStrChain(String[] words) {
    Set<String> wordsSet = new HashSet<>(Arrays.asList(words));
    int ans = 0;

    for (final String word : words)
      ans = Math.max(ans, longestStrChain(word, wordsSet));

    return ans;
  }
  // dp[s] := the longest string chain, where s is the last word
  private Map<String, Integer> dp = new HashMap<>();

  private int longestStrChain(final String s, Set<String> wordsSet) {
    if (dp.containsKey(s))
      return dp.get(s);

    int ans = 1;

    for (int i = 0; i < s.length(); ++i) {
      final String pred = s.substring(0, i) + s.substring(i + 1);
      if (wordsSet.contains(pred))
        ans = Math.max(ans, longestStrChain(pred, wordsSet) + 1);
    }

    dp.put(s, ans);
    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def longestStrChain(self, words: list[str]) -> int:
    wordsSet = set(words)

    @functools.lru_cache(None)
    def dp(s: str) -> int:
      """Returns the longest chain where s is the last word."""
      ans = 1
      for i in range(len(s)):
        pred = s[:i] + s[i + 1:]
        if pred in wordsSet:
          ans = max(ans, dp(pred) + 1)
      return ans

    return max(dp(word) for word in words)

Approach 2: Bottom-up

  • Time: $O(\texttt{sort} + n\max(|\texttt{words[i]}|)^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int longestStrChain(vector<string>& words) {
    int ans = 0;
    // dp[s] := the longest string chain, where s is the last word
    unordered_map<string, int> dp;

    ranges::sort(words, ranges::less{},
                 [](const string& word) { return word.length(); });

    for (const string& word : words) {
      for (int i = 0; i < word.length(); ++i) {
        const string pred = word.substr(0, i) + word.substr(i + 1);
        dp[word] = max(dp[word], (dp.contains(pred) ? dp[pred] : 0) + 1);
      }
      ans = max(ans, dp[word]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int longestStrChain(String[] words) {
    int ans = 0;
    Map<String, Integer> dp = new HashMap<>();

    Arrays.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));

    for (final String word : words) {
      int bestLength = 0;
      for (int i = 0; i < word.length(); ++i) {
        final String pred = word.substring(0, i) + word.substring(i + 1);
        bestLength = Math.max(bestLength, dp.getOrDefault(pred, 0) + 1);
      }
      dp.put(word, bestLength);
      ans = Math.max(ans, bestLength);
    }

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def longestStrChain(self, words: list[str]) -> int:
    dp = {}

    for word in sorted(words, key=len):
      dp[word] = max(dp.get(word[:i] + word[i + 1:], 0) +
                     1 for i in range(len(word)))

    return max(dp.values())