Back

Reverse Words in a String

medium

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order, joined by a single space. Your returned string should not contain leading or trailing spaces, nor multiple spaces between words.

Test Cases

Copy an input into the main harness and Run to verify
Input
s = "the sky is blue"
Expected Output
"blue is sky the"
Input
s = " hello world "
Expected Output
"world hello"

Explanation: Leading and trailing spaces are removed.

Input
s = "a good example"
Expected Output
"example good a"

Explanation: Runs of spaces collapse to a single space.

Constraints

  • 1 <= s.length <= 10^4
  • s contains English letters, digits and spaces.
  • There is at least one word in s.

Hints

Hint 1 — click to reveal

The whitespace rules are the real test — leading, trailing, and repeated spaces all have to go.

Hint 2 — click to reveal

Splitting on a run of whitespace handles all three at once.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.