15% off all plans & roadmaps Use code

See plans

Reverse Words in a String

Updated

TL;DR: Reverse the order of the words in a string and collapse any extra spaces. Compact the words to the front in one pass, reverse the whole buffer, then reverse each word back to fix its letters.

Problem

You are given a string s. Reverse the order of its words.

A word is a sequence of non-space characters. Words in s are separated by at least one space.

Return a string made of the words in reverse order, joined by a single space.

The input may have leading spaces, trailing spaces, or several spaces between two words. The returned string must have only one space between words and no extra spaces at either end.

Example 1

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2

Input: s = " hello world "
Output: "world hello"
Explanation: The reversed string should not contain leading or trailing spaces.

Example 3

Input: s = "a good example"
Output: "example good a"
Explanation: Multiple spaces between two words become a single space in the output.

Constraints

  • 1 <= s.length <= 10^4
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Constraints that matter

  • With n up to 10^4, a single O(n) pass is fast. Any approach that rescans the string for each word, or shifts characters repeatedly, does far more work than needed in the worst case.
  • Only letters, digits and spaces appear, so a space is the one separator. You can test c == ' ' and never handle tabs or newlines.
  • Leading, trailing and repeated spaces force a cleaning pass before any reversal. Reversing the raw input would leave the extra spaces in the wrong places.
  • There is at least one word. The output is never empty, so the cleaning pass always writes a first word, and the final reversal never runs on an empty range.

View on LeetCode

Hints

Hint 1

This is a rearrangement of words where each word keeps its letters.

Hint 2

Split the string on every space character.

Solution

Intuition

This is a rearrangement of words where each word keeps its letters. Reversing the whole string does two things at once: it reverses the word order, and it reverses the letters inside each word. A second reversal of each word undoes the letter flip. Both reversals are two-pointer swaps that move inward from the ends of a range.

Picture a row of word cards with uneven gaps, where sliding them left closes the gaps. Flipping the whole row reverses word order, and turning each card face up again fixes its letters.

Look at what the input forces. Extra spaces mean you cannot rely on positions to find word boundaries, so you must first rebuild the string with one space between words. That rebuild is also two-pointer work: a read pointer scans the input while a write pointer fills the output. The write pointer never passes the read pointer, so no character is overwritten before it is read.

The pattern is two pointers in two forms. Compaction uses a read pointer and a write pointer that both move forward. Reversal uses a left pointer and a right pointer that move toward each other. Each step is a linear scan, so the whole solution runs in O(n) time.

Watch the pattern animation

Worked example

Input: s = "   multiple   spaces   between   words   "
Output: "words between spaces multiple"
Explanation: The string has four words: multiple, spaces, between and words. Each word has three spaces before it, and the string ends with three more spaces. The output keeps the four words, drops every extra space, and lists the words in reverse order.

Approach 1: Brute force with split and join

Split the string on every space character. This is the solution most candidates write first, and it is correct. The split leaves empty tokens wherever two spaces touch or a space sits at either end, so you drop those tokens before reversing the list and joining the words with one space.

Steps

  1. Split s on each space character. Each gap between spaces becomes one token.
  2. Keep only the tokens that are not empty.
  3. Reverse the list of remaining words.
  4. Join the words with a single space and return the result.

Dry run

Split the example on spaces. It has 15 spaces, so split(' ') returns 16 tokens. Twelve of those tokens are empty strings from the runs of spaces at the start, between words, and at the end. The four non-empty tokens are multiple, spaces, between and words.

Reversing the list gives words, between, spaces, multiple. Joining them with one space returns words between spaces multiple, which matches the expected output.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. The split scans every character once, and the token lengths add up to at most n. The filter visits each token once, and reversing and joining touch each word once, so the total time is O(n). The token list and the joined result hold up to n characters together, so the extra space is O(n).

PythonTested in our runner

class Solution:
    def reverseWords(self, s: str) -> str:
        tokens = s.split(' ')
        words = [t for t in tokens if t != '']
        words.reverse()
        return ' '.join(words)

The String Reversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Reversal

Part of Two Pointers

Approach 2: Two pointers: compact, reverse, reverse each wordOptimalString Reversal

What's slow: the split approach builds a list of every token, including the empty ones, and then copies the words again when it joins them. That is O(n) extra memory for work the problem does not ask for, and it creates many small strings.

The insight that fixes it: the cleaned words can live in the same buffer as the input. A read pointer and a write pointer compact the words to the front with single spaces between them. After that, two reversals on the compacted prefix give the answer, and no list of words is needed.

Steps

  1. Copy s into a mutable buffer: a char array, a list or a byte slice.
  2. Compact: move a read pointer through the buffer and skip spaces. When a word starts, write one space if a word was already written, then copy the word to the write pointer.
  3. Truncate the buffer to the write pointer's length.
  4. Reverse the whole buffer. Each word is now in the right place but its letters are backward.
  5. Scan the buffer for spaces. Reverse each word between two boundaries, including the last word.
  6. Convert the buffer back to a string and return it.

Dry run

The example has 41 characters. The table tracks the read pointer r, the write pointer w, and the buffer prefix that the write pointer has built so far.

StepActionrwBuffer
1skip 3 leading spaces30(empty)
2copy multiple118multiple
3skip 3 spaces148multiple
4write one space, copy spaces2015multiple spaces
5skip 3 spaces2315multiple spaces
6write one space, copy between3023multiple spaces between
7skip 3 spaces3323multiple spaces between
8write one space, copy words3829multiple spaces between words
9skip 3 trailing spaces, r reaches the end4129multiple spaces between words
10truncate the buffer to length 294129multiple spaces between words

The second phase reverses indices 0 to 28, which gives sdrow neewteb secaps elpitlum. The third phase reverses each word in place.

StepRange reversedBuffer
11[0, 4] sdrowwords neewteb secaps elpitlum
12[6, 12] neewtebwords between secaps elpitlum
13[14, 19] secapswords between spaces elpitlum
14[21, 28] elpitlumwords between spaces multiple

The final buffer is words between spaces multiple, which matches the expected output.

Complexity

TimeO(n)
SpaceO(1) extra in C++; O(n) for the mutable copy in the other languages

Let n be the length of s, and let w be the length of the compacted prefix, so w is at most n. The read pointer advances once per character, and the write pointer never passes the read pointer, so compaction does O(n) work. Reversing the whole prefix takes about w / 2 swaps. The word reversals take about w / 2 swaps in total because each character belongs to exactly one word, so time is O(n).

In Python, Java, JavaScript, Go and C# the buffer holds n characters, so the extra space is O(n). In C++ the buffer is the string parameter that the function modifies, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def reverseWords(self, s: str) -> str:
        chars = list(s)
        n = len(chars)
        # Phase 1: compact the words to the front, one space between them
        w = 0
        r = 0
        while r < n:
            if chars[r] == ' ':
                r += 1
                continue
            if w > 0:
                chars[w] = ' '
                w += 1
            while r < n and chars[r] != ' ':
                chars[w] = chars[r]
                w += 1
                r += 1
        del chars[w:]
        # Phase 2: reverse the whole buffer
        self.reverse_range(chars, 0, w - 1)
        # Phase 3: reverse each word back to its letter order
        start = 0
        for i in range(w + 1):
            if i == w or chars[i] == ' ':
                self.reverse_range(chars, start, i - 1)
                start = i + 1
        return ''.join(chars)

    def reverse_range(self, chars, i, j):
        while i < j:
            chars[i], chars[j] = chars[j], chars[i]
            i += 1
            j -= 1

Common mistakes

  • Writing the separator before the first word, for example with an unconditional a[w++] = ' ', puts a leading space in the output. Write the separator only when w > 0, which means a word was already written.
  • Reversing the whole original buffer instead of the compacted prefix [0, w - 1]. The old characters after w are leftovers and move into the result. Truncate first, then reverse only the prefix.
  • Passing i instead of i - 1 as the end index in the word reversal. The space at index i then gets reversed into the word and the output is wrong. The end index is inclusive, so use i - 1.
  • Checking buffer[i] == ' ' before i == w in the word scan. When the last word ends at w, that check reads one index past the compacted prefix. Test i == w first.
  • Stopping the word scan at the last space. The last word never gets reversed back, so the output contains words such as secaps backward. Loop up to w inclusive so the final word is handled.

Edge cases

  • "hello" returns "hello". A single word with no spaces survives the full reversal and the single word reversal.
  • " hello " returns "hello". Leading and trailing spaces disappear during compaction.
  • "a b" returns "b a". A run of spaces collapses into one separator.
  • "a" returns "a". This is the smallest legal input and tests the loop bounds with w = 1.
  • "1 2 3" returns "3 2 1". Digits are word characters, so only spaces separate words.
  • A 10^4 length string of single letters separated by single spaces returns the same letters in reverse order with the same spacing. This checks that the buffer is not truncated too early.

Follow-ups interviewers ask

Can you solve it in O(1) extra space?
Yes, if the buffer can be modified. In C++ the parameter is already a mutable string, so the compaction and reversals add only O(1) extra space. In Python, Java, JavaScript, Go and C# the string is immutable, so you need a buffer of size n first.
What if words are separated by tabs or other whitespace?
Replace the test c == ' ' with a helper that checks for any whitespace character. The algorithm does not change because it only needs to know where each word starts and ends. In Python, s.split() with no argument already splits on any whitespace run.
What if the string does not fit in memory?
Read the input from the end in chunks, using a seek to the end of the file. Collect one word at a time and write each word to the output as soon as it is complete. Memory then holds one chunk and the longest word, and the output is written as a stream.

Reverse Words in a String FAQ

What is the time complexity of Reverse Words in a String?

Both approaches run in O(n) time, where n is the length of s. The two-pointer version touches each character a fixed number of times. The split version does the same amount of work with a larger constant.

Why use two pointers for Reverse Words in a String?

Two pointers let you compact the words in one pass and reverse ranges without storing a list of words. The read pointer scans every character, and the write pointer rebuilds the output in the same buffer. The reversals also use two pointers that move inward.

Can Reverse Words in a String be solved in O(1) extra space?

Yes in C++, because the string parameter is mutable and the algorithm only swaps characters and moves indices. In Python, Java, JavaScript, Go and C# the string is immutable, so the buffer costs O(n). The returned string is O(n) in every language, so no version can use O(1) space there.

Is split() enough for Reverse Words in a String in Python?

Yes, ' '.join(reversed(s.split())) returns the correct answer. Python's split() with no argument removes every run of whitespace, so the empty tokens never appear. Interviewers still expect the two-pointer version because the split version builds a list of O(n) words.

Why does `s.split(' ')` return empty strings?

Each space is a separator, so two adjacent spaces produce an empty token between them. Leading and trailing spaces also create empty tokens at the ends. Filter those tokens out, or use a split that drops empty entries.

Asked at

See which companies ask this — Pro

Practise it