# Encode given string by shifting each character forward with its alphabetical value

In this problem, we need to calculate the distance between the character and 'a', and by adding it to the character, we need to shift the character.

The solution approach is to find the difference between the ASCII values of both characters, and add it to the current character's ASCII value.

Problem statement - We have given an alpha string of length N containing only alphabetical characters. We need to encode the string according to the below conditions.

• Take a distance between the current character and 'a'.

• Shift the character in the clockwise direction by distance. Also, consider the circular shift.

## Sample examples

Input

alpha = "abcd"


Output

'aceg'

Explanation

• The difference between 'a' and 'a' is 0. So, we need to make 0 shifts.

• The difference between 'a' and 'b' is 1. So, we get a 'c' when we shift it by 1.

• The distance between 'a' and 'c' is 2. So, we get 'e' when we shift 'c' by 2.

• The distance between 'a' and 'd' is 3. So, we get 'g' when we shift 'd' by 3.

Input

alpha = "tutorialspoint";


Output

'momciqawkecqam'

Explanation - We calculated the character difference for each character and shifted them by difference.

Input

alpha = "aaaa"


Output

"aaaa"


Explanation - The difference between 'a' and 'a' is 0. So the output string is the same as the input string.

## Approach 1

This approach will take the difference between 'a' and character. If the sum of the current character value and difference is greater than or equal to 26, we will take modulo of sum to perform the circular shift.

### Algorithm

Step 1 - Start traversing the given string using the for loop.

Step 2 - In the 'diff' integer variable, store the ch - 'a', which is the distance between the character and 'a'.

Step 3 - If 2*diff is greater than or equal to 26, take the modulo of 2 * diff with 26.

Step 4 - Add the 'diff' to the 'a' and store it into the 'ch' character.

Step 5 - If 2*diff is less than 26, add diff to the 'ch'.

Step 6 - Print the alpha string.

### Example

#include <bits/stdc++.h>
using namespace std;

for (auto &ch : alpha) {
int diff = ch - 'a';
// If character + difference becomes greater than 'z'
if (diff * 2 >= 26) {
// Take modulus with 26
diff = (diff * 2) % 26;
ch = 'a' + diff;
}
// If 'z' is not exceeded
else {
// Add difference to the current character
ch = ch + diff;
}
}
cout << "The encoded string is - " << alpha << endl;
}
int main() {
string alpha = "abcd";
return 0;
}


### Output

The encoded string is - aceg


Time complexity - O(N), where N is the string length.

Space complexity - O(1) as we update the original string without using extra space.

We learned to encode the given string by performing the circular shift of the character by adding the distance to the character. Programmers can write the code to decrypt the encoded string for more practice of the problem given above.

Updated on: 24-Aug-2023

45 Views 