Coding problem · Easy · Basics
Reverse the Words
Easy Algorithms & data structures
Given a sentence s of words separated by single spaces, return the words in reverse order.
Example 1
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2
Input: s = "hello" Output: "hello"
Hints
Hint 1
Split into words, reverse the list, join with spaces.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(n)
Split on spaces, reverse the resulting list of words, and join it back. The characters inside each word stay in order.
Reference solution
function reverseWords(s) {
return s.split(' ').reverse().join(' ');
}
function reverseWords(s: string): string {
return s.split(' ').reverse().join(' ');
}
def reverse_words(s: str) -> str:
return ' '.join(reversed(s.split(' ')))
<?php
function reverseWords(string $s): string
{
return implode(' ', array_reverse(explode(' ', $s)));
}
class Solution {
public String reverseWords(String s) {
java.util.List<String> words = java.util.Arrays.asList(s.split(" "));
java.util.Collections.reverse(words);
return String.join(" ", words);
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy