Reverse Only Alphabets Problem

Given: A string containing special characters (!,@,^,&,$) and alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’). We have to reverse only the alphabets keeping the special symbols intact. 

Input: A@%gh,q

Output: q@%hg,A

Explanation: Here we have to reverse characters in the array and ignore the special symbols. Only the position of characters will change and position of special symbols will be same. 

# Approach 1(Efficient)

In this method, we will be not using extra space.


#include <iostream>
#include <string.h>

//Function returns 1(true) if x is alphabet,0(false otherwise

int check_alpha(char z)


	int flag = 0;

	if ((z >= 'A' && z <= 'Z') || (z >= 'a' && z <= 'z'))

		flag = 1;


		flag = 0;

	if (flag == 0)

		return 0;


		return 1;


//Function reverses a string

void revstring(char str[])


	// Initializing x and y

	int x = strlen(str) - 1, y = 0;

	//Traversing from both ends, till x &y are equal

	while (y < x)


		// leave special characters

		if (!check_alpha(str[y]))


		else if (!check_alpha(str[x]))



		// if both s[y] and s[x] are alphabatical characters

		//swap the alphabets


			char temp;

			temp = str[y];

			str[y] = str[x];

			str[x] = temp;



int main()


	char str[] = "A@%gh&q";

	std::cout << "Input string: " << str << std::endl;


	std::cout << "Output string: " << str << std::endl;

	return 0;



# Approach 2

In this approach, we have to use extra space by making a new array like pass[].

Follow the following steps:-

1) Create a auxilary character array like pass[].
2) Now copy alphabets from given array to pass[].
3) Reversing pass[] using string reversal.
4) We traverse input string and pass in a single loop. When a alphabet character occurs in input string, replace it with present character of pass[].


Report Error/ Suggestion

Related Posts:


Interview Questions

CopyRight © 2020

CopyRight © 2020