Extra Characters in a String (LeetCode 2707): Solution and Explanation

Medium
Array
Hash Table
String
Dynamic Programming
Trie

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

  1. Put the dictionary in a hash set and create dp of size n + 1 with dp[0] = 0.
  2. For each i from 1 to n, start with dp[i] = dp[i - 1] + 1 (letter i - 1 is extra).
  3. For each j < i, if s[j:i] is a dictionary word, set dp[i] = min(dp[i], dp[j]).
  4. Return dp[n].

Step-by-step example

s = "leetscode", dictionary = ["leet","code","leetcode"]
  1. dp[1..3] = 1, 2, 3: no word ends at l, e or e.
  2. i = 4: skipping costs 4, but "leet" = s[0:4] is a word, so dp[4] = dp[0] = 0.
  3. i = 5: no word ends at "s", so dp[5] = dp[4] + 1 = 1.
  4. i = 6..8 grow to 2, 3, 4 because no word ends there.
  5. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 abcab with ab, abc, cab, taking abc first leaves ab, 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 letters 0..i-1, and the word s[j:i] excludes index i.

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.