Skip to content

Commit a685c75

Browse files
committed
Add Word Break problem
1 parent af265ef commit a685c75

File tree

4 files changed

+123
-3
lines changed

4 files changed

+123
-3
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@ This repository contains the coding interview problems along with solutions.
33

44
| Problem | Solution | Code | Category | Difficulty |
55
|---------------|----------|------|----------|------------|
6-
| Island Count | | | | |
7-
| | | | | |
8-
| | | | | |
6+
| [Island Count](Island%20Count) | | [CPP](Island%20Count/solution.cpp) | Graph Traversal | Medium |
7+
| [Minimum Falling Path Sum](Minimum%20Falling%20Path%20Sum) | [text](Minimum%20Falling%20Path%20Sum/solution.txt) | [CPP](Minimum%20Falling%20Path%20Sum/solution.cpp) | Dynamic Programming | Medium |
8+
| [Word Break](Word%20Break) | [text](Word%20Break/solution.txt) | [CPP](Word%20Break/solution.cpp) | Dynamic Programming | Medium |

Word Break/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Word Break
2+
[Try the problem](https://leetcode.com/problems/word-break/)
3+
4+
Given a **non-empty** string s and a dictionary *wordDict* containing a list of **non-empty** words, determine if s can be segmented into a space-seperated sequence of one or more dictionary words.
5+
6+
**Note:**
7+
- The same word in the dictionary may be resued multiple times in the segmentation.
8+
- You may assume the dictionary does not contain duplicate words.
9+
10+
### Example 1
11+
12+
```
13+
Input: s = "leetcode", wordDict = ["leet", "code"]
14+
Output: true
15+
Explanation: Return true because "leetcode" can be segmented as "leet code".
16+
```
17+
18+
### Example 2
19+
20+
```
21+
Input: s = "applepenapple", wordDict = ["apple", "pen"]
22+
Output: true
23+
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
24+
Note that you are allowed to reuse a dictionary word.
25+
```
26+
27+
## Example 3
28+
29+
```
30+
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
31+
Output: false
32+
```

Word Break/solution.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <map>
4+
#include <string>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
bool wordBreak(string s, vector<string>& wordDict) {
10+
int n = s.length();
11+
// canBreak[i] denotes whether we can break the string starting from the i-th index
12+
bool canBreak[n];
13+
memset(canBreak, false, sizeof(canBreak));
14+
map<string, int> isWord;
15+
for (auto word: wordDict) {
16+
isWord[word] = 1;
17+
}
18+
for (int i = n - 1; i >= 0; --i) {
19+
string cur = s.substr(i, 1);
20+
bool canBreakCur = false;
21+
for (int k = i + 1; k < n; ++k) {
22+
canBreakCur |= canBreak[k] && isWord[cur];
23+
if (canBreakCur == true) {
24+
break;
25+
}
26+
cur += s[k];
27+
}
28+
if (isWord[cur]) {
29+
canBreakCur = true;
30+
}
31+
canBreak[i] = canBreakCur;
32+
}
33+
return canBreak[0];
34+
}
35+
};
36+
37+
int main() {
38+
Solution solver;
39+
vector<string> wordDict = {"a", "bcd", "cd"};
40+
cout << solver.wordBreak("abcd", wordDict) << endl; // 1
41+
cout << solver.wordBreak("acde", wordDict) << endl; // 0
42+
return 0;
43+
}

Word Break/solution.txt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)