28.6k views
5 votes
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue".
return "blue is sky the".
Could you do it in-place without allocating extra space?"

1 Answer

0 votes

Final answer:

Reversing an input string word by word in-place involves two steps: First, reversing the entire string, then reversing each word in the reversed string to achieve the correct word order without extra space.

Step-by-step explanation:

To reverse a given input string word by word in-place without using extra space, we need to understand the constraints and devise a procedure that manipulates the string within its own space. Since we know that the words are separated by a single space and there are no leading or trailing spaces, the reversing can be done in two steps:

  1. Reverse the entire string. This makes the string appear as if it's in reverse order character by character.
  2. Reverse each word within the now reversed string. Since we have reversed the string entirely in the previous step, when we reverse each word again, they will appear in correct order, but the sequence of words will be reversed, thus giving us the desired output.

Here is a step-by-step demonstration for the string the sky is blue:

  1. Reverse the entire string.
  2. Reverse each word separately to get blue is sky the.

Remember, this approach assumes we can modify the original string and does not require any additional memory allocation for a new string, thus being an in-place solution.

User Aniket Singh
by
8.3k points