Leetcode: 472. Concatenated Words

Problem Statement

from typing import List


class Solution:
    def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
        root = {}
        for w in words:
            node = root
            for c in w:
                node.setdefault(c, {})
                node = node[c]
            node["$"] = True

        @cache
        def dfs(i, j, k):
            if j == len(words[i]):
                return k > 1
            node = root
            while j < len(words[i]) and words[i][j] in node:
                node = node[words[i][j]]
                j += 1
                if "$" in node and dfs(i, j, k + 1):
                    return True
            return False

        return [w for i, w in enumerate(words) if dfs(i, 0, 0)]