JavaScript Program to Mirror Characters of a String
Last Updated :
09 Jul, 2024
Our task is to mirror characters from the N-th position up to the end of a given string, where 'a' will be converted into 'z', 'b' into 'y', and so on. This JavaScript problem requires mirroring the characters in a string starting from a specified position. There are various approaches available to accomplish this, such as utilizing loops and maps. In this article, we will explore various methods to find the mirror characters of a string.
Examples:
Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.
Input : N = 6
pneumonia
Output : pnefnlmrz
Method 1: Creating a String:
In this method, we maintain a string (or a character array) containing the English lowercase alphabet. Starting from the pivot point up to the length of the string, we retrieve the reversed alphabetical counterpart of a character by using its ASCII value as an index. By applying this approach, we convert the given string into the desired mirrored form.
Syntax:
let modifiedString = "";
for (let i = 0; i < startPosition; i++)
modifiedString = modifiedString + inputString[i];
for (let i = startPosition; i < inputStringLength; i++)
modifiedString = modifiedString + reverseAlphabet[inputString[i].charCodeAt() - 'a'.charCodeAt()];
Example: In the code we will implement above approach by creating a string.
JavaScript
function reverseAlphabetFromPosition(
inputString, startPosition) {
let reverseAlphabet =
"zyxwvutsrqponmlkjihgfedcba";
let inputStringLength =
inputString.length;
let newString = "";
for (let i = 0; i < startPosition; i++)
newString += inputString[i];
for (let i = startPosition; i < inputStringLength; i++)
newString += reverseAlphabet[inputString[i].
charCodeAt() - 'a'.charCodeAt()];
return newString;
}
let givenString = "geeksforgeeks";
let startingPosition = 5;
console.log(
reverseAlphabetFromPosition(
givenString, startingPosition - 1));
Time Complexity: O(n)
Space Complexity: O(n)
Method 2: Using a for loop
- Initialize an empty string to store the mirrored result.
- Iterate through the characters of the given string using a loop.
- When the loop index is equal to or greater than the starting position, replace the current character with its mirror (e.g., 'a' becomes 'z' and 'b' becomes 'y').
- Append the mirrored character to the result string.
Syntax:
for (let i = 0; i < givenString.length; i++) {
// condition
}
Example: In the code we will implement above approach by using single for loop.
JavaScript
let givenString = "geeksforgeeks";
let startingPosition = 5;
let mirroredString = '';
for (let i = 0; i < givenString.length; i++) {
if (i >= startingPosition - 1) {
mirroredString +=
String.fromCharCode(219 - givenString.charCodeAt(i));
} else {
mirroredString += givenString[i];
}
}
console.log(mirroredString);
Time Complexity: O(n)
Space Complexity: O(n)
Method 3: Using Custom Mapping
- Create a character mapping to represent the mirror transformations.
- Initialize an empty string for the mirrored result.
- Iterate through the characters of the given string.
- If the character is in the mapping, replace it with the mapped character; otherwise, keep it as is.
Syntax:
const mirrorMap = {
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v',
'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q',
'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l',
'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b',
'z': 'a'
};
Example: In the code we will implement above approach by using map.
JavaScript
let givenString = "geeksforgeeks";
let startingPosition = 5;
const mirrorMap = {
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v',
'f': 'u', 'g': 't', 'h': 's', 'i': 'r', 'j': 'q',
'k': 'p', 'l': 'o', 'm': 'n', 'n': 'm', 'o': 'l',
'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g',
'u': 'f', 'v': 'e', 'w': 'd', 'x': 'c', 'y': 'b',
'z': 'a'
};
let mirroredString = '';
for (let char of givenString) {
startingPosition--;
if (startingPosition > 0) {
mirroredString += char;
}
else mirroredString += mirrorMap[char] || char;
}
console.log(mirroredString);
Time Complexity: O(n)
Space Complexity: O(n)
Method 4: Using Array.reduce() Method
Using the Array.reduce() method to mirror a string involves converting the string into an array of characters, then applying reduce to accumulate the characters in reverse order, effectively reversing the string.
Example: In this example The function mirrorString uses split('') and reduce() to reverse a string by accumulating characters in reverse order.
JavaScript
function mirrorString(str) {
return str.split('').reduce((reversed, char) => char + reversed, '');
}
console.log(mirrorString("Hello, World!"));
Method 5: Using Array.map() Method
In this method, we convert the string into an array of characters using split(''). Then, we use the map() method to iterate through each character. For characters after the specified starting position, we calculate their mirrored counterparts based on their ASCII values. Finally, we join the characters back into a string.
Example:
JavaScript
function mirrorStringFromPosition(inputString, startPosition) {
const startIdx = startPosition - 1;
const mirroredString = inputString
.split('')
.map((char, index) => {
if (index >= startIdx) {
// Calculate mirrored character based on ASCII values
const mirroredCharCode = 219 - char.charCodeAt();
return String.fromCharCode(mirroredCharCode);
}
return char;
})
.join('');
return mirroredString;
}
const givenString = "geeksforgeeks";
const startingPosition = 5;
console.log(mirrorStringFromPosition(givenString, startingPosition));
Time Complexity: O(n)
Space Complexity: O(n)
Method 6: Using Alphabet Calculation
In this approach we calculates the mirrored character by subtracting the character's position in the alphabet from the position of the last letter ('z' or 'Z').
Example:
JavaScript
function mirrorCharacters(str) {
const mirror = char => {
if (char >= 'a' && char <= 'z') {
return String.fromCharCode('a'.charCodeAt(0) +
('z'.charCodeAt(0) - char.charCodeAt(0)));
}
if (char >= 'A' && char <= 'Z') {
return String.fromCharCode('A'.charCodeAt(0) +
('Z'.charCodeAt(0) - char.charCodeAt(0)));
}
return char;
};
return str.split('').map(mirror).join('');
}
const input = "geeksforgeeks";
const result = mirrorCharacters(input);
console.log(result);
Method 7: Using ASCII Value Manipulation
In this approach, we directly manipulate the ASCII values of the characters to find their mirrored counterparts. This method involves calculating the mirrored character by subtracting the character's ASCII value from the ASCII value of 'z' and adding the ASCII value of 'a'. This approach ensures constant time complexity for each character transformation.
Example: This example demonstrates the use of the ASCII value manipulation approach to mirror characters in a string from a specified position.
JavaScript
function mirrorStringFromN(inputString, N) {
let result = '';
for (let i = 0; i < inputString.length; i++) {
if (i < N) {
result += inputString[i];
} else {
let mirroredChar = String.fromCharCode('a'.charCodeAt(0) + ('z'.charCodeAt(0) - inputString[i].charCodeAt(0)));
result += mirroredChar;
}
}
return result;
}
// Test cases
console.log(mirrorStringFromN('paradox', 3)); // Output: paizwlc
console.log(mirrorStringFromN('pneumonia', 6)); // Output: pnefnlmrz
Similar Reads
JavaScript Program to Swap Characters in a String
In this article, We'll explore different approaches, understand the underlying concepts of how to manipulate strings in JavaScript, and perform character swaps efficiently. There are different approaches for swapping characters in a String in JavaScript: Table of Content Using Array ManipulationUsin
6 min read
JavaScript Program to Access Individual Characters in a String
In this article, we are going to learn about accessing individual characters from the given string. Accessing individual characters in a string means retrieving a specific character from the string using its index position (zero-based) or iterating through each character one by one. Example: Input :
4 min read
JavaScript Program to FindNumber of Flips to make Binary String Alternate
In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern. Examples: I
4 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensu
3 min read
JavaScript Program to Check if a Given String is a Rotation of a Palindrome
In this article, we will see how to check a given string is a rotation of a palindrome. A palindrome is a string that remains the same when its characters are reversed (e.g., "racecar" is a palindrome). Example: Input: str = "racecar"Output: true // "racecar" is a rotation of a palindrome "racecar"I
6 min read
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements
In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elementsâ positions and printing the output in the console. Examples:Input: helloOutput: lelhoExplanation: h,l,l are consonants in the given st
6 min read
JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
We are given a matrix containing only lower-case alphabetical characters. The task is to print all the palindromic paths present in the given matrix. A path is a sequence of cells starting from the top-left cell and ending at the bottom-right cell. We are allowed to move only to the right and down f
4 min read
Java Program to Add Characters to a String
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
5 min read
Java Program to Replace Multiple Characters in a String
In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
3 min read
Java Program to Iterate Over Characters in String
Given string str of length N, the task is to traverse the string and print all the characters of the given string using java. Illustration: Input : str = âGeeksforGeeksâ Output : G e e k s f o r G e e k sInput : str = "GfG" Output : G f G Methods: Using for loops(Naive approach)Using iterators (Opti
3 min read