June 20th 2023
Problem Description permalink
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Solution permalink
function expect(description: string, test: boolean) {
if (test) {
console.log(`✅ ${description}`)
} else {
console.log(`❌ ${description}`)
}
}
function reverseWords(s: string): string {
return s
.trim()
.split(/\s+/g)
.reverse()
.join(" ")
}
expect("Simple example", reverseWords("the sky is blue") == "blue is sky the")
expect("Leading and trailing space", reverseWords(" hello world ") == "world hello")
expect("complex spacing", reverseWords("a good example") == "example good a")
Discussion permalink
This problem was a quick warmup stretch. It helps that my life is regular expressions right now so it was immediately obvious that this was going to need a regex to split on space. Really this function does two things- it's doing a string sanitization on an input (removing leading and trailing space, breaking up into tokens based on a space delimeter) AND THEN it's doing a reversal. If this was something to be shipped in production I would be very tempted to break up those responsibilities into several functions so that they could be tested (maybe sanitize
, tokenize
, reverseWords
). For this little stretch, though, it's ok for all of those concerns to live together in a single function.