KatInterview

472. Concatenated Words

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all "concatenated words" within a given list of unique strings. A concatenated word is defined as a string that is composed entirely of at least two shorter words, which are also present in the same input list. This problem can be seen as a variation of the classic "Word Break" problem, where for each word in the list, we need to check if it can be segmented into other, shorter words from the same list.

Solution

Concatenated Words in Python

class Solution:
    def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
        # Sort words by length. This is a key optimization.
        # It ensures that when we check a word, all its potential shorter constituent
        # words are already in the dictionary (Trie).
        words.sort(key=len)

        result = []
        # Using a dictionary as a Trie. A special character marks the end of a word.
        trie = {}

        for word in words:
            # An empty word cannot be a concatenated word, and the shortest word
            # cannot be formed by other words.
            if not word:
                continue

            # Check if the current word can be formed by words already in the Trie.
            if self.can_form(word, trie):
                result.append(word)
            
            # Add the current word to the Trie for subsequent checks.
            node = trie
            for char in word:
                if char not in node:
                    node[char] = {}
                node = node[char]
            node['#'] = True # '#' marks the end of a word

        return result

    def can_form(self, word: str, trie: dict) -> bool:
        # If the trie is empty (first word), it cannot be formed.
        if not trie:
            return False
            
        n = len(word)
        # dp[i] is true if the prefix of word with length i can be segmented.
        dp = [False] * (n + 1)
        dp[0] = True # Base case: an empty string can always be formed.

        for i in range(n):
            # If we can't form the prefix word[:i], we can't extend from here.
            if not dp[i]:
                continue

            node = trie
            # From position i, try to find a word in the Trie that matches a suffix.
            for j in range(i, n):
                char = word[j]
                if char not in node:
                    break # No word in Trie with this prefix.
                node = node[char]
                # If we found a word in the Trie, we can form the prefix up to j+1.
                if '#' in node:
                    dp[j + 1] = True

        return dp[n]

Concatenated Words in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Solution {
    // TrieNode class for the prefix tree.
    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        boolean isWord = false;
    }

    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        // Sort words by length. This is a key optimization.
        // It ensures that when we check a word, all its potential shorter constituent
        // words are already in the Trie.
        Arrays.sort(words, Comparator.comparingInt(String::length));

        List<String> result = new ArrayList<>();
        TrieNode root = new TrieNode();

        for (String word : words) {
            // An empty word cannot be a concatenated word. Also, the shortest word
            // cannot be formed by other words, so we can skip it. The check `canForm`
            // will correctly handle this for the first non-empty word.
            if (word.isEmpty()) {
                continue;
            }

            // Check if the current word can be formed by words already in the Trie.
            if (canForm(word, root)) {
                result.add(word);
            }

            // Add the current word to the Trie for subsequent checks.
            addWord(word, root);
        }

        return result;
    }

    // Checks if a word can be segmented using words from the Trie.
    private boolean canForm(String word, TrieNode root) {
        if (root.children[word.charAt(0) - 'a'] == null && word.length() > 0) return false;
        int n = word.length();
        // dp[i] is true if the prefix of word with length i can be segmented.
        boolean[] dp = new boolean[n + 1];
        dp[0] = true; // Base case: an empty string can always be formed.

        for (int i = 0; i < n; i++) {
            // If we can't form the prefix word[0...i-1], we can't extend from here.
            if (!dp[i]) {
                continue;
            }

            TrieNode curr = root;
            // From position i, try to find a word in the Trie that matches a suffix.
            for (int j = i; j < n; j++) {
                int index = word.charAt(j) - 'a';
                if (curr.children[index] == null) {
                    break; // No word in Trie with this prefix.
                }
                curr = curr.children[index];
                // If we found a word in the Trie, we can form the prefix up to j+1.
                if (curr.isWord) {
                    dp[j + 1] = true;
                }
            }
        }

        return dp[n];
    }

    // Adds a word to the Trie.
    private void addWord(String word, TrieNode root) {
        TrieNode curr = root;
        for (char ch : word.toCharArray()) {
            int index = ch - 'a';
            if (curr.children[index] == null) {
                curr.children[index] = new TrieNode();
            }
            curr = curr.children[index];
        }
        curr.isWord = true;
    }
}

Concatenated Words in C++

class Solution {
private:
    // TrieNode structure for the prefix tree.
    struct TrieNode {
        TrieNode* children[26];
        bool isWord;

        TrieNode() {
            for (int i = 0; i < 26; ++i) {
                children[i] = nullptr;
            }
            isWord = false;
        }
    };

public:
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        // Sort words by length. This is a key optimization.
        // It ensures that when we check a word, all its potential shorter constituent
        // words are already in the Trie.
        sort(words.begin(), words.end(), [](const string& a, const string& b) {
            return a.length() < b.length();
        });

        vector<string> result;
        TrieNode* root = new TrieNode();

        for (const string& word : words) {
            // An empty word cannot be a concatenated word, and also the shortest word
            // cannot be formed by other words.
            if (word.empty()) {
                continue;
            }

            // Check if the current word can be formed by words already in the Trie.
            if (canForm(word, root)) {
                result.push_back(word);
            }

            // Add the current word to the Trie for subsequent checks.
            addWord(word, root);
        }

        return result;
    }

private:
    // Checks if a word can be segmented using words from the Trie.
    bool canForm(const string& word, TrieNode* root) {
        if (word.empty()) return false;
        int n = word.length();
        // dp[i] is true if the prefix of word with length i can be segmented.
        vector<bool> dp(n + 1, false);
        dp[0] = true; // Base case: an empty string can always be formed.

        for (int i = 0; i < n; ++i) {
            // If we can't form the prefix word[0...i-1], we can't extend from here.
            if (!dp[i]) {
                continue;
            }

            TrieNode* curr = root;
            // From position i, try to find a word in the Trie that matches a suffix.
            for (int j = i; j < n; ++j) {
                int index = word[j] - 'a';
                if (!curr->children[index]) {
                    break; // No word in Trie with this prefix.
                }
                curr = curr->children[index];
                // If we found a word in the Trie, we can form the prefix up to j+1.
                if (curr->isWord) {
                    dp[j + 1] = true;
                }
            }
        }

        return dp[n];
    }

    // Adds a word to the Trie.
    void addWord(const string& word, TrieNode* root) {
        TrieNode* curr = root;
        for (char ch : word) {
            int index = ch - 'a';
            if (!curr->children[index]) {
                curr->children[index] = new TrieNode();
            }
            curr = curr->children[index];
        }
        curr->isWord = true;
    }
};

Concatenated Words in TypeScript

function findAllConcatenatedWordsInADict(words: string[]): string[] {
    // TrieNode class for the prefix tree.
    class TrieNode {
        children: Map<string, TrieNode> = new Map();
        isWord: boolean = false;
    }

    // Sort words by length. This is a key optimization.
    // It ensures that when we check a word, all its potential shorter constituent
    // words are already in the Trie.
    words.sort((a, b) => a.length - b.length);

    const result: string[] = [];
    const root = new TrieNode();

    // Helper function to add a word to the Trie.
    const addWord = (word: string) => {
        let curr = root;
        for (const char of word) {
            if (!curr.children.has(char)) {
                curr.children.set(char, new TrieNode());
            }
            curr = curr.children.get(char)!;
        }
        curr.isWord = true;
    };

    // Helper function to check if a word can be segmented.
    const canForm = (word: string): boolean => {
        if (word.length === 0) return false;
        const n = word.length;
        // dp[i] is true if the prefix of word with length i can be segmented.
        const dp: boolean[] = new Array(n + 1).fill(false);
        dp[0] = true; // Base case

        for (let i = 0; i < n; i++) {
            if (!dp[i]) continue;

            let curr = root;
            for (let j = i; j < n; j++) {
                const char = word[j];
                if (!curr.children.has(char)) {
                    break; // No word in Trie with this prefix
                }
                curr = curr.children.get(char)!;
                if (curr.isWord) {
                    dp[j + 1] = true;
                }
            }
        }
        return dp[n];
    };

    for (const word of words) {
        if (word.length === 0) continue;
        
        if (canForm(word)) {
            result.push(word);
        }
        addWord(word);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.