Search⌘ K
AI Features

Reverse Words in a String

Explore the method of reversing the order of words in a sentence using the two pointers technique. Understand how to handle leading, trailing, and multiple spaces while maintaining character order within words. This lesson equips you to manipulate strings effectively, preparing you for coding interviews requiring array and string manipulation skills.

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

Examples

canvasAnimation-image
1 / 4

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Reverse Words in a String

1.

What is the output if the following sentence is given as an input?

“The quick brown fox jumped over a lazy dog”.

A.

“lazy dog a over fox jumped brown quick The”

B.

“dog lazy over a jumped fox brown quick The”

C.

“dog lazy jumped jumped fox brown quick The”

D.

“dog lazy a over jumped fox brown quick The”


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > main.js
function reverseWords(sentence) {
// Replace this placeholder return statement with your code
return "";
}
export {
reverseWords
}
Reverse Words in a String