Word Break (Trie + DP)

beginner
9 min

Word Break (Trie + DP)

Welcome to this comprehensive lesson on the Word Break problem! We'll learn how to solve this problem using a combination of Trie (Prefix Tree) and Dynamic Programming (DP). This lesson is designed for beginners and intermediates, so let's dive in!

What is Word Break Problem?

The Word Break problem is a common problem in computer science where we need to determine whether a given string can be broken into valid words from a given dictionary. A word is considered valid if it exists in the dictionary.

Why do we need Trie and Dynamic Programming?

Trie helps us efficiently store words from the dictionary and quickly search for words within the tree. Dynamic Programming allows us to solve the problem recursively, ensuring that the subproblems are solved only once.

Creating a Trie

Let's start by creating a Trie (Prefix Tree) to store our dictionary.

python
class TrieNode: def __init__(self): self.children = {} self.is_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_word = True

šŸ’” Pro Tip: A Trie node can have multiple children corresponding to different characters.

Implementing Dynamic Programming

Now, let's implement the Dynamic Programming part of our solution. We'll create a function canBreak that takes a string s and a Trie trie, and returns whether s can be broken into words from the dictionary.

python
def canBreak(s, trie, dp): if s in trie.root.children: return True if not s: return False for i in range(1, len(s) + 1): prefix = s[:i] if prefix in trie.root.children: if dp[prefix] != -1: return True subproblem_solution = canBreak(s[i:], trie, dp) if subproblem_solution: dp[prefix] = i return False

šŸ“ Note: We use a dp dictionary to store the length of the longest prefix that can be broken into words, helping us avoid redundant calculations.

Putting it all together

Now that we have our Trie and Dynamic Programming functions, we can solve the Word Break problem.

python
def solve(words): trie = Trie() for word in words: trie.insert(word) s = "leetcodecodingcontest" dp = [-1] * (len(s) + 1) result = canBreak(s, trie, dp) return result

šŸŽÆ Quiz Time:

Quick Quiz
Question 1 of 1

What is the main purpose of the Trie in our Word Break solution?

That's it for today! Now you have a solid understanding of how to solve the Word Break problem using a Trie and Dynamic Programming. Keep practicing and happy coding! šŸš€