πDay 23. Word Break π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
You are given a string s and a list dictionary[] of words. Your task is to determine whether the string s can be formed by concatenating one or more words from the dictionary[].
Note: From dictionary[], any word can be taken any number of times and in any order.
π Example Walkthrough:
Example 1:
Input:
s = "ilike"
dictionary[] = ["i", "like", "gfg"]Output:
trueExplanation:
The given string s can be broken down as "i like" using words from the dictionary.
Example 2:
Input:
Output:
Explanation:
The given string s can be broken down as "i like gfg" using words from the dictionary.
Example 3:
Input:
Output:
Explanation:
The given string s cannot be formed using the dictionary words.
Constraints:
$( 1 \leq |s| \leq 3000 )$
$( 1 \leq |dictionary| \leq 1000 )$
$( 1 \leq |dictionary[i]| \leq 100 )$
π― My Approach:
Dynamic Programming
Algorithm Steps:
Use a boolean DP vector
dpof size n+1 wheredp[i]indicates if the substrings[0...i-1]can be segmented.Insert dictionary words into an unordered set for O(1) lookups.
Iterate through the string and check all possible substrings using the dictionary.
If a valid word is found and its prefix was segmentable, mark
dp[i+j]as true.Return
dp[n].
π Time and Auxiliary Space Complexity
Expected Time Complexity: $( O(n \times m) )$, as each substring is checked in the dictionary.
Expected Auxiliary Space Complexity: $( O(n) )$, as we use a DP array of size
n+1.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated