VOOZH about

URL: https://www.geeksforgeeks.org/dsa/substring-reverse-pattern/

⇱ Substring Reverse Pattern - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Substring Reverse Pattern

Last Updated : 12 Sep, 2022

Given string str, the task is to print the pattern given in the examples below:

Examples:  

Input: str = "geeks" 
Output: 
geeks 
*kee* 
**e** 
The reverse of "geeks" is "skeeg" 
Replace the first and last characters with '*' i.e. *kee* 
Replace the second and second last character in the modified string i.e. **e** 
And so on.

Input: str = "first" 
Output: 
first 
*sri* 
**r** 

Approach: 

  • Print the unmodified string.
  • Reverse the string and initialize i = 0 and j = n - 1.
  • Replace s[i] = '*' and s[j] = '*' and update i = i + 1 and j = j - 1 then print the modified string.
  • Repeat the above steps while j - i > 1.

Below is the implementation of the above approach: 


Output
geeks
*kee*
**e**

Complexity Analysis:

  • Time Complexity: O(N) since one traversal of the string is required to complete all operations hence the overall time required by the algorithm is linear
  • Auxiliary Space: O(1) since no extra array is used so the space taken by the algorithm is constant
Comment