|
| 1 | +The question is a perfect example of a problem where the interviewee can ask for |
| 2 | +clarification questions. |
| 3 | + |
| 4 | +For example, can the same word in the dictionary of words be used multiple times? |
| 5 | +If this were false, the solution could go in an entirely different direction. |
| 6 | + |
| 7 | +I tried to think of a brute force solution, and the idea that clicked was to figure |
| 8 | +out the smallest length string from the left that is a possible word in the dictionary, |
| 9 | +then I just have a smaller problem of checking whether a smaller string (left over) |
| 10 | +can be segmented into different dictionary words. |
| 11 | + |
| 12 | +Once we hit a deadpoint, that is the current string cannot be a dictionary word or segmented |
| 13 | +into one, we can return 0, and during backtracking we will try with a larger length |
| 14 | +string that is possible. |
| 15 | + |
| 16 | +Then, the realization comes that this problem can have overlapping subproblems. |
| 17 | +For e.g. the string 'catsandog' leads to a smaller subproblem 'andog' provided that 'cats' |
| 18 | +is a word in the dictionary. |
| 19 | +Now, 'andog' leads to the word 'dog' provided 'an' is in the dictionary. |
| 20 | +So, 'catsandog' can lead to the smaller subproblem 'dog' directly in one step provided |
| 21 | +'catsan' is a word in the dictionary, during the backtracking step. |
| 22 | + |
| 23 | +So, now the think is how many states should be memoized? |
| 24 | +Clearly, the recursion here just contains the string, and just the starting index of the |
| 25 | +string seems to be sufficient. |
| 26 | + |
| 27 | +So, we can now even think of an iterative DP solution. |
| 28 | + |
| 29 | +Let us denote canBreak[i] as true if we can break the string starting from the i-th index |
| 30 | +using the words in the dictionary. |
| 31 | + |
| 32 | +So, the recursive step can be expressed as: |
| 33 | +canBreak[i] = (OR from k = i+1 to n): canBreak[i + k] AND isWord[i..(i+k)] |
| 34 | + |
| 35 | +The above expression with handling some boundary cases and verifying it mathematically, |
| 36 | +is just what we were trying to do recursively, when we get the smallest word matching, |
| 37 | +we moved to solving a new problem, now we can simply remember the solution to all smaller |
| 38 | +problems and use them whenever needed. |
| 39 | + |
| 40 | +The time complexity of the above solution can be verified to be O(N^2). |
| 41 | +And, we are using an extra space of O(N) to build this, so comes the space complexity as O(N). |
| 42 | + |
| 43 | +I was thinking whether we could further optimize the solution. |
| 44 | +But, for that we need to somehow think of getting rid of the loop on k in the above |
| 45 | +recursive expression, but wasn't able to think of any idea to do that! |
0 commit comments