Insert Spaces to Rebuild a Sentence from Dictionary Words
MicrosoftApplied Scientist · OnsiteLast updated
A coding question that asks you to insert spaces into a string that lost them so that every piece is a dictionary word, returning the smallest valid sentence or None when no split exists. It tests string segmentation with dictionary lookups, handling of impossible inputs, and a canonical tie-breaking rule.
You are given a string s whose spaces were lost and a list of dictionary words. Insert spaces into s so that it splits into a sequence of words that are all in the dictionary, and return the resulting sentence. Dictionary words may be used any number of times. If no such split exists, return None.
Function Signature
def reconstruct_sentence(s: str, dictionary: list[str]) -> str | None:
Rules
- A valid sentence is words
w1, ..., wm(withm >= 1) joined by single spaces, where every word is indictionaryand the concatenationw1 + ... + wmequalss. - If several valid sentences exist, return the smallest one under ordinary string comparison, where the space character sorts before every lowercase letter. Because every valid sentence spells the same letters, this is the same as preferring the shortest possible first word, then the shortest possible second word, and so on.
- Return
Nonewhen no valid sentence exists.
Constraints
1 <= len(s) <= 20001 <= len(dictionary) <= 10001 <= len(word) <= 20for every dictionary wordsand every dictionary word consist only of lowercase English lettersatoz.- Dictionary words are distinct.
Examples
Example 1
Input: s = "icecreamcone", dictionary = ["ice", "cream", "icecream", "cone", "creamcone"]
Output: "ice cream cone"
There are three valid sentences: "ice cream cone", "ice creamcone" and "icecream cone". The first is the smallest: it starts with the shorter word "ice", and its second word "cream" is shorter than "creamcone".
Example 2
Input: s = "goodday", dictionary = ["good", "go", "odd"]
Output: None
After "good" the rest is "day", and after "go" and "odd" the rest is "ay"; neither is a dictionary word, so no split works.
Example 3
Input: s = "abab", dictionary = ["ab", "a", "b"]
Output: "a b a b"
The valid sentences are "a b a b", "a b ab", "ab a b" and "ab ab"; words may repeat, and the smallest is "a b a b".
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.