MediumTwo PointersString

Reverse Words in a String

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now