Reverse the ordering of words in a string
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Reversing the order of words in a string is a common interview and utility problem. The core task is simple: keep each word intact, but place the last word first, the second-to-last word second, and so on.
The only real complication is deciding what to do with whitespace. Some solutions normalize spaces, while others preserve the original spacing pattern. Both are valid, but they solve slightly different problems.
The Simple Solution: Normalize Whitespace
If you only care about the words themselves, the easiest solution is:
- split the string into words
- reverse the list of words
- join them back with single spaces
In Python:
Output:
Notice that split() without an explicit separator treats runs of whitespace as separators and removes leading and trailing whitespace. That is often exactly what you want.
Preserving the Original Whitespace Pattern
Sometimes the requirement is stricter. You may want to reverse the words but keep the spaces exactly where they were.
A regex-based approach works well for that:
Output:
This version is more complex, but it preserves the original whitespace layout.
Decide What Counts as a Word
In most simple solutions, a word is "any run of non-whitespace characters." That means punctuation stays attached:
Output:
If you want punctuation handled separately, you no longer have a pure whitespace-splitting problem. You need tokenization rules, which is a more advanced text-processing task.
Other Languages Follow the Same Pattern
The same idea appears everywhere: split into tokens, reverse the token order, then join. For example, in JavaScript the normalized-space version is still just one line:
So the hard part is not the language syntax. The hard part is deciding how spaces and punctuation are supposed to behave.
Complexity
Both common approaches run in linear time relative to the input size, aside from the temporary storage used for tokens.
The normalized-space version is usually the best balance of correctness and simplicity:
- splitting is
O(n) - reversing is
O(m) - joining is
O(n)
Where n is the string length and m is the number of words.
Common Pitfalls
- Reversing characters instead of words.
"abc def"should become"def abc", not"fed cba". - Forgetting to define how multiple spaces should behave.
- Using
split(" ")instead of plainsplit(), which can leave empty strings when there are repeated spaces. - Assuming punctuation must be detached from words. That is a separate requirement unless the problem explicitly says so.
- Ignoring tabs or other whitespace characters if the input is not limited to single spaces.
Summary
- The simplest solution is
split,reverse, andjoin. - Plain
split()normalizes repeated whitespace, which is often desirable. - If exact spacing must be preserved, use a token-based approach that keeps whitespace tokens.
- Clarify what counts as a word before coding.
- Most bugs in this problem come from hidden assumptions about whitespace, not from the reversal itself.
Related reading
- Reversible shuffle algorithm using a key
- review of a codility test - pair_sum_even_count
- RMI alternatives for bidirectional asynchronous calls and callbacks through firewalls or NAT
- Robot exploration algorithm
- Robust algorithm for chromatic instrument tuner?
- robust algorithm for surface reconstruction from 3D point cloud?
- Robust Algorithm to detect uneven illumination in images Detection Only Needed
- Robust and fast checksum algorithm?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.