← Back to Leo Academy Masterclass

Problem #151: Reverse Words in a String

Medium Array & String

Intuition & Strategy Breakdown

Trim string, split words by whitespace, reverse word order list, and join words with a single space.

Python Solution

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.split()[::-1])

Java Solution

class Solution {
    public 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();
    }
}
Watch Interactive Video on Leo Academy Main App