Design Gurus Logo
Extra Characters in a String (medium)

Problem Statement

Given a string s and an array of words dictionary. Break string s into multiple non-overlapping substrings such that each substring should be part of the dictionary. There are some characters left which are not part of any substring.

Return the minimum number of remaining characters in s, which are not part of any substring after string break-up.

Examples

  1. Example 1:

    • Input: s = "amazingracecar", dictionary = ["race", "car"]
    • Expected Output: 7
    • Justification: The substrings are read in place; the characters are never reordered. "amazingracecar" contains "race" and then "car", one after the other, at the end of the string. Those 7 characters are covered. The 7 characters before them, 'a', 'm', 'a', 'z', 'i', 'n' and 'g', are not part of any dictionary word, so the answer is 7.
  2. Example 2:

    • Input: s = "bookkeeperreading", dictionary = ["keep", "read"]
    • Expected Output: 9
    • Justification: The words "keep" and "read" can be formed from s, but 'b', 'o', 'o', 'k', 'e', 'r', 'i', 'n', 'g' are extra.
  3. Example 3:

    • Input: s = "thedogbarksatnight", dictionary = ["dog", "bark", "night"]
    • Expected Output: 6
    • Justification: The words "dog", "bark", and "night" can be formed, leaving 't', 'h', 'e', 's', 'a', 't' as extra characters.

Constraints:

  • 1 <= s.length <= 50
  • 1 <= dictionary.length <= 50
  • 1 <= dictionary[i].length <= 50
  • dictionary[i] and s consists of only lowercase English letters
  • dictionary contains distinct words

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory