Reverse the order of words in a string, removing extra spaces.
Problem Statement
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.
Examples
Input: s = "the sky is blue"
Output: "blue is sky the"
Explanation: The order of words is reversed while stripping extra spaces.
Input: s = " hello world "
Output: "world hello"
Explanation: The order of words is reversed while stripping extra spaces.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
š” Hint 1:
Handle multiple consecutive spaces and leading/trailing spaces.
š” Hint 2:
Split the string by whitespace: s.trim().split(/\s+/) extracts all words cleanly.
š” Hint 3:
Reverse the words array and join with a single space.
Editorial & Approach
Problem Overview & Intuition
Trim extra leading and trailing whitespace, tokenize the string by one or more whitespace characters, reverse the token order, and join with a single space separator in O(N) time.
Step-by-Step Approach
- Trim whitespace from both ends of
s. - Split by regular expression
/\s+/to capture non-empty words. - Reverse the array of words.
- Join with
" "and return.
Optimal Implementation (JavaScript)
function reverseWords(s) {
return s.trim().split(/\s+/).reverse().join(' ');
}
Complexity Analysis
Time Complexity
O(N) ā linear scan to tokenize, reverse, and join.
Space Complexity
O(N) ā space to hold words and joined output.
Edge Cases & Corner Traps Handled
- Leading and trailing spaces: " hello world " -> "world hello".
- Multiple spaces between words: "a b" -> "b a".
- Single word: returns unchanged.