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
30
31
class Solution {
 public:
  int longestStrChain(vector<string>& words) {
    const unordered_set<string> wordsSet{begin(words), end(words)};
    int ans = 0;

    for (const string& word : words)
      ans = max(ans, longestStrChain(word, wordsSet));

    return ans;
  }

 private:
  // dp[s] := longest string chain where s is the last word
  unordered_map<string, int> dp;

  int longestStrChain(const string& s, const unordered_set<string>& wordsSet) {
    if (dp.count(s))
      return dp[s];

    int ans = 1;

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

    return dp[s] = ans;
  }
};
 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] := 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)

    # Dp(s) := longest chain where s is the last word
    @functools.lru_cache(None)
    def dp(s: str) -> int:
      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(n\log n + 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] := longest string chain where s is the last word
    unordered_map<string, int> dp;

    sort(begin(words), end(words),
         [](const auto& a, const auto& b) { return a.length() < b.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.count(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) -> 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())