Explorer
Data Structures & Algorithms

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

  1. Trim whitespace from both ends of s.
  2. Split by regular expression /\s+/ to capture non-empty words.
  3. Reverse the array of words.
  4. 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.

Reverse words in a given string / Palindrome Check

Easy
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.
Example Scenarios
1Example 1
Input: s = "the sky is blue"
Output: "blue is sky the"
Explanation:

The order of words is reversed while stripping extra spaces.

2Example 2
Input: s = " hello world "
Output: "world hello"
Explanation:

The order of words is reversed while stripping extra spaces.

Editor
Loading Editor...
s =
"the sky is blue"
Output:Click "Run" above to execute and verify your code here.
blue is sky the