Reverse Individual Words With O(1) Extra Space


A string may be composed of several words. Every word in a C++ string may contain letters, numbers or special symbols. Strings are considered to be storage elements for these kind of characters. Each word is separated by a space character. Each word also forms a string of characters. Reverse of any string in C++ is the string follows the following points −

  • It is formed by taking characters from the end towards the beginning.

  • The length of the original string remains unchanged.

The order of occurrence of characters in a string can be reversed easily by swapping the characters at the start and end of the word.

Constant auxiliary space is denoted by O(1), which means that no extra space is required by the program to complete its execution.

Some of the examples illustrating the problem statement are as

Sample Examples

Example 1 - str : Abc def

Output : cbA fed

Explanation : The case of the characters remain as it is while reversing the strings.

Example 2 - str : Hey spe%32

Output : yeH 23%eps

The problem statement can be solved by extracting the individual words and maintaining a pair of start and end pointers for each word, and then reversing it.

Algorithm

  • Step 1 − A for loop is used to iterate through the input string provided.

  • Step 2 − The start character of the first word is captured using a variable st.

  • Step 3 − As soon as the first space is encountered, the lst variable is fixed at the previous character, to mark the starting and ending characters of the word respectively.

  • Step 4 −Using these two pointers, and a while loop, the characters of this word are reversed. During each iteration of the while loop the pointers are shifted to exhaust the string.

  • Step 5 − The values are updated to shift the pointers to the next subsequent word and so on. st is reinitialised to the next character after space.

  • Step 6 − The entire string is iterated and the corresponding words thus reversed.

Example

The following C++ code snippet takes as input a string and reverses the words contained within it −

// including the required libraries
#include <bits/stdc++.h>
using namespace std;

//reversing current word of string
void reverseWord(string &st, int s, int e){
   while (s < e) {
      swap(st[s], st[e]);
      s++;
      e--;
   }
}

//reverse the words of a string
string reverseString(string str){
   int len = str.length();

   //initialising the pointer with the first letter of the input string
   int st = 0;
   for (int i = 0; i <= len; i++) {

      //stop the pointer at the first word
      //either a space will be found indicating end of word or the string is finished
      char ch = str[i];
      if (ch == ' ' || i == len) {

         //fetching the last character of the current word of the string
         int lst = i - 1;

         // Reverse the current word
         reverseWord(str, st,lst);

         //since the ith character is string , go to i+1 th character to fetch next word
         st = i + 1;
      }
   }
   return str;
}

//calling the method to reverse words
int main(){

   //input string
   string str = "Reverse words Tutorials Point";
   cout<<"original String:"<<str;

   //reversed string
   string revstr = reverseString(str);
   cout << "\nReversed string : "<< revstr;
   return 0;
}

Output

original String:Reverse words Tutorials Point
Reversed string : esreveR sdrow slairotuT tnioP

Space Complexity

The space required in the above approach is constant, since no new initialisations to any kind of variables are made. No external space storage is required to swap the words. All the modifications are made in the available storage variables.

Conclusion

A string is composed of characters, which can be arranged in any order or reversed with a simple iteration over the string. Since, the algorithm performs a single iteration over the entire span of characters stored within it, the total time required is O(n), where n is the length of the string.

Updated on: 15-Mar-2023

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements