151. Reverse Words in a String
Asked at 25Apple65Microsoft57Bloomberg53Amazon51Google46Meta45Deutsche Bank72Infosys54Yelp94Nykaa89Snap83Zopsmart62ServiceNow55Nvidia55Barclays53Capgemini52EPAM Systems51IBM44Accenture44TikTok41Cisco37LinkedIn37tcs36Oracle35Goldman Sachs21
Problem
Return the words of s in reverse order, joined by single spaces. s may have leading, trailing or repeated spaces, which must not appear in the output.
Example: " hello world " → "world hello"
Constraints: follow-up: O(1) extra space if strings are mutable.
Split on whitespace (drops extra spaces), reverse, join. In-place follow-up (char array): reverse the whole string, then reverse each word, then compact spaces.
Complexity: O(n).
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
assert Solution().reverseWords("the sky is blue") == "blue is sky the"
assert Solution().reverseWords(" hello world ") == "world hello"
assert Solution().reverseWords("a good example") == "example good a"
class Solution {
public String reverseWords(String s) {
List<String> words = Arrays.asList(s.trim().split("\\s+"));
Collections.reverse(words);
return String.join(" ", words);
}
}
func reverseWords(s string) string {
words := strings.Fields(s)
for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
return strings.Join(words, " ")
}