Reverse Sentence - FreeCodeCamp #32 Daily Challenge
1 min
Reverse Sentence โ Analysis & Explanation ๐
Problem Statement
Given a string of words, return a new string with the words in reverse order. For example, the first word should be at the end and the last word at the beginning.
Conditions:
- Words may be separated by one or more spaces.
- The returned string must have only one space between each word.
Initial Analysis
What does the challenge ask?
Reverse the order of the words and normalize spaces. That is:
- Correctly split the words (ignoring extra spaces).
- Reorder and print them in reverse order, separated by a single space.
For this, JavaScriptโs split, reverse, and join methods are ideal.
Key Test Cases
- Input:
"world hello"โ Output:"hello world" - Input:
"push commit git"โ Output:"git commit push" - Input:
"npm install sudo"โ Output:"sudo install npm" - Input:
"import default function export"โ Output:"export function default import"
All cases normalize spaces and reverse the word order.
Solution Development
Strategy
- Split using
.split(/\s+/)to get only words. - Reverse the array.
- Join with
.join(' ')to ensure a single space.
JavaScript Implementation
function reverseSentence(sentence) {
return sentence
.trim() // Remove leading/trailing spaces
.split(/\s+/) // Split into words, ignore extra spaces
.reverse() // Reverse the array
.join(' ') // Join with a single space
}Complexity Analysis
Time
Each operation (trim, split, reverse, join) traverses the string or array once:
Space
Auxiliary arrays proportional to the input size are created:
Edge Cases & Considerations
- Empty string or only spaces: returns "" (empty).
- Leading/trailing spaces: are removed.
- Multiple spaces between words: normalized to one.
- Single word: returns the same, no extra spaces.
Reflections & Learnings
๐น Strings & arrays: efficient manipulation in JS. ๐น Regular expressions: robust against โmessyโ input. ๐น Functional composition: readable and compact code.
๐ก The solution is optimal and readable. No further optimizations needed.