|
| 1 | +''' |
| 2 | +Word Break (Find the original words) |
| 3 | +
|
| 4 | +Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. |
| 5 | +If there is more than one possible reconstruction, return solution with less words. |
| 6 | +If there is no possible reconstruction, then return null. |
| 7 | +
|
| 8 | +Input: sentence = 'thequickbrownfox', words = ['quick', 'brown', 'the', 'fox'] |
| 9 | +Output: ['the', 'quick', 'brown', 'fox'] |
| 10 | +
|
| 11 | +Input: sentence = 'bedbathandbeyond', words = ['bed', 'bath', 'bedbath', 'and', 'beyond'] |
| 12 | +Output: ['bedbath', 'and', 'beyond'] (['bed', 'bath', 'and', 'beyond] has more words) |
| 13 | +
|
| 14 | +========================================= |
| 15 | +Optimized dynamic programming solution (more simpler solutions can be found here https://www.geeksforgeeks.org/word-break-problem-dp-32/) |
| 16 | + Time Complexity: O(N*M) , N = number of chars in the sentence, M = max word length |
| 17 | + Space Complexity: O(N+W) , W = number of words |
| 18 | +Bonus solution: Backtracking, iterate the sentence construct a substring and check if that substring exist in the set of words. |
| 19 | +If the end is reached but the last word doesn't exist in the words, go back 1 word from the result (backtracking). |
| 20 | + Time Complexity: O(?) , (worst case, about O(W! * N), for example sentence='aaaaaac', words=['a','aa','aaa','aaaa','aaaaa', 'aaaaaa']) |
| 21 | + Space Complexity: O(W) |
| 22 | +''' |
| 23 | + |
| 24 | + |
| 25 | +############ |
| 26 | +# Solution # |
| 27 | +############ |
| 28 | + |
| 29 | +import math |
| 30 | + |
| 31 | +def word_break(sentence, words): |
| 32 | + n, w = len(sentence), len(words) |
| 33 | + if (n == 0) or (w == 0): |
| 34 | + return None |
| 35 | + |
| 36 | + dw = [-1 for i in range(n + 1)] |
| 37 | + dp = [math.inf for i in range(n + 1)] |
| 38 | + dp[0] = 0 |
| 39 | + matched_indices = [0] |
| 40 | + |
| 41 | + dic = {} # save all words in dictionary for faster searching |
| 42 | + max_word = 0 # length of the max word |
| 43 | + for i in range(w): |
| 44 | + dic[words[i]] = i |
| 45 | + max_word = max(max_word, len(words[i])) |
| 46 | + |
| 47 | + for i in range(1, n + 1): |
| 48 | + matched = False |
| 49 | + # start from the back of the matched_indices list (from the bigger numbers) |
| 50 | + for j in range(len(matched_indices) - 1, -1, -1): |
| 51 | + matched_index = matched_indices[j] |
| 52 | + # break this loop if the subsentence created with this matched index is bigger than the biggest word |
| 53 | + if matched_index < i - max_word: |
| 54 | + break |
| 55 | + |
| 56 | + subsentence = sentence[matched_index: i] |
| 57 | + # save this result if this subsentence exist in the words and number of words that forms sentence is smaller |
| 58 | + if (subsentence in dic) and (dp[matched_index] + 1 < dp[i]): |
| 59 | + dp[i] = dp[matched_index] + 1 |
| 60 | + dw[i] = dic[subsentence] |
| 61 | + matched = True |
| 62 | + |
| 63 | + if matched: |
| 64 | + matched_indices.append(i) |
| 65 | + |
| 66 | + # the sentence can't be composed from the given words |
| 67 | + if dp[n] == math.inf: |
| 68 | + return None |
| 69 | + |
| 70 | + # find the words that compose this sentence |
| 71 | + result = ['' for i in range(dp[n])] |
| 72 | + i = n |
| 73 | + j = dp[n] - 1 |
| 74 | + while i > 0: |
| 75 | + result[j] = words[dw[i]] |
| 76 | + i -= len(words[dw[i]]) |
| 77 | + j -= 1 |
| 78 | + |
| 79 | + return result |
| 80 | + |
| 81 | + |
| 82 | +######################### |
| 83 | +# Solution Backtracking # |
| 84 | +######################### |
| 85 | + |
| 86 | +from collections import deque |
| 87 | + |
| 88 | +def word_break_backtracking(sentence, words): |
| 89 | + all_words = set() |
| 90 | + |
| 91 | + # create a set from all words |
| 92 | + for i in range(len(words)): |
| 93 | + all_words.add(words[i]) |
| 94 | + |
| 95 | + n = len(sentence) |
| 96 | + i = 0 |
| 97 | + subsentence = '' |
| 98 | + result = deque() |
| 99 | + |
| 100 | + # go letter by letter and save the new letter in subsentence |
| 101 | + while (i < n) or (len(subsentence) != 0): |
| 102 | + # if there are no left letters in the sentence, then this combination is not valid |
| 103 | + # remove the last word from the results and continue from that word |
| 104 | + if i == n: |
| 105 | + i -= len(subsentence) |
| 106 | + # if there are no words in the result, then this string is not composed only from the given words |
| 107 | + if len(result) == 0: |
| 108 | + return None |
| 109 | + subsentence = result[-1] |
| 110 | + result.pop() |
| 111 | + |
| 112 | + # add the new letter into subsentence and remove it from the sentence |
| 113 | + subsentence += sentence[i] |
| 114 | + i += 1 |
| 115 | + |
| 116 | + # check if the new word exist in the set |
| 117 | + if subsentence in all_words: |
| 118 | + result.append(subsentence) |
| 119 | + subsentence = '' |
| 120 | + |
| 121 | + return list(result) |
| 122 | + |
| 123 | + |
| 124 | +########### |
| 125 | +# Testing # |
| 126 | +########### |
| 127 | + |
| 128 | +# Test 1 |
| 129 | +# Correct result => ['the', 'quick', 'brown', 'fox'] |
| 130 | +print(word_break('thequickbrownfox', ['quick', 'brown', 'the', 'fox'])) |
| 131 | + |
| 132 | +# Test 2 |
| 133 | +# Correct result => ['bedbath', 'and', 'beyond'] |
| 134 | +print(word_break('bedbathandbeyond', ['bed', 'bath', 'bedbath', 'and', 'beyond'])) |
| 135 | + |
| 136 | +# Test 3 |
| 137 | +# Correct result => ['bedbath', 'andbeyond'] |
| 138 | +print(word_break('bedbathandbeyond', ['bed', 'and', 'bath', 'bedbath', 'bathand', 'beyond', 'andbeyond'])) |
| 139 | + |
| 140 | +# Test 4 |
| 141 | +# Correct result => None ('beyo' doesn't exist) |
| 142 | +print(word_break('bedbathandbeyo', ['bed', 'bath', 'bedbath', 'bathand', 'beyond'])) |
| 143 | + |
| 144 | +# Test 5 |
| 145 | +# Correct result => ['314', '15926535897', '9323', '8462643383279'] |
| 146 | +print(word_break('3141592653589793238462643383279', ['314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793'])) |
| 147 | + |
| 148 | +# Test 6 |
| 149 | +# Correct result => ['i', 'like', 'like', 'i', 'mango', 'i', 'i', 'i'] |
| 150 | +print(word_break('ilikelikeimangoiii', ['mobile', 'samsung', 'sam', 'sung', 'man', 'mango', 'icecream', 'and', 'go', 'i', 'like', 'ice', 'cream'])) |