Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created February 15, 2021 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylvainpolletvillard/bff98911471a27f513dbd68e926603e4 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/bff98911471a27f513dbd68e926603e4 to your computer and use it in GitHub Desktop.
pinapple pen interview question
/*
Given a string str and a dictionary dict containing a list of non-empty words, add spaces in str to construct a “sentence” where each word is a valid word in dict. Return all possible sentences. You are allowed to reuse the words in dict.
Example:
str = “penpineapplepenapple”
dict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
$ makeSentence(str, dict) $ [ “pen pine apple pen apple”, “pen pineapple pen apple”, “pen pine applepen apple” ]
*/
function makeSentence(str, dict){
const findWordsAtStart = str => dict.filter(word => str.startsWith(word))
const R = (str, sentences) => {
const words = findWordsAtStart(str)
if(str.length === 0 || words.length === 0) return sentences // end of recursion
return words.flatMap(word => {
const restOfStr = str.slice(word.length)
return R(restOfStr, sentences.map(s => s ? s + " " + word : word))
})
}
const sentences = [""]; // initial empty sentence
return R(str, sentences)
}
str = "penpineapplepenapple"
dict = ["apple", "pen", "applepen", "pine", "pineapple"]
makeSentence(str, dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment