VOOZH about

URL: https://www.geeksforgeeks.org/dsa/encode-given-string-by-shifting-each-character-forward-with-its-alphabetical-value/

⇱ Encode given string by shifting each character forward with its alphabetical value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 27 Jun, 2023

Given string str of size N consisting of lowercase English alphabets, the task is to encode the given string as follows:

  • change every character of that string to another character
  • the distance between the changed character and the current character is the same as the distance between the current character and 'a'.
  • Also, assume that the character's array forms a cycle, i.e. after 'z' the cycle starts again from 'a'.

Examples:

Input: str = "geeksforgeeks"
Output: "miiukkcimiiuk"
Explanation:
g changed to m (distance between g & a is 6, distance between m & g is 6)
e changed to i (distance between e & a is 4, distance between i & e is 4)
and same for other characters as well.

Input: str = "cycleofalphabet"
Output: "ewewickaweoacim"

Approach: This problem can be solved using the following steps:

  • Run a loop from i=0 to i<N and traverse each character of the string. For each character str[i]:
    • Find the distance between str[i] and 'a', i.e. dist=str[i]-'a'.
    • Now, if (dist+(str[i]-'a')) > 26, this means that 'z' is exceeded, so
  • Otherwise, change str[i] to str[i]+dist.
  • Print the string as the answer to this problem.

Below is the implementation of the above approach:

 
 


Output
ewewickaweoacim


 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment
Article Tags: