Problem
Ask
Submissions

Problem: Reverse Words in a String

Medium
30 min
Explore how to reverse words in a sentence without altering the characters in each word. This lesson helps you understand and implement the two pointers pattern to efficiently handle spaces and rearrange words in a string.

Statement

You are given a string sentence that may contain leading or trailing spaces, as well as multiple spaces between words. Your task is to reverse the order of the words in the sentence without changing the order of characters within each word. Return the resulting modified sentence as a single string with words separated by a single space, and no leading or trailing spaces.

Note: A word is defined as a continuous sequence of non-space characters. Multiple words separated by single spaces form a valid English sentence. Therefore, ensure there is only a single space between any two words in the returned string, with no leading, trailing, or extra spaces.

Constraints:

  • The sentence contains English uppercase and lowercase letters, digits, and spaces.

  • There is at least one word in a sentence.

  • 11 \leq sentence.length 104\leq 10^4

Problem
Ask
Submissions

Problem: Reverse Words in a String

Medium
30 min
Explore how to reverse words in a sentence without altering the characters in each word. This lesson helps you understand and implement the two pointers pattern to efficiently handle spaces and rearrange words in a string.

Statement

You are given a string sentence that may contain leading or trailing spaces, as well as multiple spaces between words. Your task is to reverse the order of the words in the sentence without changing the order of characters within each word. Return the resulting modified sentence as a single string with words separated by a single space, and no leading or trailing spaces.

Note: A word is defined as a continuous sequence of non-space characters. Multiple words separated by single spaces form a valid English sentence. Therefore, ensure there is only a single space between any two words in the returned string, with no leading, trailing, or extra spaces.

Constraints:

  • The sentence contains English uppercase and lowercase letters, digits, and spaces.

  • There is at least one word in a sentence.

  • 11 \leq sentence.length 104\leq 10^4