Given a string str and an integer X. The task is to reverse the middle X characters of the given string and then print the modified string. Note that len(str) – X is always even.
Examples:
Input: str = “neveropen”, X = 3
Output: neveropenrofneveropen
Middle three character are “neveropenforneveropen”
Hence the resultant string is “neveropenrofneveropen”
Input: str = “acknowledgement”, X = 7
Output: acknegdelwoment
Approach:
- Since we need not reverse the first and last few character. Find the number of characters that we need not reverse in the beginning and in the end i.e. n = len(str) – X / 2.
- Print the first n characters as it is.
- Then print the middle x characters starting from n + 1 in reverse order.
- Finally, the last n characters as it is.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <iostream> using namespace std; // Function to reverse the middle x characters in a string void reverse(string str, int x) { // Find the position from where // the characters have to be reversed int n = (str.length() - x) / 2; // Print the first n characters for ( int i = 0; i < n; i++) cout << str[i]; // Print the middle x characters in reverse for ( int i = n + x - 1; i >= n; i--) cout << str[i]; // Print the last n characters for ( int i = n + x; i < str.length(); i++) cout << str[i]; } // Driver code int main() { string str = "neveropen" ; int x = 3; reverse(str, x); return 0; } |
Java
// Java implementation of the above approach class GfG { // Function to reverse the middle x // characters in a string static void reverse(String str, int x) { // Find the position from where // the characters have to be reversed int n = (str.length() - x) / 2 ; // Print the first n characters for ( int i = 0 ; i < n; i++) System.out.print(str.charAt(i)); // Print the middle x characters in reverse for ( int i = n + x - 1 ; i >= n; i--) System.out.print(str.charAt(i)); // Print the last n characters for ( int i = n + x; i < str.length(); i++) System.out.print(str.charAt(i)); } // Drived code public static void main(String []args) { String str = "neveropen" ; int x = 3 ; reverse(str, x); } } // This code is contributed by Rituraj Jain |
Python3
# Python3 implementation of the approach # Function to reverse the middle x characters in a string def reverse(str1, x): # Find the position from where # the characters have to be reversed n = ( len (str1) - x) / / 2 # Print the first n characters for i in range (n): print (str1[i], end = "") # Print the middle x characters in reverse for i in range (n + x - 1 , n - 1 , - 1 ): print (str1[i], end = "") # Print the last n characters for i in range (n + x, len (str1)): print (str1[i], end = "") # Driver code str1 = "neveropen" x = 3 reverse(str1, x) # This code is contributed by mohit kumar 29. |
C#
// C# implementation of the above approach using System; class GFG { // Function to reverse the middle x // characters in a string static void reverse( string str, int x) { // Find the position from where // the characters have to be reversed int n = (str.Length - x) / 2; // Print the first n characters for ( int i = 0; i < n; i++) Console.Write(str[i]); // Print the middle x characters in reverse for ( int i = n + x - 1; i >= n; i--) Console.Write(str[i]); // Print the last n characters for ( int i = n + x; i < str.Length; i++) Console.Write(str[i]); } // Drived code public static void Main() { string str = "neveropen" ; int x = 3; reverse(str, x); } } // This code is contributed // by Akanksha Rai |
Javascript
<script> // JavaScript implementation of the above approach // Function to reverse the middle x // characters in a string function reverse( str , x) { // Find the position from where // the characters have to be reversed var n = (str.length - x) / 2; // Print the first n characters for (i = 0; i < n; i++) document.write(str.charAt(i)); // Print the middle x characters in reverse for (i = n + x - 1; i >= n; i--) document.write(str.charAt(i)); // Print the last n characters for (i = n + x; i < str.length; i++) document.write(str.charAt(i)); } // Drived code var str = "neveropen" ; var x = 3; reverse(str, x); // This code contributed by aashish1995 </script> |
PHP
<?php // PHP implementation of the approach // Function to reverse the middle x // characters in a string function reverse( $str , $x ) { // Find the position from where // the characters have to be reversed $n = ( strlen ( $str ) - $x ) / 2; // Print the first n characters for ( $i = 0; $i < $n ; $i ++) echo ( $str [ $i ]); // Print the middle x characters in reverse for ( $i = $n + $x - 1; $i >= $n ; $i --) echo ( $str [ $i ]); // Print the last n characters for ( $i = $n + $x ; $i < strlen ( $str ); $i ++) echo $str [ $i ]; } // Driver code $str = "neveropen" ; $x = 3; reverse( $str , $x ); // This code is contributed by Shivi_Aggarwal ?> |
neveropenrofneveropen
Time Complexity: O(n) where n is the length of the string
Auxiliary Space: O(1)
Approach#2: Using slicing
Compute the length of the input string string and the starting and ending positions of the middle substring to be reversed. Extract the middle substring from string using slicing. Reverse the middle substring using the reversed() function and join the characters into a string. Concatenate the three parts of string: the part before the reversed middle substring, the reversed middle substring, and the part after the reversed middle substring. Return the final concatenated string.
Algorithm
1. Compute the length of the input string string and the starting and ending positions of the middle substring to be reversed using the formula (n – x) // 2 and (n – x) // 2 + x, where n is the length of string and x is the number of characters to reverse.
2. Extract the middle substring from string using slicing and assign it to chars_to_reverse.
3. Reverse the characters in chars_to_reverse using the reversed() function and assign the result to reversed_chars.
4. Concatenate the three parts of string using the + operator: the part before the reversed middle substring (string[:mid_start]), the reversed middle substring (reversed_chars), and the part after the reversed middle substring (string[mid_end:]).
5. Return the final concatenated string.
C++
#include <iostream> #include <string> using namespace std; // Function to reverse middle characters of a string based on the given length x string reverseMiddleChars(string str, int x) { int n = str.length(); int mid_start = (n - x) / 2; int mid_end = mid_start + x; string chars_to_reverse = str.substr(mid_start, x); // Reversing the characters string reversed_chars = "" ; for ( int i = chars_to_reverse.length() - 1; i >= 0; i--) { reversed_chars += chars_to_reverse[i]; } // Constructing the final string by concatenating the parts return str.substr(0, mid_start) + reversed_chars + str.substr(mid_end); } int main() { string str = "neveropen" ; int x = 3; cout << reverseMiddleChars(str, x) << endl; return 0; } |
Java
// Java code import java.io.*; public class ReverseMiddleChars { // Function to reverse middle characters of a string based on the given length x static String reverseMiddleChars(String str, int x) { int n = str.length(); int midStart = (n - x) / 2 ; int midEnd = midStart + x; String charsToReverse = str.substring(midStart, midEnd); // Reversing the characters StringBuilder reversedChars = new StringBuilder(); for ( int i = charsToReverse.length() - 1 ; i >= 0 ; i--) { reversedChars.append(charsToReverse.charAt(i)); } // Constructing the final string by concatenating the parts return str.substring( 0 , midStart) + reversedChars + str.substring(midEnd); } public static void main(String[] args) { String str = "neveropen" ; int x = 3 ; System.out.println(reverseMiddleChars(str, x)); } } // This code is contributed by guptapratik |
Python3
def reverse_middle_chars(string, x): n = len (string) mid_start = (n - x) / / 2 mid_end = mid_start + x chars_to_reverse = string[mid_start:mid_end] reversed_chars = ''.join( reversed (chars_to_reverse)) return string[:mid_start] + reversed_chars + string[mid_end:] string = 'neveropen' x = 3 print (reverse_middle_chars(string, x)) |
C#
using System; class Program { // Function to reverse middle characters of a string based on the given length x static string ReverseMiddleChars( string str, int x) { int n = str.Length; int midStart = (n - x) / 2; int midEnd = midStart + x; string charsToReverse = str.Substring(midStart, x); // Reversing the characters char [] reversedCharsArray = charsToReverse.ToCharArray(); Array.Reverse(reversedCharsArray); string reversedChars = new string (reversedCharsArray); // Constructing the final string by concatenating the parts return str.Substring(0, midStart) + reversedChars + str.Substring(midEnd); } static void Main() { string str = "neveropen" ; int x = 3; Console.WriteLine(ReverseMiddleChars(str, x)); } } |
Javascript
// Function to reverse middle characters of a string based on the given length x function reverseMiddleChars(str, x) { const n = str.length; const midStart = Math.floor((n - x) / 2); const midEnd = midStart + x; const charsToReverse = str.substring(midStart, midEnd); // Reversing the characters let reversedChars = '' ; for (let i = charsToReverse.length - 1; i >= 0; i--) { reversedChars += charsToReverse.charAt(i); } // Constructing the final string by concatenating the parts return str.substring(0, midStart) + reversedChars + str.substring(midEnd); } const str = "neveropen" ; const x = 3; console.log(reverseMiddleChars(str, x)); |
neveropenrofneveropen
Time Complexity: O(n), where n is the length of the input string string. This is because the code performs slicing and concatenation operations that take time proportional to the length of the string.
Auxiliary Space: O(n), where n is the length of the input string string. This is because the code creates a new string to hold the reversed characters, which could be as long as the middle substring of string. Additionally, the sliced parts of string are also stored in memory during the concatenation process.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!