Extra Characters in a String (LeetCode 2707): Solution and Explanation
Cover as much of s as you can with non-overlapping dictionary words and count the letters left uncovered. For s = "leetscode" with ["leet","code","leetcode"], the best split is leet + code, leaving only the s, so the answer is 1.
Intuition
This is Word Break with forgiveness: letters are allowed to stay uncovered, but each one costs 1. You want the cheapest way to process the whole string.
Look at the last letter of a prefix. Either it is extra, and the cost is the best answer for the prefix one shorter plus 1, or it is the last letter of some dictionary word s[j:i], and the cost is the best answer for the first j letters.
That gives dp[i] = min(dp[i - 1] + 1, dp[j] for every word s[j:i]). With a hash set of the words and n <= 50, trying every j is cheap.
Approach: Prefix DP over end positions
- Put the dictionary in a hash set and create
dpof sizen + 1withdp[0] = 0. - For each
ifrom 1 ton, start withdp[i] = dp[i - 1] + 1(letteri - 1is extra). - For each
j < i, ifs[j:i]is a dictionary word, setdp[i] = min(dp[i], dp[j]). - Return
dp[n].
Step-by-step example
s = "leetscode", dictionary = ["leet","code","leetcode"]
- dp[1..3] = 1, 2, 3: no word ends at l, e or e.
- i = 4: skipping costs 4, but "leet" = s[0:4] is a word, so dp[4] = dp[0] = 0.
- i = 5: no word ends at "s", so dp[5] = dp[4] + 1 = 1.
- i = 6..8 grow to 2, 3, 4 because no word ends there.
- i = 9: "code" = s[5:9] gives dp[5] = 1. "leetcode" is not a substring here. dp[9] = 1, the answer.
Code: Python, Java, C++
1class Solution:
2 def minExtraChar(self, s: str, dictionary: List[str]) -> int:
3 words = set(dictionary)
4 n = len(s)
5 dp = [0] * (n + 1)
6 for i in range(1, n + 1):
7 dp[i] = dp[i - 1] + 1
8 for j in range(i):
9 if s[j:i] in words:
10 dp[i] = min(dp[i], dp[j])
11 return dp[n]1class Solution {
2 public int minExtraChar(String s, String[] dictionary) {
3 Set<String> words = new HashSet<>(Arrays.asList(dictionary));
4 int n = s.length();
5 int[] dp = new int[n + 1];
6 for (int i = 1; i <= n; i++) {
7 dp[i] = dp[i - 1] + 1;
8 for (int j = 0; j < i; j++) {
9 if (words.contains(s.substring(j, i))) {
10 dp[i] = Math.min(dp[i], dp[j]);
11 }
12 }
13 }
14 return dp[n];
15 }
16}1class Solution {
2public:
3 int minExtraChar(string s, vector<string>& dictionary) {
4 unordered_set<string> words(dictionary.begin(), dictionary.end());
5 int n = s.size();
6 vector<int> dp(n + 1, 0);
7 for (int i = 1; i <= n; i++) {
8 dp[i] = dp[i - 1] + 1;
9 for (int j = 0; j < i; j++) {
10 if (words.count(s.substr(j, i - j))) {
11 dp[i] = min(dp[i], dp[j]);
12 }
13 }
14 }
15 return dp[n];
16 }
17};Time and space complexity
O(n^3)
There are O(n^2) pairs (j, i), and building and hashing each substring costs O(n). With n <= 50 this is tiny.
O(n + L)
The dp array plus the hash set holding the L total dictionary characters.
Other approaches
Trie from each start (suffix DP) (time O(n^2 + L), space O(L))
Let dp[i] be the answer for s[i:]. From each i, walk a trie of the words forward along s; every word end at k gives dp[k + 1]. This avoids building substrings.
Memoized recursion (time O(n^3), space O(n))
solve(i) tries skipping s[i] or matching any word starting at i, caching results. Same recurrence written top-down.
Common mistakes
- Being greedy with the longest word. In
abcabwithab,abc,cab, takingabcfirst leavesab, which also works, but on other inputs the long word blocks a better split. Only the DP is safe. - Forgetting the skip option. Without
dp[i - 1] + 1, prefixes with no word ending at them have no valid value. - Off-by-one between letter indices and prefix lengths.
dp[i]covers letters0..i-1, and the words[j:i]excludes indexi.
Frequently asked questions
How is this different from Word Break?
Word Break asks whether the whole string can be covered, a yes or no DP. Here uncovered letters are allowed and you minimise how many there are, so the boolean becomes a count.
Do I need a trie?
Not for these limits. A hash set is enough when s has at most 50 letters. A trie helps when s is long and the words are short.
Can words overlap in the answer?
No. The DP chains non-overlapping pieces because each word s[j:i] continues from the answer for the first j letters, which ends before j.