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
Extra Characters in a String INPUT String s: l e e t s c o d e 0 1 2 3 4 5 6 7 8 Dictionary: "leet" "code" "leetcode" Optimal Split: "leet" "s" "code" Extra char: 's' at index 4 ALGORITHM (DP) 1 Define DP State dp[i] = min extra chars for s[0...i-1] 2 Initialize dp[0]=0 (empty string) 3 Transition For each i, try all j less than i: if s[j:i] in dict: dp[i]=min(dp[i],dp[j]) else: dp[i]=dp[i-1]+1 4 Return dp[n] Answer = dp[9] = 1 DP Table: i 0 1 2 3 4 5 ... 9 dp 0 1 2 3 0 1 ... 1 FINAL RESULT Optimal breakdown: leet + s + code Output: 1 Minimum extra characters left over = 1 Why not "leetcode"? "leetscode" != "leetcode" Extra 's' prevents full match Best: "leet" + "code" = 1 extra Key Insight: Use dynamic programming where dp[i] represents the minimum extra characters for substring s[0...i-1]. For each position, either mark current char as extra (dp[i-1]+1), or find a dictionary word ending at i and take dp[j] where j is the start of that word. Time: O(n^2 * m), Space: O(n) where m = max word length. TutorialsPoint - Extra Characters in a String | Dynamic Programming Approach
Asked in
Amazon 15 Google 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen