Extra Characters in a String - Problem
You're given a string s and a dictionary of valid words. Your goal is to break down the string into dictionary words with the minimum number of leftover characters.
Think of it like a word puzzle: you want to use as many characters as possible to form valid dictionary words, leaving behind the fewest "extra" characters that can't be used.
Example: If s = "leetscode" and dictionary = ["leet", "code", "leetcode"], you could break it as:
- "leet" + "code" → uses 8 characters, 0 extra ✅
- "leetcode" → uses 8 characters, 0 extra ✅
- Skip breaking → uses 0 characters, 9 extra ❌
Return the minimum number of extra characters when you break the string optimally.
Input & Output
example_1.py — Basic Word Matching
$
Input:
s = "leetscode", dictionary = ["leet","code","leetcode"]
›
Output:
0
💡 Note:
We can break "leetscode" as "leet" + "code" using both dictionary words, leaving 0 extra characters. Alternatively, we could use "leetcode" + skip "s" + skip "code" but that would give us 1 extra character.
example_2.py — Some Extra Characters
$
Input:
s = "sayhelloworld", dictionary = ["hello","world"]
›
Output:
3
💡 Note:
We can break it as: skip "s", skip "a", skip "y", "hello", "world". This leaves us with 3 extra characters (s, a, y) that couldn't be matched with any dictionary words.
example_3.py — No Dictionary Matches
$
Input:
s = "xyz", dictionary = ["abc","def"]
›
Output:
3
💡 Note:
None of the characters in "xyz" can form any dictionary words, so all 3 characters are extra.
Constraints
- 1 ≤ s.length ≤ 50
- 1 ≤ dictionary.length ≤ 50
- 1 ≤ dictionary[i].length ≤ 50
- s and dictionary[i] consist of only lowercase English letters
- dictionary contains distinct words
Visualization
Tap to expand
Understanding the Visualization
1
Scan Position
Start from each position in the string
2
Try Dictionary Words
Check if any dictionary word can fit starting at current position
3
Make Decision
Either skip character (add to extras) or use a valid dictionary word
4
Optimize Recursively
Use memoization to remember best results for each position
Key Takeaway
🎯 Key Insight: At each position, we make an optimal choice between skipping (1 extra) or using dictionary words, building up the solution using previously computed results through dynamic programming.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code