KatInterview

Tile a Word Using a Vocabulary List

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstringstrie

Last 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 vocab may be used any number of times.
  • Words must be placed consecutively from left to right; they cannot overlap or be rearranged.
  • Return True if at least one valid tiling exists, False otherwise.

Constraints

  • 1 <= len(text) <= 10^4
  • 1 <= len(vocab) <= 10^5
  • Every string in vocab is non-empty.
  • Characters are lowercase English letters.
  • The combined length of all words in vocab can 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.