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:
C++
#include <bits/stdc++.h>
using namespace std;
void printPattern( char s[], int n)
{
cout << s << "\n" ;
int i = 0, j = n - 2;
while (i < j) {
char c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
}
i = 0;
j = n - 2;
while (j - i > 1) {
s[i] = s[j] = '*' ;
cout << s << "\n" ;
i++;
j--;
}
}
int main()
{
char s[] = "geeks" ;
int n = sizeof (s) / sizeof (s[0]);
printPattern(s, n);
return 0;
}
|
Java
class GFG
{
static void printPattern( char [] s, int n)
{
System.out.println(s);
int i = 0 , j = n - 1 ;
while (i < j)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
}
i = 0 ;
j = n - 1 ;
while (j - i > 1 )
{
s[i] = s[j] = '*' ;
System.out.println(s);
i++;
j--;
}
}
public static void main(String []args)
{
char [] s = "geeks" .toCharArray();
int n = s.length;
printPattern(s, n);
}
}
|
Python3
def printPattern(s, n):
print (''.join(s))
i, j = 0 , n - 1
while i < j:
s[i], s[j] = s[j], s[i]
i + = 1
j - = 1
i, j = 0 , n - 1
while j - i > 1 :
s[i], s[j] = '*' , '*'
print (''.join(s))
i + = 1
j - = 1
if __name__ = = "__main__" :
s = "geeks"
n = len (s)
printPattern( list (s), n)
|
C#
using System;
class GFG
{
static void printPattern( char [] s, int n)
{
Console.WriteLine(s);
int i = 0, j = n - 1;
while (i < j)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
}
i = 0;
j = n - 1;
while (j - i > 1)
{
s[i] = s[j] = '*' ;
Console.WriteLine(s);
i++;
j--;
}
}
public static void Main(String []args)
{
char [] s = "geeks" .ToCharArray();
int n = s.Length;
printPattern(s, n);
}
}
|
Javascript
<script>
function printPattern(s, n)
{
document.write( s.join( '' ) + "<br>" );
var i = 0, j = n - 1;
while (i < j) {
var c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
}
i = 0;
j = n - 1;
while (j - i > 1) {
s[i] = s[j] = '*' ;
document.write( s.join( '' ) + "<br>" );
i++;
j--;
}
}
var s = "geeks" .split( '' );
var n = s.length;
printPattern(s, n);
</script>
|
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