KatInterview

Identify Compound Words in a Dictionary

Dynamic ProgrammingModel answer
HardModel answerDynamic Programmingstringsdynamic-programmingtrie

Last updated

Find all strings in a list that can be constructed by concatenating two or more smaller strings from the same list.

Given an array words of non-empty, lowercase English strings, identify every string that can be fully constructed by joining together two or more strings from the same array.

Individual component strings can be reused multiple times.

Write a function that returns a list of all such compound strings.

Constraints

  • $1 \le \text{words.length} \le 10^5$
  • The total sum of string lengths across the array does not exceed $1,000,000$.
  • All strings consist only of lowercase English letters.
  • The returned list can contain the matching words in any order.

Example 1

Input: words = ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]
Output: ["catsdogcats", "dogcatsdog", "ratcatdogcat"]
Explanation: 
- "catsdogcats" = "cats" + "dog" + "cats"
- "dogcatsdog" = "dog" + "cats" + "dog"
- "ratcatdogcat" = "rat" + "cat" + "dog" + "cat"

Example 2

Input: words = ["a", "b", "ab", "abc"]
Output: ["ab"]
Explanation: "ab" can be formed by "a" + "b".

Hints

Hint 1

If you sort the words by length in ascending order, any word that can form a longer word must appear before it.

Hint 2

This problem is a variation of the Word Break problem. You can evaluate whether a string is valid using Dynamic Programming.

Hint 3

To prevent a word from satisfying the criteria by matching itself, only include words of strictly shorter length in your lookup set during evaluation.