Solution: Reverse Words in a String

Let's solve the Reverse Words in a String problem using the Two Pointers pattern.

Statement

Given a sentenceA sentence is a string of space-separated words., reverse the order of its wordsA word is a string of characters without any spaces. without affecting the order of letters within the given word.

Constraints:

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

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

  • The order of the letters within a word is not to be reversed.

Note: The input string may contain leading or trailing spaces or multiple spaces between words. The returned string, however, should only have a single space separating each word. Do not include any extra spaces.

Solution

For this problem, the goal is to reverse the order of the words in a given string. We'll use the two pointers approach that will help us manipulate the string in place (without needing additional memory for another string), which is efficient in terms of time complexity. 

We can solve this problem in two main steps:

  1. Reverse the entire string: First, we reverse the entire string. This action places the words in the desired order, but each word is itself reversed (i.e., the characters in each word are in the reverse order).

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.