10. Concatenated Words

Difficulty:HardPattern:DP / Set LookupsTime:O(N * L^2)Space:O(N * L)

Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.

How It Works & Algorithmic Design

Solves using Word Length Sorting with Memoized Word Break Checking:

  1. Sort: Sort words by length in ascending order.
  2. Sub-word Verification: Maintain a set wordSet of previously processed shorter words.
  3. Word Break Check: For each word, execute DP canForm(word, wordSet):
    • Check if word can be partitioned into two or more words present in wordSet.
  4. Update: Add current word into wordSet.

Why This Approach Works Best

Processing shorter words first ensures a word can only be formed by strictly shorter constituent parts, optimizing performance across large dictionaries.

Example Walkthrough

Input

["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

List of words.

Concatenated Words

"catsdogcats", "dogcatsdog", "ratcatdogcat"

Formed by joining smaller dictionary words.

Output

["catsdogcats", "dogcatsdog", "ratcatdogcat"]

Result array.

Answer: Concatenated Words implementation

function findAllConcatenatedWordsInADict(words) {
  words.sort((a, b) => a.length - b.length);
  const wordSet = new Set();
  const res = [];
  function canForm(word) {
    if (wordSet.size === 0) return false;
    const dp = new Array(word.length + 1).fill(false);
    dp[0] = true;
    for (let i = 1; i <= word.length; i++) {
      for (let j = 0; j < i; j++) {
        if (dp[j] && wordSet.has(word.substring(j, i))) {
          dp[i] = true;
          break;
        }
      }
    }
    return dp[word.length];
  }
  for (const word of words) {
    if (canForm(word)) res.push(word);
    wordSet.add(word);
  }
  return res;
}

Sort words by length and test if each word can be segmented using previously stored smaller words.

Key Takeaways
  • Sorting words by length builds set incrementally.

  • Reuses classic Word Break Dynamic Programming.

  • Runs in $O(N \cdot L^2)$ time where $N$ is word count and $L$ is word length.