Check if Text Can Be Built from Dictionary Words
Dynamic ProgrammingAuto-graded · 21 test casesLast updated
Tests dynamic programming with Trie optimization to determine if a string can be fully decomposed into a sequence of dictionary words.
You are given a text string text and a list of dictionary words dictionary. Your task is to determine whether the entire text can be constructed by concatenating words from the dictionary in sequence.
Each word from the dictionary may be used multiple times, and the concatenation must cover the entire text with no characters left over or skipped.
Write a function that returns True if such a decomposition exists, and False otherwise.
Constraints
1 <= len(text) <= 3001 <= len(dictionary) <= 10001 <= len(dictionary[i]) <= 20textanddictionary[i]consist only of lowercase English letters- All words in
dictionaryare unique - Empty strings in the dictionary should be ignored (they contribute nothing to any valid decomposition)
Examples
Example 1
Input: can_construct_text('leetcode', ['leet', 'code'])
Output: True
Example 2
Input: can_construct_text('applepenapple', ['apple', 'pen'])
Output: True
Example 3
Input: can_construct_text('catsandog', ['cats', 'dog', 'sand', 'and', 'cat'])
Output: False
Hints
Hint 1
Think of this as a reachability problem: can you reach the end of the text by making valid jumps using dictionary words?
Hint 2
Dynamic programming can track which positions in the text are reachable by valid word sequences from the start.
Hint 3
A Trie data structure allows efficient prefix matching and early termination when no dictionary word matches the current substring.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We model this problem as a reachability question over positions in the text. Position i represents having successfully matched the first i characters of the text using dictionary words.
The core insight is to use dynamic programming where reachable[i] indicates whether the prefix text[:i] can be fully decomposed into dictionary words. We initialize reachable[0] = True (the empty prefix is trivially valid), and for each reachable position, we attempt to extend it by matching dictionary words.
To efficiently check which words match at each position, we build a Trie (prefix tree) from all dictionary words. For each reachable starting position, we walk character-by-character through the text while simultaneously traversing the Trie. Whenever we reach a node marked as a word ending, we know that substring forms a valid dictionary word, so we mark that endpoint as reachable.
The Trie provides two key optimizations:
- Prefix pruning: We stop searching as soon as the current character sequence is not a prefix of any dictionary word
- Early termination: We can return immediately when we mark the final position as reachable
Why It Works
By processing positions left-to-right, when we process position i, all positions before it have already been finalized. The Trie walk from position i enumerates exactly the dictionary words that appear as substrings starting at position i. Each time we find a complete word ending at position j, we correctly mark position j as reachable because we found a valid path: a known-good decomposition up to i plus a dictionary word from i to j.
Complexity
Time Complexity: O(n · L) where n is the length of the text and L is the maximum word length. For each starting position, we walk at most L characters through the Trie, with each step taking O(1) time. Building the Trie takes O(W) where W is the total characters across all dictionary words.
Space Complexity: O(W + n) for the Trie structure and the reachability array. The Trie stores one node per unique prefix in the dictionary, which in the worst case is O(W) but typically much smaller due to shared prefixes.
from typing import List
def can_construct_text(text: str, dictionary: List[str]) -> bool:
# Build a trie to store all dictionary words for efficient prefix matching
trie = {}
end_marker = ""
for word in dictionary:
if not word:
continue
node = trie
for char in word:
node = node.setdefault(char, {})
node[end_marker] = True
# Track which positions in text can be reached by valid word sequences
reachable = [False] * (len(text) + 1)
reachable[0] = True
for start in range(len(text)):
if not reachable[start]:
continue
node = trie
for end in range(start, len(text)):
node = node.get(text[end])
if node is None:
break # No dictionary word has this prefix
if end_marker in node:
reachable[end + 1] = True
if end + 1 == len(text):
return True # Early exit when we reach the end
return reachable[len(text)]