Reverse the Order of Words in a Sentence

Solve this Problem
Medium15–20 min
Topics
Companies
Practice:GFG ↗
Given a string s, return a new string with the words in reverse order — separated by a single space, with no leading or trailing spaces, even if s itself had extra spaces between words or around the edges. Splitting the string into a words array and reading it backward works, but it allocates an array you only ever read once. Scanning from the end of the string and extracting one word at a time — skip spaces, capture the word, repeat — builds the answer in a single backward pass with no intermediate array.

Test Case 1:

Input:s = " the sky is blue "
Output:"blue is sky the"
Explanation:Leading and trailing spaces are dropped, and the words come back in reverse order.

Test Case 2:

Input:s = "hello world"
Output:"world hello"
Explanation:A simple two-word swap.

Test Case 3:

Input:s = "a good example"
Output:"example good a"
Explanation:The extra spaces between "good" and "example" collapse into a single space in the output.

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s contains English letters, digits, and spaces ' '
  • There is at least one word in s
  • s may have leading, trailing, or multiple spaces between words
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public String reverseWords(String s) {
3 StringBuilder result = new StringBuilder();
4 int i = s.length() - 1;
5 while (i >= 0) {
6 while (i >= 0 && s.charAt(i) == ' ') i--;
7 if (i < 0) break;
8 int end = i;
9 while (i >= 0 && s.charAt(i) != ' ') i--;
10 if (result.length() > 0) result.append(" ");
11 result.append(s, i + 1, end + 1);
12 }
13 return result.toString();
14 }
15}
16
t
h
e
s
k
y
i
s
b
l
u
e
i
Variables
i18
result""
INITIALIZE

Start i at the last index (18) and scan backward, pulling out one word at a time.

Step 1 / 11

Approach & Solutions

Brute Force — Split, Reverse, Join

Brute

Trim the string and split it on whitespace — a regex split like \s+ collapses any run of spaces into a single separator for free. Then walk the resulting words array from the last word to the first, appending each one (with a space in between) to build the reversed sentence. Simple and correct, but it allocates a whole intermediate array just to read it back in reverse.

TimeO(n)
SpaceO(n)
1class Solution { 2 public String reverseWords(String s) { 3 String[] words = s.trim().split("\\s+"); 4 StringBuilder result = new StringBuilder(); 5 for (int i = words.length - 1; i >= 0; i--) { 6 result.append(words[i]); 7 if (i > 0) result.append(" "); 8 } 9 return result.toString(); 10 } 11}

Optimal — Single Backward Pass

Optimal

Scan the string from the end without ever splitting it into an array. Repeatedly skip a run of spaces, then scan backward to find the start of the next word, and append that word straight into the answer — with a separating space if it isn't the first word appended. Because the scan starts from the end, the very first word found is the sentence's LAST word, which is exactly where it belongs in the reversed output. One pass, no regex, no intermediate array.

TimeO(n)
SpaceO(n)
1class Solution { 2 public String reverseWords(String s) { 3 StringBuilder result = new StringBuilder(); 4 int i = s.length() - 1; 5 while (i >= 0) { 6 while (i >= 0 && s.charAt(i) == ' ') i--; 7 if (i < 0) break; 8 int end = i; 9 while (i >= 0 && s.charAt(i) != ' ') i--; 10 if (result.length() > 0) result.append(" "); 11 result.append(s, i + 1, end + 1); 12 } 13 return result.toString(); 14 } 15}

Related Problems