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(' ');
}

Was this page helpful?