Extra Characters in a String - Problem
You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary. There may be some extra characters in s which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s optimally.
Input & Output
Example 1 — Basic Case
$
Input:
s = "leetscode", dictionary = ["leet", "code", "leetcode"]
›
Output:
1
💡 Note:
We can break s into "leet" + "s" + "code". The character "s" is not in the dictionary, so we have 1 extra character.
Example 2 — Perfect Match
$
Input:
s = "sayhelloworld", dictionary = ["hello", "world"]
›
Output:
3
💡 Note:
We can break s into "say" + "hello" + "world". The substring "say" has 3 extra characters.
Example 3 — No Dictionary Words
$
Input:
s = "abc", dictionary = ["def", "ghi"]
›
Output:
3
💡 Note:
No words from dictionary can be used, so all 3 characters are extra.
Constraints
- 1 ≤ s.length ≤ 50
- 1 ≤ dictionary.length ≤ 50
- 1 ≤ dictionary[i].length ≤ 50
- dictionary[i] and s consist of only lowercase English letters
- dictionary contains distinct words
Visualization
Tap to expand
Understanding the Visualization
1
Input
String "leetscode" and dictionary ["leet", "code", "leetcode"]
2
Process
Find optimal way to use dictionary words and minimize extra characters
3
Output
Minimum extra characters = 1
Key Takeaway
🎯 Key Insight: Use dynamic programming to find the optimal way to split the string, minimizing characters that don't belong to any dictionary word.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code