MediumTwo PointersString

1 approach, code in every language

Problem description

Given a string made of words separated by spaces, produce a new string in which the order of the words is reversed. A word is any maximal run of non-space characters.

The result must contain the words in reverse order joined by exactly one space, with no leading or trailing spaces and no repeated spaces between words, even if the input had extra spacing.

Example 1

Input: s = "the sky is blue"

Output: "blue is sky the"

The four words are listed from last to first with single spaces between them.

Example 2

Input: s = " hello world "

Output: "world hello"

Surrounding and repeated interior spaces are collapsed while the two words swap positions.

Constraints

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

After the pattern

Now solve one you haven't seen.

Read the Caption Back to Front is our own problem on the technique behind Reverse Words in a String: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free