![]() |
VOOZH | about |
Given an input string s and a dictionary dictionary[] containing a set of words, determine whether the string s can be segmented into a sequence of space-separated words that exist in the dictionary.
A string is considered segmentable if it can be broken down into a series of dictionary words, where each segment must match exactly one of the words in the dictionary. The string can be split at any position as long as the resulting substrings are valid words from the dictionary.
This is a famous Google interview question, also being asked by many other companies now a days.
Examples:
Input: s = "ilike", dictionary[] = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"]
Output: "Yes"
Explanation: The string"ilike"can be segmented into"i like", which consists of valid words"i"and"like"from the dictionary.Input: s = "ilikesamsung", dictionary[] = ["i", "like", "sam", "sung", "samsung", "mobile", "ice", "cream", "icecream", "man", "go", "mango"]
Output: "Yes"
Explanation: The string can be segmented as "i like samsung" or "i like samsung"
The solution discussed here is mainly an extension of below DP based solution.
Dynamic Programming | Set 32 (Word Break Problem)
In the above post, a simple array is used to store and search words in a dictionary. Here we use Trie to do these tasks quickly.
A Trie can efficiently store dictionary words and enable fast prefix matching. Each node represents a character, allowing quick checks for the existence of a prefix. By recursively trying all possible prefixes of a string, we can check if each prefix exists in the Trie. If a prefix is found, we then check if the remaining substring is also segmentable. This approach eliminates redundant checks and speeds up the process of determining if the string is segmentable.
Yes Yes Yes Yes Yes No
Time Complexity: O(n*m) where n is the length of the string and m is the length of the longest word in the dictionary.
Auxiliary Space: O(n*m)