v9.1.1
Menu

Reverse Words in a String

mediumFREEStrings & ParsingApple DSA

Given a string s, reverse the order of words. A word is a sequence of non-space characters. Remove leading/trailing spaces and reduce multiple spaces to a single space.

Example

Input
the sky is blue
Output
blue is sky the
Reasoning
  • The input string the sky is blue is split into individual words: the, sky, is, blue
  • These words are then reversed in order to produce the desired output
  • The reversed words are joined back together with a single space in between each word: blue is sky the
  • The resulting string has no leading or trailing spaces and only single spaces between words, yielding the final output: blue is sky the

Constraints

  • 1 <= len(s) <= 10^4
  • s contains English letters, digits, and spaces

More from Apple DSA

solution.py

Test results

Sign in to run your code against the test cases.