KatInterview

557. Reverse Words in a String III

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reverse the characters of each word in a given sentence. The original order of the words and the single spaces separating them must be maintained. For example, "Let's take" should become "s'teL ekat". The constraints simplify the problem: no leading/trailing spaces, and words are separated by a single space.

Solution

Reverse Words in a String III in Python

class Solution:
    def reverseWords(self, s: str) -> str:
        # Split the string into a list of words using space as the delimiter.
        words = s.split(' ')
        
        # Use a list comprehension to create a new list of reversed words.
        # word[::-1] is a Python slice notation to reverse a string.
        reversed_words = [word[::-1] for word in words]
        
        # Join the list of reversed words back into a single string,
        # separated by spaces.
        return ' '.join(reversed_words)

Reverse Words in a String III in Java

class Solution {
    public String reverseWords(String s) {
        // Split the string by spaces into an array of words.
        // The problem guarantees words are separated by a single space.
        String[] words = s.split(" ");
        
        // Iterate through the array of words.
        for (int i = 0; i < words.length; i++) {
            // Reverse each word using StringBuilder and update the array in-place.
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        
        // Join the reversed words back together with spaces.
        return String.join(" ", words);
    }
}

Reverse Words in a String III in C++

class Solution {
public:
    string reverseWords(string s) {
        // 'start' marks the beginning of the current word.
        int start = 0;
        // Iterate through the string with index 'i'.
        // The loop goes up to s.length() to handle the last word.
        for (int i = 0; i <= s.length(); ++i) {
            // A word ends when we see a space or reach the end of the string.
            if (i == s.length() || s[i] == ' ') {
                // Reverse the substring representing the word.
                // The word is from index 'start' to 'i-1'.
                // std::reverse works on a half-open range [first, last).
                reverse(s.begin() + start, s.begin() + i);
                
                // Update 'start' to the beginning of the next word.
                start = i + 1;
            }
        }
        return s;
    }
};

Reverse Words in a String III in TypeScript

function reverseWords(s: string): string {
    // Split the string into an array of words based on the space delimiter.
    const words = s.split(' ');
    
    // Use the map function to create a new array where each word is reversed.
    const reversedWords = words.map(word => {
        // For each word, split it into characters, reverse the array of characters,
        // and then join them back into a string.
        return word.split('').reverse().join('');
    });
    
    // Join the array of reversed words back into a single string,
    // with spaces in between.
    return reversedWords.join(' ');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.