Reverse Words in a String
Problem Statement
Given a string, reverse the order of the words. Words are separated by one or more spaces, and the result should not contain leading or trailing spaces, with exactly one space between words. This is an easy-level problem testing string manipulation skills.
Example
Input: s = " hello world "
Output: "world hello" (reversed words with single spaces)
Input: s = "the sky is blue"
Output: "blue is sky the"
Code
Java
Python
JavaScript
public class Solution { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); StringBuilder result = new StringBuilder(); for (int i = words.length - 1; i >= 0; i--) { result.append(words[i]); if (i > 0) result.append(" "); } return result.toString(); } }
def reverse_words(s): words = s.strip().split() return " ".join(words[::-1]) # Example usage print(reverse_words(" hello world ")) # "world hello" print(reverse_words("the sky is blue")) # "blue is sky the"
function reverseWords(s) { let words = s.trim().split(/\s+/); return words.reverse().join(" "); } // Example usage console.log(reverseWords(" hello world ")); // "world hello" console.log(reverseWords("the sky is blue")); // "blue is sky the"
Explanation
- Trim the string to remove leading and trailing spaces.
- Split the string into words, handling multiple spaces appropriately.
- Reverse the array of words (either manually or using built-in methods).
- Join the words back together with a single space between them.
- Return the resulting string.
Note
Time complexity is O(n) where n is the string length. Space complexity is O(n) for storing the words array.