20 · String Parsing & Expression Evaluation

#151 Reverse Words in a String

Mediumsolve on LeetCode ↗

frequently reported atAppleMicrosoftBloombergAmazonGoogleMeta

the problem

In plain words

A string s holds words made of letters and digits, separated by spaces. There may be extra spaces at the start, at the end, or between words. Return the words in reverse order, joined by exactly one space, with no spaces at either end.

in s = "the sky is blue"

out "blue is sky the"

in s = " hello world "

out "world hello"

The spaces at both ends disappear.

in s = "a good example"

out "example good a"

The run of three spaces becomes one.

  • 1 ≤ s.length ≤ 10⁴
  • s has English letters, digits and ' '
  • s contains at least one word
  • Follow-up: if strings could change in place, use O(1) extra space

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #189
      Rotate Array
      Mediumin Arrays & Strings
    2. #344
      Reverse String
      Easyin Recursion
    3. #125
      Valid Palindrome
      Easyin Two Pointers