AlgoMaster Logo

Reverse Words in a String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Using Built-in Functions

Intuition:

This approach leverages built-in language functions to split the string by spaces, remove any empty elements, and reverse the resulting word list. This is straightforward but relies heavily on library functions.

Steps:

  1. Split the input string by spaces.
  2. Filter out any empty strings resulting from extra spaces.
  3. Reverse the list and join the words into a single string with space separation.

Code:

2. Two Pointers with Deque

Intuition:

Using a two-pointer approach along with a deque (double-ended queue) can help manage space efficiently and avoid unnecessary memory allocation beyond what is required to store words. This technique manually traverses the string and accumulates words in reverse order.

Steps:

  1. Traverse the string from end to start using two pointers to find words.
  2. Use a deque to efficiently manage the words that should appear first in the result.
  3. Append words to the front of the deque and join them at the end.

3. Two Pointers: In-place Replacement

Intuition:

This method reverses the entire string first, then reverses each word in place. This technique is more space efficient because the reversal occurs directly within the input string resorted to character arrays.

Steps:

  1. Reverse the entire character array.
  2. Reverse each word within the array.
  3. Clean up any extra spaces resulting from the reversal process.

Code: