KatInterview

Smallest Sentence from a Spaceless String and Word List

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstringsgreedy

Last 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 wi appears in vocab, 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) <= 2000
  • 1 <= len(vocab) <= 1000
  • 1 <= len(word) <= 20 for every word in vocab
  • text and every word in vocab consist only of lowercase letters a to z.
  • All words in vocab are 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.