Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 17, 2021 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/abc10f2a200e91012196f3a5da4ce1b5 to your computer and use it in GitHub Desktop.
Save vrat28/abc10f2a200e91012196f3a5da4ce1b5 to your computer and use it in GitHub Desktop.
Longest String Chain(Python - Bottom Up)
class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len) # sort words by its length
ans = 0
cnt = defaultdict(int)
for word in words:
cnt[word] = 1
for i in range(len(word)):
predecessor = word[:i] + word[i+1:]
if predecessor in cnt and cnt[word] < cnt[predecessor] + 1:
cnt[word] = cnt[predecessor] + 1
ans = max(ans, cnt[word])
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment