KatInterview

151. Reverse Words in a String

MediumSolutions 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 order of words in a given string s. A "word" is a sequence of non-space characters. The input string can have leading/trailing spaces and multiple spaces between words. The output must have words in reverse order, separated by a single space, with no leading or trailing spaces.

Solution

Reverse Words in a String in Python

class Solution:
    def reverseWords(self, s: str) -> str:
        # The split() method, when called without arguments, handles several things for us:
        # 1. It splits the string by any whitespace (one or more spaces, tabs, newlines).
        # 2. It automatically discards any empty strings that would result from multiple spaces,
        #    so it effectively handles leading, trailing, and multiple spaces between words.
        words = s.split()
        
        # Reverse the list of words.
        # In Python, [::-1] is a concise way to reverse a list.
        reversed_words = words[::-1]
        
        # Join the words in the reversed list back into a string, separated by a single space.
        return " ".join(reversed_words)

Reverse Words in a String in Java

class Solution {
    public String reverseWords(String s) {
        // Use a StringBuilder for efficient string concatenation.
        StringBuilder result = new StringBuilder();
        int i = s.length() - 1;

        // Iterate through the string from right to left.
        while (i >= 0) {
            // Skip trailing spaces of a word (or leading spaces of the whole string).
            while (i >= 0 && s.charAt(i) == ' ') {
                i--;
            }
            
            // If we've scanned past all characters, break the loop.
            if (i < 0) {
                break;
            }

            // Mark the end of the current word.
            int j = i;
            
            // Find the beginning of the current word.
            while (i >= 0 && s.charAt(i) != ' ') {
                i--;
            }

            // Extract the word. The word is from index (i + 1) to (j + 1).
            String word = s.substring(i + 1, j + 1);

            // Append the word to the result.
            // If the result already has content, we need to add a space first.
            if (result.length() > 0) {
                result.append(" ");
            }
            result.append(word);
        }
        
        return result.toString();
    }
}

Reverse Words in a String in C++

class Solution {
public:
    string reverseWords(string s) {
        // This solution implements the in-place O(1) space approach.
        
        // Step 1: Reverse the entire string.
        // "  the sky is blue  " becomes "  eulb si yks eht  "
        reverse(s.begin(), s.end());
        
        int n = s.length();
        int store_idx = 0; // This pointer will track the position to write the next character in the cleaned-up string.

        // Step 2 & 3 combined: Reverse each word and clean up spaces in a single pass.
        for (int start_idx = 0; start_idx < n; ++start_idx) {
            // Find the beginning of a word.
            if (s[start_idx] != ' ') {
                // If this is not the first word we've found, we need to add a space before it.
                if (store_idx != 0) {
                    s[store_idx++] = ' ';
                }

                // Find the end of the word and copy the word to its new location.
                int end_idx = start_idx;
                while (end_idx < n && s[end_idx] != ' ') {
                    s[store_idx++] = s[end_idx++];
                }
                
                // The word is now at s[store_idx - (end_idx - start_idx) ... store_idx-1].
                // Reverse this word in its new place.
                // For example, "eulb" is copied, then reversed to "blue".
                reverse(s.begin() + store_idx - (end_idx - start_idx), s.begin() + store_idx);
                
                // Move start_idx to the position after the current word to continue scanning.
                start_idx = end_idx - 1;
            }
        }
        
        // After the loop, the string from 0 to store_idx holds the result.
        // Resize the string to remove any trailing characters from the original string.
        s.resize(store_idx);
        
        return s;
    }
};

Reverse Words in a String in TypeScript

function reverseWords(s: string): string {
    // This solution uses a pipeline of built-in string and array methods.

    // 1. Trim whitespace from both ends of the string.
    // e.g., "  hello world  " -> "hello world"
    const trimmedS = s.trim();
    
    // 2. Split the string into an array of words.
    // The regex /\s+/ matches one or more whitespace characters.
    // This handles cases with multiple spaces between words.
    // e.g., "a good   example" -> ["a", "good", "example"]
    const words = trimmedS.split(/\s+/);
    
    // 3. Reverse the array of words.
    // e.g., ["blue", "is", "sky", "the"] -> ["the", "sky", "is", "blue"]
    const reversedWords = words.reverse();
    
    // 4. Join the words back into a single string, with a single space as a separator.
    // e.g., ["world", "hello"] -> "world hello"
    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.