Click Below to subscribe

Reverse a string without affecting special characters.

Given a string S, that contains special characters with alphabets, reverse the string in a way that special characters are not affected.

So firstly we need to check whether an element is an alphabet or not.

function isAlphabet(char) { 
    return ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')); 
} 

#Implementation:- Time complexity - O(n)

function reverse(str) {  
	if(!str) {
		return '';
	}
    const charArray = str.split('');
    let i = 0, j = charArray.length - 1; 
    
    while (i < j) 
    { 
        if (!isAlphabet(charArray[i])) { 
            i++;
        } 
        else if(!isAlphabet(charArray[j])) { 
            j--; 
        }
        else { 
            [charArray[i], charArray[j]] = [charArray[j], charArray[i]]; //swap
            i++; 
            j--; 
        } 
    } 
	return charArray.join('');
}

Test Program:-

const str = "we're all we've got";
console.log(reverse(str));

//output- to'ge vew ll'ae rew

#Note:- Here I am using array destructuring for swapping, you can also use a temporary variable.

Destructuring assignment

let a = 1;
let b = 3;
[a, b] = [b, a];

console.log(a, b);  // 3  1

const arr = [1,2,3];
[arr[2], arr[1]] = [arr[1], arr[2]];

console.log(arr); // [1, 3, 2]

swapping using a temporary variable

const temp   = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
i++; 
j--; 

Leave Your Comment