Smallest Sentence from a Spaceless String and Word List
Dynamic ProgrammingAuto-graded · 23 test casesLast updated
Segment a spaceless string into dictionary words and return the lexicographically smallest valid sentence, or None if impossible; tests suffix DP plus greedy reconstruction.
Restore the Smallest Sentence
A piece of text has had all of its spaces removed. You are given the resulting string text and a list vocab of allowed words. Your job is to put spaces back so that every resulting piece is an allowed word, and to return the resulting sentence.
Each allowed word may be used as many times as you like.
Definition of a valid sentence
A valid sentence is a sequence of words w1, w2, ..., wm with m >= 1 such that:
- every
wiappears invocab, and - concatenating them (with no separators) gives exactly
text.
The sentence is written by joining the words with a single space between consecutive words.
Which sentence to return
Several valid sentences may exist. Return the one that is smallest under ordinary string comparison of the finished sentences, where the space character sorts before every lowercase letter.
Every valid sentence contains the same letters in the same order and differs only in where the spaces are placed, so this is equivalent to preferring the shortest possible first word, then the shortest possible second word, and so on.
If no valid sentence exists, return None.
Function
Implement smallest_sentence(text, vocab) that returns the smallest valid sentence as a string, or None if there is none.
Constraints
1 <= len(text) <= 20001 <= len(vocab) <= 10001 <= len(word) <= 20for every word invocabtextand every word invocabconsist only of lowercase lettersatoz.- All words in
vocabare distinct.
Examples
Example 1
Input: smallest_sentence('icecreamcone', ['ice', 'cream', 'icecream', 'cone', 'creamcone'])
Output: 'ice cream cone'
Example 2
Input: smallest_sentence('goodday', ['good', 'go', 'odd'])
Output: None
Example 3
Input: smallest_sentence('abab', ['ab', 'a', 'b'])
Output: 'a b a b'
Hints
Hint 1
First decide whether a split exists at all: define a boolean for each suffix of the text saying whether that suffix can be fully split into vocabulary words.
Hint 2
Because all valid sentences have the same letters, the string comparison reduces to comparing word lengths from left to right: an earlier space wins. So prefer the shortest next word.
Hint 3
Taking the shortest matching word is only safe if the rest can still be completed. Use the suffix feasibility table to skip words that lead to a dead end, then build the answer from left to right.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two parts: deciding whether a split exists, and picking the smallest one.
Feasibility. Let ok[i] be true when the suffix text[i:] can be split completely into vocabulary words. The empty suffix is trivially splittable, so ok[n] = True. Going from right to left, ok[i] is true if there is some word length L such that text[i:i+L] is a vocabulary word and ok[i+L] is true. Only the distinct word lengths present in the vocabulary (at most 20) need to be tried, and lengths that run past the end of the text can be skipped.
If ok[0] is false, return None.
Choosing the smallest sentence. All valid sentences contain the same letters in the same order, so two different sentences agree until the first position where one has a space and the other has a letter. A space sorts before any lowercase letter, so the sentence with the earlier word boundary is smaller. In other words, the sentence whose first differing word is shorter wins.
So starting at position 0, repeatedly take the shortest vocabulary word that matches at the current position and whose remaining suffix is still splittable (ok[i+L]). Then jump forward and repeat until the end.
Why it is correct
The comparison between two sentences is decided at the first word where they differ, and the shorter word wins. Hence the best sentence must start with the shortest first word that can still be completed into a valid sentence; the ok table tells us exactly which first words can be completed. After fixing that word, the remaining problem is the same problem on the suffix, so the same argument applies inductively. Because we only move to positions where ok is true, the greedy loop never gets stuck. A shorter word that leads to a dead end (for example "a" in text = "abc", vocab = ["a", "abc"]) is correctly rejected by the feasibility check.
Complexity
With n = len(text), at most 20 distinct word lengths and words of length at most 20:
- Time:
O(n * K * Lmax)withK, Lmax <= 20, about 800k basic operations at most, plus building the set. - Space:
O(n)for the table and output, plus the space of the vocabulary set.
Reference solution
from typing import List, Optional
def smallest_sentence(text: str, vocab: List[str]) -> Optional[str]:
words = set(vocab)
lens = sorted({len(w) for w in words})
n = len(text)
# ok[i] is True iff text[i:] can be split entirely into vocabulary words.
ok = [False] * (n + 1)
ok[n] = True
for i in range(n - 1, -1, -1):
for L in lens:
if i + L > n:
break
if ok[i + L] and text[i:i + L] in words:
ok[i] = True
break
if not ok[0]:
return None
out = []
i = 0
while i < n:
for L in lens:
if i + L <= n and ok[i + L] and text[i:i + L] in words:
out.append(text[i:i + L])
i += L
break
return ' '.join(out)