Reverse Middle X Characters
Last Updated :
19 Oct, 2023
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 = “geeksforgeeks”, X = 3
Output: geeksrofgeeks
Middle three character are “geeksforgeeks”
Hence the resultant string is “geeksrofgeeks”
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++
#include <iostream>
using namespace std;
void reverse(string str, int x)
{
int n = (str.length() - x) / 2;
for ( int i = 0; i < n; i++)
cout << str[i];
for ( int i = n + x - 1; i >= n; i--)
cout << str[i];
for ( int i = n + x; i < str.length(); i++)
cout << str[i];
}
int main()
{
string str = "geeksforgeeks" ;
int x = 3;
reverse(str, x);
return 0;
}
|
Java
class GfG
{
static void reverse(String str, int x)
{
int n = (str.length() - x) / 2 ;
for ( int i = 0 ; i < n; i++)
System.out.print(str.charAt(i));
for ( int i = n + x - 1 ; i >= n; i--)
System.out.print(str.charAt(i));
for ( int i = n + x; i < str.length(); i++)
System.out.print(str.charAt(i));
}
public static void main(String []args)
{
String str = "geeksforgeeks" ;
int x = 3 ;
reverse(str, x);
}
}
|
Python3
def reverse(str1, x):
n = ( len (str1) - x) / / 2
for i in range (n):
print (str1[i], end = "")
for i in range (n + x - 1 , n - 1 , - 1 ):
print (str1[i], end = "")
for i in range (n + x, len (str1)):
print (str1[i], end = "")
str1 = "geeksforgeeks"
x = 3
reverse(str1, x)
|
C#
using System;
class GFG
{
static void reverse( string str, int x)
{
int n = (str.Length - x) / 2;
for ( int i = 0; i < n; i++)
Console.Write(str[i]);
for ( int i = n + x - 1; i >= n; i--)
Console.Write(str[i]);
for ( int i = n + x; i < str.Length; i++)
Console.Write(str[i]);
}
public static void Main()
{
string str = "geeksforgeeks" ;
int x = 3;
reverse(str, x);
}
}
|
Javascript
<script>
function reverse( str , x)
{
var n = (str.length - x) / 2;
for (i = 0; i < n; i++)
document.write(str.charAt(i));
for (i = n + x - 1; i >= n; i--)
document.write(str.charAt(i));
for (i = n + x; i < str.length; i++)
document.write(str.charAt(i));
}
var str = "geeksforgeeks" ;
var x = 3;
reverse(str, x);
</script>
|
PHP
<?php
function reverse( $str , $x )
{
$n = ( strlen ( $str ) - $x ) / 2;
for ( $i = 0; $i < $n ; $i ++)
echo ( $str [ $i ]);
for ( $i = $n + $x - 1; $i >= $n ; $i --)
echo ( $str [ $i ]);
for ( $i = $n + $x ; $i < strlen ( $str ); $i ++)
echo $str [ $i ];
}
$str = "geeksforgeeks" ;
$x = 3;
reverse( $str , $x );
?>
|
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;
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);
string reversed_chars = "" ;
for ( int i = chars_to_reverse.length() - 1; i >= 0; i--) {
reversed_chars += chars_to_reverse[i];
}
return str.substr(0, mid_start) + reversed_chars + str.substr(mid_end);
}
int main() {
string str = "geeksforgeeks" ;
int x = 3;
cout << reverseMiddleChars(str, x) << endl;
return 0;
}
|
Java
import java.io.*;
public class ReverseMiddleChars {
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);
StringBuilder reversedChars = new StringBuilder();
for ( int i = charsToReverse.length() - 1 ; i >= 0 ; i--) {
reversedChars.append(charsToReverse.charAt(i));
}
return str.substring( 0 , midStart) + reversedChars + str.substring(midEnd);
}
public static void main(String[] args) {
String str = "geeksforgeeks" ;
int x = 3 ;
System.out.println(reverseMiddleChars(str, x));
}
}
|
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 = 'geeksforgeeks'
x = 3
print (reverse_middle_chars(string, x))
|
C#
using System;
class Program
{
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);
char [] reversedCharsArray = charsToReverse.ToCharArray();
Array.Reverse(reversedCharsArray);
string reversedChars = new string (reversedCharsArray);
return str.Substring(0, midStart) + reversedChars + str.Substring(midEnd);
}
static void Main()
{
string str = "geeksforgeeks" ;
int x = 3;
Console.WriteLine(ReverseMiddleChars(str, x));
}
}
|
Javascript
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);
let reversedChars = '' ;
for (let i = charsToReverse.length - 1; i >= 0; i--) {
reversedChars += charsToReverse.charAt(i);
}
return str.substring(0, midStart) + reversedChars + str.substring(midEnd);
}
const str = "geeksforgeeks" ;
const x = 3;
console.log(reverseMiddleChars(str, x));
|
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.
Share your thoughts in the comments
Please Login to comment...