To determine if a given word ( w ) can be constructed by concatenating words from a dictionary (set), we can use dynamic programming. This problem is similar to the classic "word break" problem, where we check if a word can be segmented into a sequence of dictionary words.
Approach
-
Dynamic Programming (DP) Setup:
- Let ( dp[i] ) be a boolean array where ( dp[i] ) is
True if the substring ( w[0..i-1] ) can be segmented into dictionary words.
- Initialize ( dp[0] ) as
True because an empty string can always be segmented (base case).
- For each position ( i ) in the word ( w ), check all possible substrings ending at ( i ). If any substring ( w[j..i-1] ) is in the dictionary and ( dp[j] ) is
True, then set ( dp[i] ) to True.
-
Algorithm Steps:
- Initialize a DP array of size ( n+1 ) (where ( n ) is the length of ( w )) with
False.
- Set ( dp[0] = True ).
- For each ( i ) from 1 to ( n ):
- For each ( j ) from 0 to ( i-1 ):
- If ( dp[j] ) is
True and the substring ( w[j..i-1] ) is in the dictionary, set ( dp[i] = True ) and break out of the loop (since we only need one valid segmentation).
- The answer is ( dp[n] ), which indicates whether the entire word can be segmented.
Solution Code
def can_construct_word(w, dictionary):
n = len(w)
dp = [False] * (n + 1)
dp[0] = True # empty string
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
return dp[n]
Explanation
- Initialization: The DP array
dp is initialized to keep track of whether substrings up to each position can be segmented into dictionary words. The first element dp[0] is set to True because an empty string is trivially valid.
- Filling the DP Array: For each position ( i ) in the word, the algorithm checks all possible substrings ending at ( i ). If a substring ( w[j..i-1] ) is found in the dictionary and the substring up to ( j ) (i.e., ( w[0..j-1] )) can be segmented (indicated by
dp[j] being True), then dp[i] is set to True.
- Result: The value at
dp[n] (where ( n ) is the length of the word) tells us whether the entire word can be constructed from the dictionary words.
This approach efficiently checks all possible segmentations using dynamic programming, avoiding the exponential time complexity of a naive recursive solution. The time complexity is ( O(n^2) ) in the worst case, where ( n ) is the length of the word, and the space complexity is ( O(n) ) for the DP array.