📖 Scenario: Imagine you have a long string of letters without spaces, and you want to check if it can be split into meaningful words from a dictionary. This is like trying to read a sentence where all spaces are missing and figuring out if it can be broken down into real words.
🎯 Goal: You will build a program that checks if a given string can be segmented into a sequence of dictionary words using a simple approach.
📋 What You'll Learn
Create a vector of strings called dictionary with exact words: "apple", "pen", "pine", "pineapple"
Create a string variable called input_string with the exact value "pineapplepenapple"
Write a function called canBreak that takes input_string and dictionary and returns true if the string can be segmented into dictionary words, otherwise false
Print "Yes" if the string can be segmented, otherwise print "No"
💡 Why This Matters
🌍 Real World
This problem is useful in text processing, such as spell checking, auto-correct, and natural language processing where spaces might be missing or unclear.
💼 Career
Understanding this problem helps in software roles involving string manipulation, search algorithms, and dynamic programming techniques.
Progress0 / 4 steps
1
Create the dictionary vector
Create a vector of strings called dictionary with these exact words: "apple", "pen", "pine", "pineapple"
DSA C++
Hint
Use vector dictionary = {"apple", "pen", "pine", "pineapple"};
2
Create the input string
Create a string variable called input_string with the exact value "pineapplepenapple"
DSA C++
Hint
Use string input_string = "pineapplepenapple";
3
Write the canBreak function
Write a function called canBreak that takes input_string and dictionary as parameters and returns true if input_string can be segmented into dictionary words, otherwise false. Use a simple dynamic programming approach with a boolean vector called dp.
DSA C++
Hint
Use a boolean vector dp of size n+1 where dp[i] is true if substring s[0..i-1] can be segmented. Check all partitions.
4
Print the result
Print "Yes" if canBreak(input_string, dictionary) returns true, otherwise print "No"
DSA C++
Hint
Use if (canBreak(input_string, dictionary)) cout << "Yes" << endl; else cout << "No" << endl;
Practice
(1/5)
1. What does the Word Break Problem ask you to determine about a given string s and a dictionary of words wordDict?
easy
A. If s is exactly equal to one of the words in wordDict
B. If s contains any substring from wordDict
C. If s can be segmented into a space-separated sequence of one or more dictionary words
D. If s is a palindrome formed by dictionary words
Solution
Step 1: Understand the problem statement
The Word Break Problem asks if the entire string s can be split into parts where each part is a word from the dictionary wordDict.
Step 2: Differentiate from similar concepts
It is not enough for s to contain a dictionary word or be equal to one; the whole string must be fully segmented into dictionary words.
Final Answer:
If s can be segmented into a sequence of dictionary words -> Option C
Quick Check:
Word Break = Full segmentation check [OK]
Hint: Check if full string splits into dictionary words [OK]
Common Mistakes:
Thinking partial substring match is enough
Confusing exact match with segmentation
Ignoring the order of words in segmentation
2. Which of the following is the correct C++ syntax to declare a function named wordBreak that takes a string s and a vector<string> named wordDict and returns a bool?
easy
A. bool wordBreak(string s, vector<string> &wordDict);
B. bool wordBreak(string s, vector<string>& wordDict);
C. bool wordBreak(string s, vector<string> wordDict);
D. bool wordBreak(string s, vector<string> wordDict&);
Solution
Step 1: Understand parameter passing in C++
Passing vector<string> by reference requires the ampersand & after the type, with optional space before the variable name.
Step 2: Check syntax correctness
bool wordBreak(string s, vector<string> &wordDict); correctly places the ampersand before the parameter name with a space: vector<string> &wordDict. bool wordBreak(string s, vector<string>& wordDict); is also valid but less common spacing. bool wordBreak(string s, vector<string> wordDict&); is invalid syntax.
Final Answer:
bool wordBreak(string s, vector<string> &wordDict); -> Option A
Hint: Ampersand & goes between type and variable name [OK]
Common Mistakes:
Placing & after variable name incorrectly
Missing semicolon at function declaration
Using invalid syntax like wordDict&
3. What is the output of the following C++ code snippet?
bool wordBreak(string s, vector<string> &wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.size(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
int main() {
string s = "leetcode";
vector<string> wordDict = {"leet", "code"};
cout << (wordBreak(s, wordDict) ? "true" : "false") << endl;
return 0;
}
medium
A. true
B. false
C. Compilation error
D. Runtime error
Solution
Step 1: Understand the dynamic programming logic
The code uses a boolean vector dp where dp[i] is true if substring s[0..i-1] can be segmented into dictionary words. It initializes dp[0] as true (empty string).
Step 2: Trace the example input "leetcode" with dictionary ["leet", "code"]
At i=4, substring "leet" is in dictionary, so dp[4] = true. At i=8, substring "code" is in dictionary and dp[4] is true, so dp[8] = true. Finally, dp[s.size()] = true.
Final Answer:
true -> Option A
Quick Check:
DP segmentation confirms full string = true [OK]
Hint: Check dp array for full string index true [OK]
Common Mistakes:
Confusing substring indices
Forgetting to break inner loop after true
Misunderstanding dp initialization
4. Identify the bug in the following C++ code for the Word Break Problem:
bool wordBreak(string s, vector<string> &wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size(), false);
dp[0] = true;
for (int i = 1; i <= s.size(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
medium
A. dp[0] should be initialized to false
B. dp vector size should be s.size() + 1, not s.size()
C. The substring indices in s.substr are incorrect
D. unordered_set should be a vector instead
Solution
Step 1: Check dp vector size and indexing
The dp vector is sized to s.size(), but the code accesses dp[s.size()] which is out of bounds. It should be sized s.size() + 1 to include the base case for empty substring.
Step 2: Verify other parts
unordered_set usage and substring indices are correct. dp[0] must be true to represent empty string segmentation.
Final Answer:
dp vector size should be s.size() + 1, not s.size() -> Option B
Quick Check:
dp size off by one causes runtime error [OK]
Hint: dp size = string length + 1 for base case [OK]
Common Mistakes:
Using dp size equal to string length only
Misinitializing dp[0] to false
Confusing substring parameters
5. Given the string s = "applepenapple" and dictionary wordDict = ["apple", "pen"], which of the following modifications to the Word Break algorithm allows it to also return the actual segmented sentence "apple pen apple" instead of just true or false?
hard
A. Use a stack to store indices and print words in reverse order after DP
B. Return the count of possible segmentations instead of a boolean
C. Modify the dictionary to include spaces between words
D. Use a vector of strings to store sentences at each index and build them during DP
Solution
Step 1: Understand the limitation of boolean DP
The standard Word Break DP returns only true/false indicating if segmentation is possible, but does not store the actual segmented sentences.
Step 2: Modify DP to store sentences
By using a vector of strings at each dp index, we can store all possible sentences formed up to that index. When a valid word is found, append it to sentences from previous indices.
Step 3: Final answer
This approach allows reconstructing the segmented sentence like "apple pen apple".
Final Answer:
Use a vector of strings to store sentences at each index and build them during DP -> Option D
Quick Check:
Store sentences in DP to reconstruct output [OK]
Hint: Store sentences in DP array to reconstruct segmentation [OK]
Common Mistakes:
Trying to modify dictionary words
Returning count instead of sentences
Using stack without DP sentence storage
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.