string manipulation
reverse words
programming
coding challenge
algorithms

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.

Practice algorithms

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:

  1. split the string into words
  2. reverse the list of words
  3. join them back with single spaces

In Python:

python
1def reverse_words(text: str) -> str:
2    return " ".join(reversed(text.split()))
3
4
5print(reverse_words("the sky is blue"))
6print(reverse_words("  hello   world  "))

Output:

text
blue is sky the
world hello

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:

python
1import re
2
3
4def reverse_words_preserve_spaces(text: str) -> str:
5    parts = re.split(r"(\s+)", text)
6    words = [part for part in parts if part and not part.isspace()]
7    words.reverse()
8
9    result = []
10    word_index = 0
11
12    for part in parts:
13        if part and not part.isspace():
14            result.append(words[word_index])
15            word_index += 1
16        else:
17            result.append(part)
18
19    return "".join(result)
20
21
22print(reverse_words_preserve_spaces("  hello   world  again "))

Output:

text
  again   world  hello

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:

python
print(reverse_words("hello, world!"))

Output:

text
world! hello,

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:

javascript
const reverseWords = (text) => text.trim().split(/\s+/).reverse().join(" ");

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 plain split(), 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, and join.
  • 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.