Extra Characters in a String

Medium · Tries · Array · Hash Table · String · Dynamic Programming · Trie

Problem

You are given a string s and an array of distinct words dictionary. Cut s into non-overlapping pieces so that some pieces are words in dictionary; the characters not covered by any chosen word are extra characters. A word may be used any number of times.

Return the minimum number of extra characters left over when s is split as well as possible.

Examples

Input: s = "catxdogs", dictionary = ["cat","dog","dogs"]
Output: 1

Use "cat" and "dogs"; only the x is left over.

Input: s = "moonlight", dictionary = ["moon","light","ligh"]
Output: 0

"moon" + "light" covers the whole string.

Input: s = "abc", dictionary = ["d"]
Output: 3

No word appears, so every character is extra.

Constraints

Approaches

Follow-up

The same DP answers related questions by changing what the two moves cost. The use cases forbid leftovers and count the fewest words that spell s (or report that none do), and charge each leftover letter by its place in the alphabet.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…