Talentd
FleetCode
Make and follow sheets.Sign in

Reverse Words in a String III solution and explanation

EasyStringTwo Pointers4 min read84.0% acceptanceUpdated 9 Apr 2026
Reverse Words in a String iii | LeetCode 557 | C++Knowledge Center · 6:47 · 27K viewsWatch on YouTube
9 more videos on this problem
  1. Reverse Words in a String iii | LeetCode 557 | C++Knowledge Center · 6:47 · 27K views
  2. Reverse Words in a String III - Leetcode 557 - PythonNeetCodeIO · 10:18 · 27K views
  3. Reverse Words In A String III (LeetCode 557) | Full solution | 3 different methodsNikhil Lohia · 14:20 · 22K views
  4. Reverse Words in a String III | 2 Approaches | Zappos | MentorGraphics | Leetcode - 557 | Live CodecodestorywithMIK · 14:26 · 8K views
  5. Reverse Words in a String III | LEETCODE - 557 | Easy solutionhi-malik · 9:52 · 2K views
  6. Reverse Words in a String III - LeetCode #557 | Python, JavaScript, Java, C++CodingNinja · 2:57 · 1K views
  7. LeetCode 557 - Reverse Words in a String 3 | Java Solution [EASY]Code with Carter · 8:32 · 1K views
  8. How to Solve "557 Reverse Words in a String III" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 5:37 · 733 views
  9. Leetcode #557 || Reverse Words in a String III || Two-Pointer || JAVACode Unraveled · 12:00 · 266 views
  10. 557. Reverse Words in a String III | Leetcode | PythonAbdullah Arshed · 2:02 · 266 views

The problem

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "Mr Ding"
Output: "rM gniD"

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Approach overview

Problem Overview: You are given a sentence where words are separated by single spaces. The task is simple: reverse the characters of every word while keeping the original word order and spacing unchanged. For example, "Let's code" becomes "s'teL edoc".

Approach 1: Split and Reverse Each Word (O(n) time, O(n) space)

The most direct solution splits the string into words using the space character. Once you have the list of words, iterate through each one and reverse it individually using built‑in string slicing or a manual character reversal. After reversing all words, join them back together with spaces. The algorithm processes each character once during splitting and once during reversing, giving O(n) time complexity. Because the split operation creates a list of words and the join builds a new string, the extra space usage is O(n).

This approach is readable and easy to implement in languages like Python, JavaScript, or Java. In interviews, it demonstrates that you recognized the problem structure quickly. The tradeoff is the additional memory from storing intermediate words.

Approach 2: Two Pointers Inline Reversal (O(n) time, O(1) extra space)

A more efficient approach scans the string with the two pointers technique. Convert the string into a mutable character array if the language requires it. Use one pointer to mark the start of a word and iterate with another pointer until you hit a space or the end of the string. Once a word boundary is detected, reverse the characters between the start and end indices in place.

The key insight: each word can be reversed independently without affecting others. This allows an in-place swap using two pointers moving toward each other. Every character participates in at most one reversal, so the runtime remains O(n). Since the reversal happens inside the same character buffer, the additional memory usage is O(1) beyond the output string.

This technique is a classic application of the string manipulation pattern used in many interview questions. It avoids unnecessary allocations and scales well for large inputs.

Recommended for interviews: The two‑pointers inline reversal approach is typically what interviewers expect. The split‑and‑reverse method shows you understand the problem quickly, but the in‑place pointer solution demonstrates stronger algorithmic thinking and memory awareness. Both run in O(n) time, but the two‑pointer approach achieves optimal space usage and reflects common string manipulation patterns tested in technical interviews.

Approach 1: Split and Reverse Each Word

This approach involves splitting the given string into words, reversing each word individually, and then joining them back together.

def reverseWords(s):
    words = s.split()
    return ' '.join(word[::-1] for word in words)

s = "Let's take LeetCode contest"
print(reverseWords(s))
public class Solution {
    public static void reverseWords(String s) {
        char[] arr = s.toCharArray();
        int n = arr.length;
        int start = 0;

        for (int end = 0; end < n; end++) {
            if (arr[end] == ' ' || end == n - 1) {
                reverse(arr, start, (end == n - 1) ? end : end - 1);
                start = end + 1;
            }
        }
        System.out.println(new String(arr));
    }

    private static void reverse(char[] arr, int start, int end) {
        while (start < end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        String s = "Let's take LeetCode contest";
        reverseWords(s);
    }
}
#include <iostream>
#include <string>
#include <algorithm>

void reverseWords(std::string &s) {
    size_t start = 0, end;
    while ((end = s.find(' ', start)) != std::string::npos) {
        std::reverse(s.begin() + start, s.begin() + end);
        start = end + 1;
    }
    std::reverse(s.begin() + start, s.end());
}

int main() {
    std::string s = "Let's take LeetCode contest";
    reverseWords(s);
    std::cout << s << std::endl;
    return 0;
}
function reverseWords(s) {
    let words = s.split(' ');
    let reversedWords = words.map(word => word.split('').reverse().join(''));
    return reversedWords.join(' ');
}

let s = "Let's take LeetCode contest";
console.log(reverseWords(s));
#include <stdio.h>
#include <string.h>

void reverseWord(char* start, char* end) {
    while(start < end) {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

void reverseWords(char* s) {
    char* word_start = s;
    char* temp = s; 

    while(*temp) {
        temp++;
        if (*temp == ' ' || *temp == '\0') {
            reverseWord(word_start, temp - 1);
            word_start = temp + 1;
        }
    }
}

int main() {
    char s[] = "Let's take LeetCode contest";
    reverseWords(s);
    printf("%s\n", s);
    return 0;
}
using System;

public class Solution {
    public static void ReverseWords(string s) {
        char[] arr = s.ToCharArray();
        int start = 0;

        for (int end = 0; end < arr.Length; end++) {
            if (arr[end] == ' ' || end == arr.Length - 1) {
                Reverse(arr, start, (end == arr.Length - 1) ? end : end - 1);
                start = end + 1;
            }
        }
        Console.WriteLine(new String(arr));
    }

    private static void Reverse(char[] arr, int start, int end) {
        while (start < end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void Main() {
        string s = "Let's take LeetCode contest";
        ReverseWords(s);
    }
}

In Python, we split the string into words, reverse each word, and then join them back together with spaces.

Complexity

Time Complexity: O(n)
Space Complexity: O(n), due to the space required for storing the words and the reversed result.

Try this approach in the editor

Approach 2: Two Pointers Inline Reversal

This involves using a two-pointer technique to reverse the characters within each word in place, thus preserving the overall space complexity.

def reverse_words(s):
    s = list(s)
    start = 0
    
    for end in range(len(s) + 1):
        if end == len(s) or s[end] == ' ':
            reverse(s, start, end - 1)
            start = end + 1
    
    return ''.join(s)


def reverse(s, start, end):
    while start < end:
        s[start], s[end] = s[end], s[start]
        start += 1
        end -= 1


s = "Let's take LeetCode contest"
print(reverse_words(s))
public class Solution {
    public static void reverseWords(String s) {
        char[] arr = s.toCharArray();
        int start = 0;

        for (int end = 0; end <= arr.length; end++) {
            if (end == arr.length || arr[end] == ' ') {
                reverse(arr, start, end - 1);
                start = end + 1;
            }
        }
        System.out.println(new String(arr));
    }

    private static void reverse(char[] arr, int start, int end) {
        while (start < end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        String s = "Let's take LeetCode contest";
        reverseWords(s);
    }
}
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void reverseWords(string& s) {
    int i = 0;
    for(int j = 0; j <= s.size(); j++) {
        if(j == s.size() || s[j] == ' ') {
            reverse(s.begin() + i, s.begin() + j);
            i = j + 1;
        }
    }
}

int main() {
    string s = "Let's take LeetCode contest";
    reverseWords(s);
    cout << s << endl;
    return 0;
}
function reverseWords(s) {
    let start = 0;
    let chars = s.split('');

    for (let end = 0; end <= chars.length; end++) {
        if (end === chars.length || chars[end] === ' ') {
            reverse(chars, start, end - 1);
            start = end + 1;
        }
    }

    function reverse(chars, start, end) {
        while (start < end) {
            [chars[start], chars[end]] = [chars[end], chars[start]];
            start++;
            end--;
        }
    }

    return chars.join('');
}

let s = "Let's take LeetCode contest";
console.log(reverseWords(s));
#include <stdio.h>

void reverse(char* start, char* end) {
    while (start < end) {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

void reverseWords(char* s) {
    char* wordStart = s;
    char* temp = s;

    while (*temp) {
        temp++;
        if (*temp == ' ' || *temp == '\0') {
            reverse(wordStart, temp - 1);
            wordStart = temp + 1;
        }
    }
}

int main() {
    char str[] = "Let's take LeetCode contest";
    reverseWords(str);
    printf("%s\n", str);
    return 0;
}
using System;

public class Solution {
    public static void ReverseWords(string s) {
        char[] arr = s.ToCharArray();
        int start = 0;

        for (int end = 0; end <= arr.Length; end++) {
            if (end == arr.Length || arr[end] == ' ') {
                Reverse(arr, start, end - 1);
                start = end + 1;
            }
        }
        Console.WriteLine(new String(arr));
    }

    private static void Reverse(char[] arr, int start, int end) {
        while (start < end) {
            char temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void Main() {
        string s = "Let's take LeetCode contest";
        ReverseWords(s);
    }
}

In this Python solution, the string is first converted into a list to allow in-place modifications. Then, a custom reverse function swaps the word's elements in-place.

Complexity

Time Complexity: O(n)
Space Complexity: O(1)

Try this approach in the editor

Approach 3: Simulation

We can split the string s into an array of words words by spaces, then reverse each word and concatenate them back into a string.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.

function reverseWords(s: string): string {
    return s
        .split(' ')
        .map(t => t.split('').reverse().join(''))
        .join(' ');
}
func reverseWords(s string) string {
	words := strings.Fields(s)
	for i, w := range words {
		t := []byte(w)
		slices.Reverse(t)
		words[i] = string(t)
	}
	return strings.Join(words, " ")
}
impl Solution {
    pub fn reverse_words(s: String) -> String {
        s.split(' ')
            .map(|s| s.chars().rev().collect::<String>())
            .collect::<Vec<_>>()
            .join(" ")
    }
}
class Solution {
    /**
     * @param String $s
     * @return String
     */
    function reverseWords($s) {
        $words = explode(' ', $s);
        foreach ($words as $i => $word) {
            $words[$i] = strrev($word);
        }
        return implode(' ', $words);
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Split and Reverse Each Word

Time Complexity: O(n)
Space Complexity: O(n), due to the space required for storing the words and the reversed result.

Two Pointers Inline Reversal

Time Complexity: O(n)
Space Complexity: O(1)

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Split and Reverse Each WordO(n)O(n)Best for quick implementation and readability when extra memory is acceptable
Two Pointers Inline ReversalO(n)O(1)Preferred for interviews or memory‑constrained environments where in‑place string manipulation is required

Frequently asked questions

Is Reverse Words in a String III easy or hard?

Reverse Words in a String III is classified as an Easy problem on LeetCode with a high acceptance rate. It mainly tests basic string manipulation and familiarity with the two-pointer pattern.

How to solve Reverse Words in a String III in O(n)?

Traverse the string and detect word boundaries using spaces. For each word, apply a two-pointer reversal between its start and end indices. Because each character is processed only once, the algorithm completes in O(n) time.

Reverse Words in a String III Python or Java solution

In Python, a common solution uses split(), reverse slicing for each word, and join() to rebuild the sentence. In Java, you can convert the string to a char array and reverse each word using two pointers before constructing the final string.

What is the best approach for Reverse Words in a String III?

The two pointers inline reversal approach is considered the best solution. It scans the string once, identifies word boundaries, and reverses characters in place. This achieves O(n) time complexity with O(1) extra space, which is optimal for this problem.

What data structure is used in Reverse Words in a String III?

The problem primarily uses strings and sometimes a character array for in-place modification. The algorithm relies on the two-pointer technique to swap characters within each word efficiently.

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

The optimal time complexity is O(n), where n is the length of the input string. Each character is visited at most a constant number of times during scanning and reversal. Both the split-based and two-pointer solutions run in linear time.

Is Reverse Words in a String III asked at Google, Amazon, or Meta?

String manipulation problems like this frequently appear in coding interviews at companies such as Amazon, Google, and Meta. While this exact question may vary, the underlying patterns—two pointers and in-place string reversal—are common interview topics.

Comments

Now write it yourselfClose this page and solve Reverse Words in a String III in the editor, without looking.
Practise Reverse Words in a String III