Reverse Words in a String

Problem and examples

Given a string s that contains words separated by spaces, reverse the order of words in the string.

Remove any leading or trailing spaces and reduce multiple spaces between words to a single space in the output.

Note: Do not reverse the characters of individual words—only the word order should be reversed.

Input Output Description
"the sky is blue" "blue is sky the" Words are reversed in order
" hello world " "world hello" Extra spaces removed and words reversed
"a good example" "example good a" Multiple spaces between words collapsed
" Bob Loves Alice " "Alice Loves Bob" Trimmed and reversed correctly

Explore Reverse Words in a String

Load an example or enter your own input. Use the player controls to follow each change.

Understanding the Problem

We are given a string that contains words separated by spaces. However, the string may contain extra spaces — multiple spaces between words, or leading and trailing spaces. Our task is to reverse the order of the words and return a properly formatted string: the words should be in reverse order, and there should be exactly one space between them, with no leading or trailing spaces.

Step-by-Step Solution with Example

Let’s take the example string:

{ "array": [" the sky is blue "], "showIndices": false }

Step 1: Trim the String

We first remove the leading and trailing spaces from the string.

{ "array": ["the sky is blue"], "showIndices": false }

Step 2: Split the String by Spaces

Next, we split the string using space as the delimiter. This gives us an array of substrings. Some of these may be empty due to multiple spaces.

{ "array": ["the", "", "sky", "is", "blue"], "showIndices": false }

Step 3: Filter Out Empty Strings

We now remove the empty strings from the array, keeping only the valid words.

{ "array": ["the", "sky", "is", "blue"], "showIndices": false }

Step 4: Reverse the List of Words

We reverse the list so the words appear in reverse order.

{ "array": ["blue", "is", "sky", "the"], "showIndices": false }

Step 5: Join Words with a Single Space

Finally, we join the reversed words using a single space to form the final output string.

{ "array": ["blue is sky the"], "showIndices": false }

Edge Cases

  • Empty String: Return an empty string.
  • String with Only Spaces: After trimming and filtering, return an empty string.
  • String with One Word: Return the trimmed single word as-is.
  • Multiple Spaces Between Words: Ensure only one space between words in the final output.

Finally

This approach ensures a clean and efficient transformation of the input string. By trimming spaces, filtering out empty tokens, reversing the order, and rejoining the words, we handle both normal and edge cases gracefully. This makes the solution beginner-friendly and robust for real-world usage.

  1. Trim leading and trailing spaces from the string s.
  2. Split the string into a list of words using whitespace as the delimiter.
  3. Filter out any empty strings caused by multiple spaces.
  4. Reverse the list of words.
  5. Join the words with a single space to form the final output.

Implementation and efficiency

C implementation

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void reverseWords(char *str) {
    char *tokens[100];
    int count = 0;
    char *word = strtok(str, " ");
    while (word) {
        tokens[count++] = word;
        word = strtok(NULL, " ");
    }
    for (int i = count - 1; i >= 0; i--) {
        printf("%s", tokens[i]);
        if (i != 0) printf(" ");
    }
}

int main() {
    char str[] = "  hello   world  ";
    reverseWords(str);
    return 0;
}

C++ implementation

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

string reverseWords(string s) {
    stringstream ss(s);
    string word;
    vector<string> words;
    while (ss >> word) {
        words.push_back(word);
    }
    string result;
    for (int i = words.size() - 1; i >= 0; i--) {
        result += words[i];
        if (i != 0) result += " ";
    }
    return result;
}

int main() {
    string s = "  hello   world  ";
    cout << reverseWords(s) << endl;
    return 0;
}

Python implementation

def reverse_words(s):
    words = s.strip().split()
    words.reverse()
    return ' '.join(words)

s = "  hello   world  "
print(reverse_words(s))

Java implementation

public class ReverseWords {
    public static String reverseWords(String s) {
        String[] words = s.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]);
            if (i > 0) sb.append(" ");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "  hello   world  ";
        System.out.println(reverseWords(s));
    }
}

JavaScript implementation

function reverseWords(s) {
    let words = s.trim().split(/\s+/);
    words.reverse();
    return words.join(" ");
}

let s = "  hello   world  ";
console.log(reverseWords(s));

Go implementation

package main

import (
    "fmt"
    "strings"
)

func reverseWords(s string) string {
    words := strings.Fields(s)
    for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
        words[i], words[j] = words[j], words[i]
    }
    return strings.Join(words, " ")
}

func main() {
    s := "  hello   world  "
    fmt.Println(reverseWords(s))
}

Rust implementation

fn reverse_words(s: &str) -> String {
    let mut words: Vec<&str> = s.split_whitespace().collect();
    words.reverse();
    words.join(" ")
}

fn main() {
    let s = "  hello   world  ";
    println!("{}", reverse_words(s));
}

Kotlin implementation

fun reverseWords(s: String): String {
    val words = s.trim().split("\s+".toRegex())
    return words.reversed().joinToString(" ")
}

fun main() {
    val s = "  hello   world  "
    println(reverseWords(s))
}

Swift implementation

import Foundation

func reverseWords(_ s: String) -> String {
    let words = s.trimmingCharacters(in: .whitespaces).components(separatedBy: .whitespaces).filter { !$0.isEmpty }
    return words.reversed().joined(separator: " ")
}

let s = "  hello   world  "
print(reverseWords(s))

TypeScript implementation

function reverseWords(s: string): string {
    let words = s.trim().split(/\s+/);
    return words.reverse().join(" ");
}

let s = "  hello   world  ";
console.log(reverseWords(s));

Time complexity

CaseTimeExplanation
best caseO(n)Each character in the string is processed once during trimming, splitting, and joining.
average caseO(n)All operations—trim, split, reverse, and join—are linear with respect to the input size.
worst caseO(n)Even in the worst case with many extra spaces, we still process each character only once.

Space complexity

O(n)

We use extra space to store the list of words and the final result string.