SDE & MLE Prep

2707. Extra Characters in a String

Problem

Split s into non-overlapping substrings that are words of dictionary; characters not covered by any word are "extra". Return the minimum possible number of extra characters.

Example: s = "leetscode", dictionary = ["leet","code","leetcode"] → 1 (the s)

Constraints: length ≤ 50; up to 50 words.

Word Break, minimized: dp[i] = fewest extra characters in s[i:]. Either skip s[i] (cost 1 + dp[i+1]) or, for every dictionary word starting at i, jump past it for free. A trie over the dictionary avoids rebuilding substrings.

Complexity: O(n² · L) with substring hashing (n, L ≤ 50).

class Solution:
    def minExtraChar(self, s: str, dictionary: List[str]) -> int:
        words, n = set(dictionary), len(s)
        dp = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            dp[i] = 1 + dp[i + 1]
            for j in range(i + 1, n + 1):
                if s[i:j] in words:
                    dp[i] = min(dp[i], dp[j])
        return dp[0]