Reverse Words in a Sentence
Learn how to reverse the order of words in a sentence while keeping each word's characters intact. A common coding interview question with practical applications.
Detailed Explanation
Reversing Word Order
Reversing words in a sentence means rearranging the words so the last word comes first, while keeping the characters within each word unchanged.
Example
Input: "The quick brown fox jumps"
Output: "jumps fox brown quick The"
Each word retains its original spelling — only the order changes.
Algorithm
Split-reverse-join approach:
const result = sentence.split(/\s+/).reverse().join(" ");
In-place approach (O(1) extra space):
- Reverse the entire string character by character
- Reverse each individual word within the result
Step 0: "The quick brown fox"
Step 1: "xof nworb kciuq ehT" (reverse all characters)
Step 2: "fox brown quick The" (reverse each word)
This two-pass technique is a classic interview solution because it achieves word reversal without allocating a new array.
Edge Cases to Consider
- Multiple spaces: Should consecutive spaces be collapsed to one, or preserved?
- Leading/trailing spaces: Should they be trimmed or kept?
- Single word: Returns the same word unchanged
- Empty string: Returns empty string
- Newlines: Should each line be processed independently?
Multi-line Handling
When processing multi-line text, words are typically reversed within each line independently:
Input:
"Hello World"
"Good Morning"
Output:
"World Hello"
"Morning Good"
This preserves the line structure while reversing word order within each line.
Use Case
Reversing word order is a frequent coding interview question at companies like Google, Amazon, and Meta. It also has practical applications in natural language processing, search query reformulation, and text formatting for right-to-left language adaptation.