Ctrl K

Fewest Stray Letters

Medium
You are given a string text with no spaces and a vocabulary vocab of distinct words. Cut out some non-overlapping pieces of the text so that every piece is a word from the vocabulary. The same word may be used any number of times. Letters that end up in no piece are stray. Return the smallest possible number of stray letters.
Example 1
text="sunxflower", vocab=["sun", "flow", "flower", "er"] → 1

Take sun and flower (or flow and er), and only the x is left over.

Example 2
text="catalog", vocab=["cat", "log", "tal"] → 1

cat and tal overlap, and pieces may not share letters. The best choice is cat + log, leaving a single a.

Example 3
text="qq", vocab=["q", "qqq"] → 0
Constraints
  • 1 ≤ len(text) ≤ 50
  • 1 ≤ len(vocab) ≤ 50
  • 1 ≤ len(vocab[i]) ≤ 50
  • text and the vocabulary words consist of lowercase English letters
  • All words in vocab are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit Into Dictionary Words MediumWords Hidden in a Text MediumEvery Way to Space the Words HardHighlight Search Hits MediumShorten Words to Their Roots Medium
loading Python…
Input
text="sunxflower", vocab=["sun", "flow", "flower", "er"]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.