To solve the problem of checking whether a given word w can be constructed by concatenating words from a given dictionary, we can use Dynamic Programming (DP).
🔍 Problem Summary
-
Input:
- A set of words
dict (i.e., the dictionary).
- A string
w (target word).
-
Goal:
- Return
True if w can be segmented into a sequence of one or more dictionary words, otherwise return False.
This is a classic Word Break Problem.
✅ Dynamic Programming Approach
We will use a DP array dp where:
dp[i] indicates whether the substring w[0:i] (up to index i, exclusive) can be segmented using dictionary words.
🔧 Algorithm Steps
- Initialize a DP array
dp of size len(w) + 1 with all values as False.
- Set
dp[0] = True (empty string is always "breakable").
- Iterate from
i = 1 to len(w):
- For each
j from 0 to i:
- If
dp[j] is True and w[j:i] is in the dictionary:
- Set
dp[i] = True and break.
- Return
dp[len(w)].
💡 Time & Space Complexity
- Time: O(n²), where
n is the length of the word (nested loop).
- Space: O(n), one DP array.
🧠 Python Code
def can_construct(w: str, dictionary: set) -> bool:
n = len(w)
dp = [False] * (n + 1)
dp[0] = True # Empty string can be formed
for i in range(1, n + 1):
for j in range(i):
if dp[j] and w[j:i] in dictionary:
dp[i] = True
break # No need to check further for this i
return dp[n]
✅ Example
dictionary = {"apple", "pen"}
word = "applepenapple"
print(can_construct(word, dictionary)) # Output: True
⛔ Edge Case
dictionary = {"cats", "dog", "sand", "and", "cat"}
word = "catsandog"
print(can_construct(word, dictionary)) # Output: False
🧪 Optional Enhancements
- Memoization (top-down): Can be used instead of bottom-up DP.
- Trie-based optimization: For very large dictionaries.
Let me know if you'd like to see those versions too.