1. Recursive Predecessor DFS
Intuition
Recursively search all valid predecessors for each word from the input set.
Algorithm
- Store words in a hash set for quick membership checking.
- Define
dfs(word): returns max chain ending at word. - For each character in
word: - Create
prevby removing that character. - If
previn set,maxChain = max(maxChain, 1 + dfs(prev)). - Return
maxChain.
#include <iostream>#include <vector>#include <string>#include <unordered_set>#include <algorithm> using namespace std; class Solution { int dfs(const string& word, const unordered_set<string>& wordSet) { int maxChain = 1; for (int i = 0; i < word.length(); ++i) { string prev = word.substr(0, i) + word.substr(i + 1); if (wordSet.count(prev)) { maxChain = max(maxChain, 1 + dfs(prev, wordSet)); } } return maxChain; }public: int longestStrChain(vector<string>& words) { unordered_set<string> wordSet(words.begin(), words.end()); int ans = 1; for (const string& w : words) { ans = max(ans, dfs(w, wordSet)); } return ans; }}; int main() { Solution sol; vector<string> words = {"a", "b", "ba", "bca", "bda", "bdca"}; cout << "Longest Chain: " << sol.longestStrChain(words) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(L^n) - Space complexity:
O(n) call stack