Quick revision
The short answer
Reversing the order of words is a strings problem solved by scanning with indexes. We read the sentence from the end, skip spaces, find where each word starts, and append that word to a StringBuilder with one space before it, which takes O(n) time and O(n) space and tidies extra spaces for free. When the sentence is a char array to change in place, reversing the whole array and then each word gives the same order with O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Split and put each word in front (brute force) | O(n^2) | O(n) plus a String per word |
| Split, reverse the list, join | O(n) | O(n) plus a String per word |
Backward scan into one StringBuilder | O(n) | O(n) for the result |
| Reverse the whole array, then each word | O(n) | O(1) |
What to remember
We reversed the order of the words by scanning the sentence from the end with an index that skips spaces, measures each word and copies it, with one space added before every word except the first. Every character is visited once, so it takes O(n) time and O(n) space for the answer, and stray spaces disappear because they are never copied. For a char array in place, reversing the whole array and then each word gives the same order with O(1) extra space. The clue to remember is blocks that change order while their insides stay the same: find the boundaries with indexes, or reverse twice.
1What it means to reverse the words
Picture a sentence made of word magnets on a fridge door. To reverse the order of the words, you lift each magnet as a whole and place it in the new order. You never take a magnet apart, so the letters inside each word stay exactly as they were. Only the order of the magnets changes. Keep this picture in mind, because the whole problem is about finding where each magnet begins and ends.
So for the sentence the sky is blue, the answer is blue is sky the. A word here means a run of characters with no space inside it, so punctuation stays attached to its word. The problem is smaller than it looks: we never change a letter, we only copy whole words in a new order.
Real sentences are often untidy, so our example has stray spaces. It is fourteen characters long, and each character has a position, called its index, counted from 0, so the indexes run from 0 to 13. Writing each space as an underscore, it reads _sky_is__blue_: one space at the start, sky, one space, is, two spaces, blue, and one space at the end. Let us do it by hand. Reading from the right, we pass the final space and find blue. We pass two spaces and find is. We pass one space and find sky, and then only a space is left. Writing the words in the order we found them, with one space between them, gives blue is sky.
Fourteen characters: a space, sky, a space, is, two spaces, blue and a final space. The three words are marked.
- words
- sky, is, blue
- answer
- "blue is sky"
- length
- 14
1The words are sky at indexes 1 to 3, is at 5 to 6, and blue at 9 to 12. The answer puts them in the order blue, is, sky, with single spaces.
What to assume
- Can there be spaces at the ends, or several between words?
- We assume yes.
- Should the result keep them?
- We assume the expected result is tidy, with exactly one space between words and none at the ends, and that a sentence of only spaces becomes the empty string.
- Are we given a String or a char array we may change?
- A String.
A careful candidate asks about spaces, because that is where the decisions are. Can there be spaces at the ends, or several between words? We assume yes. Should the result keep them? We assume the expected result is tidy, with exactly one space between words and none at the ends, and that a sentence of only spaces becomes the empty string. Are we given a String or a char array we may change? We handle both, and the char array version keeps the spacing as it was, in case that is what the interviewer wants.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a strings scanning problem
A beginner who sees this question often reaches for a library: split the sentence into words, reverse the list and join it back together. That is a sensible instinct, and we will look at it honestly in the next section. But it is worth reading the question slowly first, because its clues describe a method that needs no extra pieces at all.
The first clue is the word words. The output is made of pieces of the input, each word copied exactly as it is. So the real task is not to change characters but to find, for each word, the index where it starts and the index where it ends. Two index variables can mark those two ends, just as two fingers can mark both ends of a magnet.
The second clue is the word reverse applied to the order of the words. If the last word must come out first, then reading the sentence from right to left meets the words in exactly the order we need. So a single scan from the end can find each word and copy it straight to its final place.
These clues place the problem in the strings and tries family, problems about sequences of characters. A trie, a tree of characters that stores many words by their shared beginnings, belongs to the family but is for searching many words, not for reordering one sentence. The technique we need is index scanning with two pointers: one index, i, walks the sentence, and a second, end, remembers where the current word ends. The general rule to carry to new problems is that when blocks of a sequence must change order while the inside of each block stays the same, find the block boundaries with indexes, or use the reverse twice trick that we will meet later.
A stack, the pile of plates where the last plate on is the first off, also reverses order, and pushing every word then popping them works. But it stores every word a second time to do what reading from the end does for free. Reversing the whole string character by character looks close too, but on its own it spells every word backwards.
3The honest first attempt, splitting and putting each word in front
The first solution most people write splits the sentence into words and builds the answer by putting each new word in front of what we have so far. It is a correct brute force, and it shows clearly what has to happen, which is why it is a good place to start.
Let us follow it on our example. First trim removes the spaces at both ends, and split with the pattern \s+, which means one or more whitespace characters, cuts the rest into sky, is and blue, so the double space does no harm. Then the loop builds sky, then is sky, then blue is sky. Correct.
Now count what it copies. Each time a word goes in front, the + operator builds a brand new String and copies the whole result so far, because a Java String can never be changed. With w words in a sentence of n characters, each step can copy up to n characters, so the time is O(w times n), which is O(n^2) for a sentence of many short words. It also makes one small String object for every word, plus the array that holds them.
A middle step removes the quadratic part. Split, reverse the list with Collections.reverse and join with String.join and a single space, which is O(n). It is a fair answer, but it hides traps. Without the trim, a leading space makes split return an empty first piece and the output gains a stray space. Splitting on a single space instead of \s+ makes an empty piece for every double space. The waste we want to remove is the pile of small strings and the extra passes, because one scan can find each word and copy it to its final place.
4Scanning from the end, one step at a time
Let us build the scan slowly. We keep an index i, starting on the last character. The words must come out last first, so we will only ever move i to the left. Each time round the loop we do three small jobs: skip any spaces, measure one word, and copy it.
The first job is to move i left while it sits on a space. If i falls off the start, below 0, there are no more words and we stop. Otherwise i now sits on the last letter of a word, so we write that position down in a second variable, end.
The second job is to keep moving i left while the characters are not spaces. When it stops, i is on the space just before the word, or at -1 if the word starts the sentence. Here a beginner often asks why the word is s[i + 1 .. end] and not s[i .. end]. Because i stopped on the space, one place too far left, so the first letter of the word is at i + 1. Writing i instead of i + 1 is the most common slip in this problem, and it copies a space into the output.
The third job is to copy the word. If the output already holds a word, we first add a single space. Then StringBuilder.append(s, i + 1, end + 1) copies just that stretch of the sentence, with no substring object in between. The second number is end + 1 because, as usual in Java, the end of a range is the first position not included.
Why does this give exactly one space between words, whatever the input looked like? Because spaces from the input are only ever skipped, never copied. The only spaces in the output are the ones we add ourselves, one before every word except the first. That single rule tidies leading, trailing and repeated spaces all at once.
There is a second method worth knowing, for when the interviewer hands us a char array and asks for no extra memory. Reverse the whole array, which puts the words in the right order but spells each one backwards. Then reverse each word again, which repairs the spelling. The picture shows it on our sentence.
An underscore is a space. The cells being reversed in each step are marked, with lo and hi at the two ends of that stretch.
- step
- before
- array
- _sky_is__blue_
1We start from the sentence as a char array that we are allowed to change. The words are in the original order.
- step
- reverse all
- array
- _eulb__si_yks_
2Reversing the whole array, indexes 0 to 13, puts the words in the new order, blue first, but every word is spelled backwards.
- step
- reverse a word
- array
- _blue__si_yks_
3Now we reverse each word on its own. The first, indexes 1 to 4, turns eulb back into blue.
- step
- reverse a word
- array
- _blue__is_yks_
4The second word, indexes 7 to 8, turns si back into is. The two spaces before it stay exactly where they are.
- step
- reverse a word
- array
- _blue__is_sky_
5The last word, indexes 10 to 12, turns yks into sky. The words are reversed and the original spacing is kept.
Each reversal is the two pointer swap from reversing a string, with lo and hi at the two ends of the stretch being reversed. Every character is touched a constant number of times, so this is O(n) time with O(1) extra space. Notice that it keeps the original spacing, two spaces stay two, which is either a feature or something to tidy afterwards, depending on what the interviewer asked.
5Watching the backward scan on the example
The picture plays reverseWords on our fourteen character sentence, with each space drawn as an underscore. In each frame you can see i and end under the cells, the stretch of the current word, and the output so far.
Watch i carefully. It only ever moves left, so the whole scan is a single pass from right to left. The output grows one whole word at a time.
An underscore is a space. i moves only to the left. Skipped spaces fade, the word being measured is marked, and words already copied to the output are finished.
- i
- 13
- end
- -
- word
- -
- output
- ""
1i starts on the last index, 13. The output is empty. We will read the sentence from right to left, so the last word is found first.
- i
- 12
- end
- -
- word
- -
- output
- ""
2s[13] is a space, so the first inner loop skips it and stops at 12, on the e. i is on the last letter of a word.
- i
- 8
- end
- 12
- word
- blue
- output
- ""
3We remember end = 12 and walk i left while the characters are letters. i stops at 8, a space, so the word is s[9..12], blue.
- i
- 8
- end
- 12
- word
- blue
- output
- "blue"
4The output is empty, so no space goes first.
append(s, 9, 13)copies blue straight from the sentence into the output.- i
- 6
- end
- -
- word
- -
- output
- "blue"
5Back at the top of the loop, i is on a space at 8. The skip loop passes the two spaces at 8 and 7 and stops on the s at 6.
- i
- 4
- end
- 6
- word
- is
- output
- "blue"
6end becomes 6 and i walks back over s and i, stopping at the space at 4. The word is s[5..6], is.
- i
- 4
- end
- 6
- word
- is
- output
- "blue is"
7The output is not empty, so one space goes in first, then is. The output reads blue is, with exactly one space.
- i
- 3
- end
- -
- word
- -
- output
- "blue is"
8The skip loop passes the space at 4 and stops on the y at 3. The two spaces in the sentence never reach the output.
- i
- 0
- end
- 3
- word
- sky
- output
- "blue is"
9end becomes 3 and i walks back over y, k and s, stopping at the leading space at 0. The word is s[1..3], sky.
- i
- 0
- end
- 3
- word
- sky
- output
- "blue is sky"
10One space, then sky. The output now reads blue is sky, and every word has been copied exactly once.
- i
- -1
- end
- -
- word
- -
- output
- "blue is sky"
11The skip loop passes the space at 0 and i becomes -1. i < 0, so we break out of the loop and return blue is sky.
Let us read a few frames back. In the third frame i stops on the space at 8 after walking over blue, and the word is taken from 9 to 12, which is the i + 1 we reasoned about. In the fifth frame the skip loop passes both of the middle spaces in one go, and in the seventh the output gains exactly one space before is.
The last frame shows the loop ending. The skip loop moves i from the leading space at 0 to -1, the check i < 0 is true, and we break out. The output reads blue is sky, and none of the five spaces from the sentence was copied into it.
6The complete Java program
Here is the full class with the backward scan, the in-place double reversal and a small reverse helper. main runs our untidy example, a clean sentence, a sentence of only spaces, a single word and the in-place version.
Let us read reverseWords in the order it runs. It creates an empty StringBuilder, a text buffer that can grow without copying itself, and sets i to the last index. The outer while loop runs while i has not fallen off the start.
Inside, the first inner loop skips spaces. Notice that it tests i >= 0 before calling charAt(i). Java checks the left side of && first and stops if it is false, so we never ask for charAt(-1), which would throw an exception. If only spaces were left, the break ends the outer loop.
Then end = i records the last letter, and the second inner loop walks i back to the space before the word. The if adds one space only when the output is not empty, and append copies s from i + 1 up to, but not including, end + 1. For the sentence of only spaces, the first skip runs i off the start at once, the loop breaks, and the method returns the empty string, which main prints as [] between brackets.
reverseWordsInPlace reverses the whole array, then walks it with i, treating every space, and the position just past the end, as the end of a word. When i reaches one, reverse(c, start, i - 1) repairs the word that ends there, and start moves past the space. Letting i run up to c.length means the last word needs no special code after the loop. main prints blue is sky the for the clean sentence.
7How much it costs, and the cases at the edges
Let us count on the example first. The index i started at 13 and ended at -1, visiting each of the fourteen positions once, and the three words, nine letters in all, were each copied once into the output. So the time is O(n) for a sentence of n characters. The StringBuilder holds at most n characters, so the space is O(n), which we need for the answer anyway.
The double reversal touches each character twice, once in the whole reversal and once in its word's reversal, so it is O(n) time, and it uses only a few index variables, so the extra space is O(1).
| Approach | Time | Extra space |
|---|---|---|
| Split and put each word in front (brute force) | O(n^2) | O(n) plus a String per word |
| Split, reverse the list, join | O(n) | O(n) plus a String per word |
Backward scan into one StringBuilder | O(n) | O(n) for the result |
| Reverse the whole array, then each word | O(n) | O(1) |
The edge cases are handled by the same loops. An empty string never enters the outer loop and returns the empty string. A sentence of only spaces skips to -1 and returns the empty string too. A single word is found, copied without a space in front, and comes back unchanged. If the input may contain tabs or other whitespace, we test Character.isWhitespace instead of comparing with a space, and everything else stays the same.
8Follow-up questions
How would you remove the extra spaces in the in-place version as well?
After the two reversals we tidy the array with a second index, called a write index, that marks where the next character should go. We walk the array with a read index, skip runs of spaces, and copy each word's characters forward to the write index, putting one space before every word except the first. When we finish, the write index is the length of the tidy sentence. It is still O(n) time and O(1) extra space, and it is how this is done in languages where strings can be changed.
Where else does the reverse twice trick appear?
The best known case is rotating an array to the right by k positions. We reverse the whole array, then reverse the first k elements and the remaining elements separately. The reason is the same as here: reversing everything puts the two blocks in the right order but backwards inside, and reversing each block again restores its inside. It runs in O(n) time with O(1) extra space.
Why not use a stack of words?
A stack works. We scan the sentence from left to right, push each word as we find it, and then pop them all, adding a space between them, so the last word pushed comes out first. But the stack holds every word as a separate String, and the backward scan gets the same order simply by reading from the end, so the stack only adds memory and objects without making anything simpler.
9Conclusion
We reversed the order of the words by scanning the sentence from the end with an index that skips spaces, measures each word and copies it, with one space added before every word except the first. Every character is visited once, so it takes O(n) time and O(n) space for the answer, and stray spaces disappear because they are never copied. For a char array in place, reversing the whole array and then each word gives the same order with O(1) extra space. The clue to remember is blocks that change order while their insides stay the same: find the boundaries with indexes, or reverse twice.
Open with
Let me check the details first: a word is a run of non-space characters, the input may have leading, trailing or repeated spaces, and I return the words with exactly one space between them, so a sentence of only spaces gives the empty string.
Then, if they want more
A first idea is to split into words and put each word in front of the result, but every prepend copies the whole result, so it is quadratic. Split, reverse and join is linear, but it leans on the library and has traps with empty pieces.
Since the output is just slices of the input in a new order, I find the word boundaries myself with an index scanning from the end. I skip spaces to the left; if I fall off the start, I stop.
Otherwise I record end, walk left to the space before the word, and append the slice from i plus one to end to a StringBuilder, adding one space first if the builder is not empty. Input spaces are only skipped, never copied, so the output is tidy.
Each character is visited once, so it is O(n) time and O(n) space for the result. If I am given a char array to change in place, I reverse the whole array, which puts the words in order but spelled backwards, then reverse each word again, which is O(n) time and constant extra space.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 45 times in that collection. How it is counted
- Official documentation
- StringBuilder (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Reverse the order of the words in a sentence.": https://scrivio-interview-library.netlify.app/data-structures/solutions/reverse-the-order-of-the-words-in-a-sentence-7d1cdd/