KatInterview

Check if Text Can Be Built from Dictionary Words

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingtriestring-processingmemoization

Last 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) <= 300
  • 1 <= len(dictionary) <= 1000
  • 1 <= len(dictionary[i]) <= 20
  • text and dictionary[i] consist only of lowercase English letters
  • All words in dictionary are 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.