Given a line of text, reverse the text without reversing the individual words.

For example,

Input:  Technical Interview Preparation
 
Output: Preparation Interview Technical

Practice this problem

A simple solution is to push the individual words from the beginning of the text into a stack. Then, pop all the words from the stack and store them back into the text in LIFO order. The time complexity of the above solution is O(n) and requires O(n) extra space for the stack, where n is the length of the given text.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

Technical Interview Preparation

Java


Download  Run Code

Output:

Technical Interview Preparation

Python


Download  Run Code

Output:

Technical Interview Preparation

How can we improve space complexity?

The idea is to in-place reverse each word present in the input text and finally reverse the whole text to get the desired output. For instance,

Input text: Preparation Interview Technical
 
1. Reverse each word:
noitaraperp weivretnI lacinhceT TI rof lairetam doog edivorp eW
 
2. Reverse the whole text:
Technical Interview Preparation

The time complexity of this solution would be O(n) and doesn’t require any extra space. The problem with this approach is that it violates the problem constraints and does three traversals of the input text instead of just one.

C


Download  Run Code

Output:

Technical Interview Preparation

C++


Download  Run Code

Output:

Technical Interview Preparation

Java


Download  Run Code

Output:

Technical Interview Preparation

Python


Download  Run Code

Output:

Technical Interview Preparation

 
Exercise: Modify the first approach to divide string into tokens by using strtok() in C, or stringstream getline(), or C++ string class find() function.