Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
How to Reverse a String in C?
Next article icon

Substring Reverse Pattern

Last Updated : 12 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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++




// C++ program to print the required pattern
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the required pattern
void printPattern(char s[], int n)
{
 
    // Print the unmodified string
    cout << s << "\n";
 
    // Reverse the string
    int i = 0, j = n - 2;
    while (i < j) {
        char c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
 
    // Replace the first and last character by '*' then
    // second and second last character and so on
    // until the string has characters remaining
    i = 0;
    j = n - 2;
    while (j - i > 1) {
        s[i] = s[j] = '*';
        cout << s << "\n";
        i++;
        j--;
    }
}
 
// Driver code
int main()
{
    char s[] = "geeks";
    int n = sizeof(s) / sizeof(s[0]);
 
    printPattern(s, n);
    return 0;
}
 
 

Java




// Java program to print the required pattern
class GFG
{
     
// Function to print the required pattern
static void printPattern(char[] s, int n)
{
    // Print the unmodified string
    System.out.println(s);
 
    // Reverse the string
    int i = 0, j = n - 1;
    while (i < j)
    {
        char c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
 
    // Replace the first and last character
    // by '*' then second and second last
    // character and so on until the string
    // has characters remaining
    i = 0;
    j = n - 1;
    while (j - i > 1)
    {
        s[i] = s[j] = '*';
        System.out.println(s);
        i++;
        j--;
    }
}
 
// Driver Code
public static void main(String []args)
{
    char[] s = "geeks".toCharArray();
    int n = s.length;
 
    printPattern(s, n);
}
}
 
// This code is contributed by Rituraj Jain
 
 

Python3




# Python3 program to print the required pattern
 
# Function to print the required pattern
def printPattern(s, n):
 
    # Print the unmodified string
    print(''.join(s))
 
    # Reverse the string
    i, j = 0, n - 1
     
    while i < j:
        s[i], s[j] = s[j], s[i]
        i += 1
        j -= 1
     
    # Replace the first and last character
    # by '*' then second and second last
    # character and so on until the string
    # has characters remaining
    i, j = 0, n - 1
     
    while j - i > 1:
        s[i], s[j] = '*', '*'
        print(''.join(s))
        i += 1
        j -= 1
 
# Driver code
if __name__ == "__main__":
 
    s = "geeks"
    n = len(s)
 
    printPattern(list(s), n)
     
# This code is contributed
# by Rituraj Jain
 
 

C#




// C# program to print the required pattern
using System;
 
class GFG
{
     
// Function to print the required pattern
static void printPattern(char[] s, int n)
{
    // Print the unmodified string
    Console.WriteLine(s);
 
    // Reverse the string
    int i = 0, j = n - 1;
    while (i < j)
    {
        char c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
 
    // Replace the first and last character
    // by '*' then second and second last
    // character and so on until the string
    // has characters remaining
    i = 0;
    j = n - 1;
    while (j - i > 1)
    {
        s[i] = s[j] = '*';
        Console.WriteLine(s);
        i++;
        j--;
    }
}
 
// Driver Code
public static void Main(String []args)
{
    char[] s = "geeks".ToCharArray();
    int n = s.Length;
 
    printPattern(s, n);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// Javascript program to print the required pattern
 
// Function to print the required pattern
function printPattern(s, n)
{
 
    // Print the unmodified string
    document.write( s.join('') + "<br>");
 
    // Reverse the string
    var i = 0, j = n - 1;
    while (i < j) {
        var c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
 
    // Replace the first and last character by '*' then
    // second and second last character and so on
    // until the string has characters remaining
    i = 0;
    j = n - 1;
    while (j - i > 1) {
        s[i] = s[j] = '*';
        document.write( s.join('') + "<br>");
        i++;
        j--;
    }
}
 
// Driver code
var s = "geeks".split('');
var n = s.length;
printPattern(s, n);
 
 
</script>
 
 
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


Next Article
How to Reverse a String in C?

S

SanjayR
Improve
Article Tags :
  • C Programs
  • DSA
  • Strings
  • Technical Scripter
  • pattern-printing
  • Reverse
  • substring
Practice Tags :
  • pattern-printing
  • Reverse
  • Strings

Similar Reads

  • Reverse String in C
    In C, reversing a string means rearranging the characters such that the last character becomes the first, the second-to-last character becomes the second, and so on. In this article, we will learn how to reverse string in C. The most straightforward method to reverse string is by using two pointers
    3 min read
  • How to Reverse a String in C?
    In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
    2 min read
  • C Program to Reverse a String Using Recursion
    Reversing a string means changing the order of characters in the string so that the last character becomes the first character of the string. In this article, we will learn how to reverse a string using recursion in a C program. The string can be reversed by using two pointers: one at the start and
    1 min read
  • C Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "
    3 min read
  • How to Match a Pattern in a String in C?
    Matching a pattern in a string involves searching for a specific sequence of characters within a larger string. In this article, we will learn different methods to efficiently match patterns in a string in C. The most straightforward method to match a string is by using strstr() function. Let’s take
    3 min read
  • Program for Reversed String Pattern
    Given string str as the input. The task is to print the pattern as shown in the example. Examples: Input : str = "geeks" Output : g e e * s k Explanation : In the first line, print the first character in the string. In the second line, print the next two characters in reverse order. In the third lin
    6 min read
  • Perfect reversible string
    You are given a string 'str', the task is to check the reverses of all possible substrings of 'str' are present in 'str' or not. Examples: Input : str = "ab" Output: "NO" // all substrings are "a","b","ab" but reverse // of "ab" is not present in str Input : str = "aba" Output: "YES" Input : str = "
    6 min read
  • PHP Reverse a String
    Reversing a string in PHP refers to rearranging a given string's characters in reverse order, starting from the last character to the first. This task is often used in text manipulation or algorithm challenges, highlighting PHP's string-handling capabilities. Examples: Input : GeeksforGeeksOutput :
    3 min read
  • Reverse words in a string
    Given a string str, your task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words. Examples: Input: str = "i.like.this
    11 min read
  • SQL Server SUBSTRING() Function
    The SQL Server SUBSTRING function extracts a substring from a string, starting at a specified position and with an optional length. The SUBSTRING function also works in Azure SQL Database, Azure SQL Data Warehouse, and Parallel Data Warehouse. SyntaxThe SQL SUBSTRING function syntax is: SUBSTRING(in
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences