Tile a Word Using a Vocabulary List
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Tests whether a candidate can apply forward-reachability DP with a trie to decide if a string can be fully covered by vocabulary words end-to-end.
Problem
You are given a target string text and a vocabulary vocab, a list of words. Your task is to decide whether text can be completely tiled by placing vocabulary words one after another, with no gaps and no leftover characters.
- Each word in
vocabmay be used any number of times. - Words must be placed consecutively from left to right; they cannot overlap or be rearranged.
- Return
Trueif at least one valid tiling exists,Falseotherwise.
Constraints
1 <= len(text) <= 10^41 <= len(vocab) <= 10^5- Every string in
vocabis non-empty. - Characters are lowercase English letters.
- The combined length of all words in
vocabcan be large; your solution should be efficient.
Examples
Example 1
Input: can_tile_with_vocab('leetcode', ['leet', 'code'])
Output: True
Example 2
Input: can_tile_with_vocab('catsandog', ['cats', 'dog', 'sand', 'and', 'cat'])
Output: False
Example 3
Input: can_tile_with_vocab('applepenapple', ['apple', 'pen'])
Output: True
Hints
Hint 1
Define a boolean array where position i means the first i characters of text can be fully tiled. Which position is trivially true before you read any character?
Hint 2
From every position you can reach, walk forward character by character through a trie of vocab words. Each time you land on a terminal node, you have found a complete word — mark the position right after it as reachable.
Hint 3
A trie lets you stop the walk immediately when no vocabulary word can extend the current path, avoiding the cost of slicing and hashing substrings for every (start, end) pair.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Restating the task
We need a yes/no answer to: can text be written as w1 + w2 + ... + wk where every wi comes from vocab (repetition allowed)?
DP state
Define reachable[i] = True if the first i characters of text can be completely tiled. The base case is reachable[0] = True — the empty prefix needs no words. The answer we want is reachable[n] where n = len(text).
Driving the DP with a trie
A naive DP would iterate over all pairs (start, end), slice text[start:end], and check if the slice is in a hash set. Slicing and hashing each substring costs O(length), pushing the total toward O(n² · L) in the worst case.
Instead, build a trie from every word in vocab. A trie lets us walk forward through text one character at a time without creating any substrings:
- For each
startwherereachable[start]isTrue, start at the trie root. - Read
text[start],text[start+1], ... one character at a time, descending into the trie. - If the current character has no matching child, stop immediately — no vocab word can extend this path.
- Whenever we land on a terminal node, the substring
text[start:end+1]is a complete vocab word. Setreachable[end+1] = True. Ifend+1 == n, the whole string is tiled and we returnTrueright away.
Because we process start values in increasing order and only ever mark positions greater than start, each reachable[start] is fully settled before it is used.
Why it is correct
- Soundness: we only mark
reachable[end+1]whenreachable[start]is alreadyTrueand the trie confirmstext[start:end+1]is invocab. Extending a valid tiling by one valid word yields another valid tiling. - Completeness: if
text[:j]can be tiled and its final word istext[i:j], thenreachable[i]isTrueby induction. The trie walk fromifollows the exact characters oftext[i:j], a path that exists because the word is in the trie. The walk reaches the terminal node and marksj. No valid tiling is missed.
Complexity
Let W = total characters across all words in vocab, n = len(text), L = length of the longest word.
- Building the trie: O(W) time and space.
- DP: each walk from a reachable
starttakes at mostmin(L, n − start)steps with one dictionary lookup per step. Total: O(n · min(n, L)). - Overall: O(W + n · min(n, L)) time, O(W + n) space.
The early break on a missing child means most walks terminate well before L steps in practice.
Edge cases
textequals a single vocab word: the walk from 0 hits a terminal at positionnand returnsTrueimmediately.- A character of
textthat appears in no vocab word: the walk from thatstartdies on the first step. - Words that are prefixes of other words (
"cat"/"cats"): both are handled by independent terminal flags on the same trie path. - Vocab words longer than
text: the walk is bounded byn, so they are naturally skipped. - Highly repetitive input (
"aaaa...ab"with["a","aa","aaa",...]): backtracking without memoization blows up exponentially here; this DP visits eachstartexactly once, keeping the runtime polynomial.
Reference solution
from typing import List
def can_tile_with_vocab(text: str, vocab: List[str]) -> bool:
# Build a trie from all vocabulary words.
# Each node is a dict with a child map and a terminal flag.
trie = [{"next": {}, "terminal": False}]
for word in vocab:
node = 0
for ch in word:
nxt = trie[node]["next"].get(ch)
if nxt is None:
nxt = len(trie)
trie[node]["next"][ch] = nxt
trie.append({"next": {}, "terminal": False})
node = nxt
trie[node]["terminal"] = True
n = len(text)
# reachable[i] = True means text[:i] can be fully tiled.
reachable = [False] * (n + 1)
reachable[0] = True # empty prefix is trivially tiled
for start in range(n):
if not reachable[start]:
continue # nothing can extend from an unreachable position
node = 0
for end in range(start, n):
nxt = trie[node]["next"].get(text[end])
if nxt is None:
# No vocab word continues along this path; stop early.
break
node = nxt
if trie[node]["terminal"]:
# text[start:end+1] is a complete vocab word.
reachable[end + 1] = True
if end + 1 == n:
return True # whole string is tiled
return reachable[n]