Replace Words

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

Problem

A root is a word that can be extended into longer words. For example, the root "help" followed by "ful" forms "helpful".

You are given a list of roots dictionary and a string sentence of words separated by single spaces. Replace every word that has a root from the dictionary as a prefix with that root. If several roots are prefixes of a word, use the shortest. Words with no root stay unchanged.

Return the sentence after all replacements.

Examples

Input: dictionary = ["sun","sunf","rain"], sentence = "sunflowers need rainy days"
Output: "sun need rain days"

"sunflowers" starts with both "sun" and "sunf"; the shorter one wins. "rainy" becomes "rain".

Input: dictionary = ["x","y"], sentence = "yes xray zed"
Output: "y x zed"

"zed" has no root, so it stays.

Input: dictionary = ["cat","catalog"], sentence = "cats catalogs ca"
Output: "cat cat ca"

"cat" is the shortest root of the first two words; "ca" is shorter than every root and stays.

Constraints

Approaches

Follow-up

What if the longest root should win, or roots matched the end of words instead of the start? The use cases change one detail of the walk each.

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…