Concatenated Words

  • Time:O(n\ell^3), where n = |\texttt{words}| and \ell = \max(|\texttt{words[i]}|)
  • Space:O(n\ell)


class Solution {
  vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
    vector<string> ans;
    unordered_set<string> wordSet{begin(words), end(words)};
    unordered_map<string, bool> memo;

    for (const string& word : words)
      if (isConcat(word, wordSet, memo))

    return ans;

  bool isConcat(const string& s, const unordered_set<string>& wordSet,
                unordered_map<string, bool>& memo) {
    if (memo.count(s))
      return memo[s];

    for (int i = 1; i < s.length(); ++i) {
      const string prefix = s.substr(0, i);
      const string suffix = s.substr(i);
      if (wordSet.count(prefix) &&
          (wordSet.count(suffix) || isConcat(suffix, wordSet, memo)))
        return memo[s] = true;

    return memo[s] = false;


class Solution {
  public List<String> findAllConcatenatedWordsInADict(String[] words) {
    List<String> ans = new ArrayList<>();
    Set<String> wordSet = new HashSet<>(Arrays.asList(words));
    Map<String, Boolean> memo = new HashMap<>();

    for (final String word : words)
      if (wordBreak(word, wordSet, memo))

    return ans;

  private boolean wordBreak(final String word, Set<String> wordSet, Map<String, Boolean> memo) {
    if (memo.containsKey(word))
      return memo.get(word);

    for (int i = 1; i < word.length(); ++i) {
      final String prefix = word.substring(0, i);
      final String suffix = word.substring(i);
      if (wordSet.contains(prefix) &&
          (wordSet.contains(suffix) || wordBreak(suffix, wordSet, memo))) {
        memo.put(word, true);
        return true;

    memo.put(word, false);
    return false;


class Solution:
  def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
    wordSet = set(words)

    def isConcat(word: str) -> bool:
      for i in range(1, len(word)):
        prefix = word[:i]
        suffix = word[i:]
        if prefix in wordSet and (suffix in wordSet or isConcat(suffix)):
          return True

      return False

    return [word for word in words if isConcat(word)]