Code Logo

Reverse Words Order

Published at25 Jul 2026
Easy 0 views
Like0

Given a string containing words separated by spaces, reverse the order of the words. The words themselves should not be modified, only their positions swapped.

Split the string by spaces, reverse the resulting array, and join back with spaces. This is a classic string manipulation pattern that tests your ability to work with arrays derived from strings.

Time complexity is O(n) where n is the string length. Space complexity is O(n) for the word array and result. The split-reverse-join pattern is fundamental to string processing.

Edge cases include empty strings, single-word strings (no change), and strings with multiple spaces between words (preserved).

Example Input & Output

Example 1
Input
""
Output
""
Explanation

Empty string

Example 2
Input
"Hello World"
Output
"World Hello"
Explanation

Reverse word order

Example 3
Input
"a b c"
Output
"c b a"
Explanation

Three words reversed

Example 4
Input
"one two three"
Output
"three two one"
Explanation

Three words

Example 5
Input
"hello"
Output
"hello"
Explanation

Single word unchanged

Algorithm Flow

Recommendation Algorithm Flow for Reverse Words Order
Recommendation Algorithm Flow for Reverse Words Order

Solution Approach

function solution(s) {
  return s.split(' ').reverse().join(' ');
}

Best Answers

java
class Solution {
    public String solution(String s) {
        String[] w=s.split(" ",-1);
        StringBuilder r=new StringBuilder();
        for(int i=w.length-1;i>=0;i--){r.append(w[i]);if(i>0)r.append(' ');}
        return r.toString();
    }
}