Open In App

Mirror characters of a string

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string and a number N, we need to mirror the characters from N-th position up to the length of the string in the alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on.

Examples: 

Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.

Input : N = 6
pneumonia
Output : pnefnlmrz

Below are different characters and their mirrors.

[Tex]a b c d e f g h i j k l m || n o p q r s t u v w x y z   [/Tex]

Mirroring the alphabetical order means that a corresponds to z, b corresponds to y. Which means that first character becomes the last and so on. Now, to achieve this we maintain a string(or a character array) which contains the English alphabets in lower case. Now from the pivot point up to the length, we can look up the reverse alphabetical order of a character by using its ASCII value as an index. Using the above technique, we transform the given string in the required one.

Implementation:

C++

// C++ code to find the reverse alphabetical // order from a given position #include <iostream> #include <string> using namespace std; // Function which take the given string // and the position from which the reversing shall // be done and returns the modified string string compute(string str, int n) { // Creating a string having reversed alphabetical order string reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; int l = str.length(); // The string up to the point specified in the question, // the string remains unchanged and from the point up to // the length of the string, we reverse the alphabetical // order for (int i = n; i < l; i++) str[i] = reverseAlphabet[str[i] - 'a']; return str; } // Driver function int main() { string str = "pneumonia"; int n = 4; string answer = compute(str, n - 1); cout << answer; return 0; }

Java

// Java code to find the reverse alphabetical // order from a given position import java.io.*; class GeeksforGeeks { // Function which take the given string // and the position from which the reversing shall // be done and returns the modified string static String compute(String str, int n) { // Creating a string having reversed alphabetical order String reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; int l = str.length(); // The string up to the point specified in the question, // the string remains unchanged and from the point up to // the length of the string, we reverse the alphabetical order String answer = ""; for (int i = 0; i < n; i++) answer = answer + str.charAt(i); for (int i = n; i < l; i++) answer = answer + reverseAlphabet.charAt(str.charAt(i) - 'a'); return answer; } // Driver function public static void main(String args[]) { String str = "pneumonia"; int n = 4; System.out.print(compute(str, n - 1)); } }

Python

# python code to find the reverse # alphabetical order from a given # position # Function which take the given string and the # position from which the reversing shall be # done and returns the modified string def compute(st, n): # Creating a string having reversed # alphabetical order reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba" l = len(st) # The string up to the point specified in the # question, the string remains unchanged and # from the point up to the length of the # string, we reverse the alphabetical order answer = "" for i in range(0, n): answer = answer + st[i]; for i in range(n, l): answer = (answer + reverseAlphabet[ord(st[i]) - ord('a')]); return answer; # Driver function st = "pneumonia" n = 4 answer = compute(st, n - 1) print(answer) # This code is contributed by Sam007.

C#

// C# code to find the reverse alphabetical // order from a given position using System; class GFG { // Function which take the given string // and the position from which the // reversing shall be done and returns // the modified string static String compute(string str, int n) { // Creating a string having reversed // alphabetical order string reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; int l = str.Length; // The string up to the point // specified in the question, // the string remains unchanged // and from the point up to // the length of the string, we // reverse the alphabetical order String answer = ""; for (int i = 0; i < n; i++) answer = answer + str[i]; for (int i = n; i < l; i++) answer = answer + reverseAlphabet[str[i]- 'a']; return answer; } // Driver function public static void Main() { string str = "pneumonia"; int n = 4; Console.Write(compute(str, n - 1)); } } // This code is contributed by Sam007.

Javascript

<script> // Javascript code to find the reverse alphabetical // order from a given position // Function which take the given string // and the position from which the // reversing shall be done and returns // the modified string function compute(str, n) { // Creating a string having reversed // alphabetical order let reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; let l = str.length; // The string up to the point // specified in the question, // the string remains unchanged // and from the point up to // the length of the string, we // reverse the alphabetical order let answer = ""; for (let i = 0; i < n; i++) answer = answer + str[i]; for (let i = n; i < l; i++) answer = answer + reverseAlphabet[str[i].charCodeAt()- 'a'.charCodeAt()]; return answer; } let str = "pneumonia"; let n = 4; document.write(compute(str, n - 1)); </script>

php

<?php // php code to find the reverse alphabetical // order from a given position // Function which take the given string // and the position from which the reversing // shall be done and returns the modified // string function compute($str, $n) { // Creating a string having reversed // alphabetical order $reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; $l = strlen($str); // The string up to the point // specified in the question, // the string remains unchanged // and from the point up to // the length of the string, we // reverse the alphabetical order $answer = ""; for ($i = 0; $i < $n; $i++) $answer = $answer.$str[$i]; for ($i = $n; $i < $l; $i++){ $answer = $answer.$reverseAlphabet[ ord($str[$i])- ord('a')]; } return $answer; } // Driver function $str = "pneumonia"; $n = 4; $answer = compute($str, $n - 1); echo $answer; // This code is contributed by Sam007 ?>


Output

pnefnlmrz

Time Complexity: O(n), where n represents the size of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Using Mapping:

Follow the below steps:

  • Firslty, mirror_characters() function takes a string and returns a number N.
  • The first step is to map the characters to the mirrored characters using dictionary comprehension.
  • The second step is to iterate over the characters in the string, starting from position N, and constructing the resulting string.
  • The final step is to return the mirrored string.

Below is the implementation of the above approach:

C++

#include <iostream> #include <string> #include <unordered_map> std::string mirrorCharacters(const std::string& str, int N) { // Create a mapping of characters to their mirrored // counterparts std::unordered_map<char, char> mapping; for (int i = 97; i < 123; i++) { mapping[static_cast<char>(i)] = static_cast<char>(219 - i); } // Initialize the result string std::string result; // Iterate over the characters of the string for (size_t i = 0; i < str.length(); i++) { char currentChar = str[i]; if (i >= N - 1) { // Mirror the character if its position is equal // to or greater than N char mirroredChar = mapping.count(currentChar) ? mapping[currentChar] : currentChar; result += mirroredChar; } else { result += currentChar; } } return result; } int main() { int N = 3; std::string string1 = "paradox"; std::cout << mirrorCharacters(string1, N) << std::endl; return 0; }

Java

import java.util.HashMap; import java.util.Map; public class MirrorCharacters { public static String mirrorCharacters(String string, int N) { // Create a mapping of characters to their mirrored // counterparts Map<Character, Character> mapping = new HashMap<>(); for (int i = 97; i < 123; i++) { mapping.put((char)i, (char)(219 - i)); } // Initialize the result string StringBuilder result = new StringBuilder(); // Iterate over the characters of the string for (int i = 0; i < string.length(); i++) { char currentChar = string.charAt(i); if (i >= N - 1) { // Mirror the character if its position is // equal to or greater than N char mirroredChar = mapping.getOrDefault( currentChar, currentChar); result.append(mirroredChar); } else { result.append(currentChar); } } return result.toString(); } public static void main(String[] args) { int N = 3; String string1 = "paradox"; System.out.println(mirrorCharacters(string1, N)); } }

Python

def mirror_characters(string, N): # Create a mapping of characters to their mirrored counterparts mapping = {chr(i): chr(219 - i) for i in range(97, 123)} # Initialize the result string result = "" # Iterate over the characters of the string for i, char in enumerate(string): if i >= N - 1: # Mirror the character if its position is equal to or greater than N mirrored_char = mapping.get(char, char) result += mirrored_char else: result += char return result # Example usage: N = 3 string1 = "paradox" print(mirror_characters(string1, N))

JavaScript

function mirrorCharacters(string, N) { // Create a mapping of characters to their mirrored counterparts const mapping = {}; for (let i = 97; i < 123; i++) { mapping[String.fromCharCode(i)] = String.fromCharCode(219 - i); } // Initialize the result string let result = ''; // Iterate over the characters of the string for (let i = 0; i < string.length; i++) { const currentChar = string.charAt(i); if (i >= N - 1) { // Mirror the character if its position is equal to or greater than N const mirroredChar = mapping[currentChar] || currentChar; result += mirroredChar; } else { result += currentChar; } } return result; } const N = 3; const string1 = 'paradox'; console.log(mirrorCharacters(string1, N)); // This code is contributed by shivamgupta0987654321


Output

paizwlc

Time complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Check if a number is prime in Flipped Upside Down, Mirror Flipped and Mirror Flipped Upside Down
Given an integer N, the task is to check if N is a prime number in Flipped Down, Mirror Flipped and Mirror Flipped Down forms of the given number.Examples: Input: N = 120121 Output: YesExplanation: Flipped forms of the number:Flipped Upside Down - 151051Mirror Flipped - 121021Mirror Upside Down - 150151Since 1510151 and 121021 are both prime number
6 min read
Python Dictionary to find mirror characters in a string
Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We hav
2 min read
Check if the given string is the same as its reflection in a mirror
Given a string S containing only uppercase English characters. The task is to find whether S is the same as its reflection in a mirror.Examples: Input: str = "AMA" Output: YES AMA is same as its reflection in the mirror. Input: str = "ZXZ" Output: NO Approach: The string obviously has to be a palindrome, but that alone is not enough. All characters
5 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Check if a string can be made palindromic by swapping pairs of characters from indices having unequal characters in a Binary String
Given a string S and a binary string B, both of length N, the task is to check if the given string S can be made palindromic by repeatedly swapping characters at any pair of indices consisting of unequal characters in the string B. Examples: Input: S = "BAA", B = "100"Output: YesExplanation:Swapping S[0] and S[1] modifies S to "ABA" and B to "010".
17 min read
Mirror of n-ary Tree
Given a Tree where every node contains variable number of children, convert the tree to its mirror. Below diagram shows an example. We strongly recommend you to minimize your browser and try this yourself first. Node of tree is represented as a key and a variable sized array of children pointers. The idea is similar to mirror of Binary Tree. For ev
9 min read
Mirror of matrix across diagonal
Given a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a matrix layout. Examples: Input : int mat[][] = {{1 2
14 min read
Python Program for focal length of a spherical mirror
Focal length is the distance between the center of the mirror to the principal foci. In order to determine the focal length of a spherical mirror we should know the radius of curvature of that mirror. The distance from the vertex to the center of curvature is called radius of curvature. The focal length is half the radius of curvature. Formula : F
2 min read
Program for triangular pattern (mirror image around 0)
Given the value of n, print the pattern.Examples : Input : n = 5 Output : 0 101 21012 3210123 432101234 Input : n = 7 Output : 0 101 21012 3210123 432101234 54321012345 6543210123456 Below is the program to print the above pattern C/C++ Code // C++ Implementation to print the pattern #include &lt;bits/stdc++.h&gt; using namespace std; // Function d
5 min read
Article Tags :
Practice Tags :