# Decrypt a string according to given rules

Given encrypted string str, the task is to decrypt the given string when the encryption rules are as follows:

2. In every odd step, append the next character to it.
3. In every even step, prepend the next character to the encrypted string so far.

For example, if str = “geeks” then the encrypted string will be,
g -> ge -> ege -> egek -> segek

Examples:

Input: str = “segosegekfrek”
Output: geeksforgeeks

Input: str = “vrstie”
Output: strive

Approach: The steps that are given to encrypt the string can be followed in reverse order to obtain the original string. There will be two conditions to obtain the original string:

• If the string is of odd length, in the odd step add the characters from the back in the resultant string, else add from the front.
• If the string is of even length, in the odd step add characters from the front and add characters from the back in the even step.

The reverse of the resultant string thus obtained is the original string which was encrypted.

Below is the implementation of the above approach:

## C++

 `// C++ program to decrypt the original string` `#include ` `using` `namespace` `std;`   `// Function to return the original string ` `// after decryption` `string decrypt(string s, ``int` `l)` `{` `    ``// Stores the decrypted string` `    ``string ans = ``""``;`   `    ``// If length is odd` `    ``if` `(l % 2) {`   `        ``// Step counter` `        ``int` `cnt = 0;`   `        ``// Starting and ending index` `        ``int` `indl = 0, indr = l - 1;`   `        ``// Iterate till all characters ` `        ``// are decrypted` `        ``while` `(ans.size() != l) {`   `            ``// Even step` `            ``if` `(cnt % 2 == 0)` `                ``ans += s[indl++];`   `            ``// Odd step` `            ``else` `                ``ans += s[indr--];`   `            ``cnt++;` `        ``}` `    ``}`   `    ``// If length is even` `    ``else` `{`   `        ``// Step counter` `        ``int` `cnt = 0;`   `        ``// Starting and ending index` `        ``int` `indl = 0, indr = l - 1;` `        ``while` `(ans.size() != l) {`   `            ``// Even step` `            ``if` `(cnt % 2 == 0)` `                ``ans += s[indr--];`   `            ``// Odd step` `            ``else` `                ``ans += s[indl++];`   `            ``cnt++;` `        ``}` `    ``}`   `    ``// Reverse the decrypted string` `    ``reverse(ans.begin(), ans.end());`   `    ``return` `ans;` `}`   `// Driver Code` `int` `main()` `{` `    ``string s = ``"segosegekfrek"``;` `    ``int` `l = s.length();` `    ``cout << decrypt(s, l);`   `    ``return` `0;` `}`

## Java

 `// Java program to decrypt the original string` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG ` `{`   `  ``// Function to return the original string ` `  ``// after decryption` `  ``public` `static` `String decrypt(String s, ``int` `l)` `  ``{` `    `  `    ``// Stores the decrypted string` `    ``String ans = ``""``;`   `    ``// If length is odd` `    ``if` `(l % ``2` `== ``1``)` `    ``{`   `      ``// Step counter` `      ``int` `cnt = ``0``;`   `      ``// Starting and ending index` `      ``int` `indl = ``0``, indr = l - ``1``;`   `      ``// Iterate till all characters ` `      ``// are decrypted` `      ``while` `(ans.length() != l) ` `      ``{`   `        ``// Even step` `        ``if` `(cnt % ``2` `== ``0``)` `          ``ans += s.charAt(indl++);`   `        ``// Odd step` `        ``else` `          ``ans += s.charAt(indr--);` `        ``cnt++;` `      ``}` `    ``}`   `    ``// If length is even` `    ``else` `    ``{`   `      ``// Step counter` `      ``int` `cnt = ``0``;`   `      ``// Starting and ending index` `      ``int` `indl = ``0``, indr = l - ``1``;` `      ``while` `(ans.length() != l) ` `      ``{`   `        ``// Even step` `        ``if` `(cnt % ``2` `== ``0``)` `          ``ans += s.charAt(indr--);`   `        ``// Odd step` `        ``else` `          ``ans += s.charAt(indl++);`   `        ``cnt++;` `      ``}` `    ``}`   `    ``// Reverse the decrypted string` `    ``StringBuffer sbr = ``new` `StringBuffer(ans);` `    ``sbr.reverse();` `    ``return` `sbr.toString();` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `main (String[] args) ` `  ``{` `    ``String s = ``"segosegekfrek"``;` `    ``int` `l = s.length();` `    ``System.out.println(decrypt(s, l));` `  ``}` `}`   `// This Code is contributed by Manu Pathria`

## Python3

 `# Python3 program to decrypt ` `# the original string`   `# Function to return the ` `# original string after ` `# decryption` `def` `decrypt(s, l):`   `    ``# Stores the decrypted ` `    ``# string` `    ``ans ``=` `""`   `    ``# If length is odd` `    ``if` `(l ``%` `2``):`   `        ``# Step counter` `        ``cnt ``=` `0`   `        ``# Starting and ending ` `        ``# index` `        ``indl ``=` `0` `        ``indr ``=` `l ``-` `1`   `        ``# Iterate till all ` `        ``# characters are decrypted` `        ``while` `(``len``(ans) !``=` `l):`   `            ``# Even step` `            ``if` `(cnt ``%` `2` `=``=` `0``):` `                ``ans ``+``=` `s[indl]` `                ``indl ``+``=` `1`   `            ``# Odd step` `            ``else``:` `                ``ans ``+``=` `s[indr]` `                ``indr ``-``=` `1`   `            ``cnt ``+``=` `1`   `    ``# If length is even` `    ``else``:`   `        ``# Step counter` `        ``cnt ``=` `0`   `        ``# Starting and ending ` `        ``# index` `        ``indl ``=` `0` `        ``indr ``=` `l ``-` `1` `        ``while` `(``len``(ans) !``=` `l):`   `            ``# Even step` `            ``if` `(cnt ``%` `2` `=``=` `0``):` `                ``ans ``+``=` `s[indr]` `                ``indr ``-``=` `1`   `            ``# Odd step` `            ``else``:` `                ``ans ``+``=` `s[indl]` `                ``indl ``+``=` `1`   `            ``cnt ``+``=` `1`   `    ``# Reverse the decrypted ` `    ``# string` `    ``string ``=` `list``(ans)` `    ``string.reverse()` `    ``ans ``=` `''.join(string)`   `    ``return` `ans`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``s ``=` `"segosegekfrek"` `    ``l ``=` `len``(s)` `    ``print``(decrypt(s, l))`   `# This code is contributed by Chitranayal`

## C#

 `// C# program to decrypt the original string` `using` `System;` `using` `System.Collections;` `using` `System.Collections.Generic;`   `class` `GFG ` `{`   `  ``// Function to return the original string ` `  ``// after decryption` `  ``static` `string` `decrypt(``string` `s, ``int` `l)` `  ``{`   `    ``// Stores the decrypted string` `    ``string` `ans = ``""``;`   `    ``// If length is odd` `    ``if` `(l % 2 == 1)` `    ``{`   `      ``// Step counter` `      ``int` `cnt = 0;`   `      ``// Starting and ending index` `      ``int` `indl = 0, indr = l - 1;`   `      ``// Iterate till all characters ` `      ``// are decrypted` `      ``while` `(ans.Length != l) ` `      ``{`   `        ``// Even step` `        ``if` `(cnt % 2 == 0)` `          ``ans += s[indl++];`   `        ``// Odd step` `        ``else` `          ``ans += s[indr--];` `        ``cnt++;` `      ``}` `    ``}`   `    ``// If length is even` `    ``else` `    ``{`   `      ``// Step counter` `      ``int` `cnt = 0;`   `      ``// Starting and ending index` `      ``int` `indl = 0, indr = l - 1;` `      ``while` `(ans.Length != l) ` `      ``{`   `        ``// Even step` `        ``if` `(cnt % 2 == 0)` `          ``ans += s[indr--];`   `        ``// Odd step` `        ``else` `          ``ans += s[indl++];`   `        ``cnt++;` `      ``}` `    ``}`   `    ``// Reverse the decrypted string` `    ``//Array.Reverse(ans);` `    ``char``[] sbr = ans.ToCharArray();` `    ``Array.Reverse(sbr);`   `    ``return` `new` `string``(sbr);` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `Main () ` `  ``{` `    ``string` `s = ``"segosegekfrek"``;` `    ``int` `l = s.Length;` `    ``Console.Write(decrypt(s, l));` `  ``}` `}`   `// This Code is contributed by Samim Hossain Mondal.`

## Javascript

 ``

Output

```geeksforgeeks

```

Complexity Analysis:

• Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
• Auxiliary Space: O(N), as we are using extra space for the string. Where N is the length of the string.

Below is Python’s implementation.

## C++

 `#include ` `using` `namespace` `std;`   `// Function for encryption` `string encrypted_string(string strg)` `{` `    ``string EncryptedString = { strg[0] };` `    ``for` `(``int` `t = 1; t < strg.length(); t++) {` `        ``if` `(t % 2 == 1) {` `            ``EncryptedString.push_back(` `                ``strg[t]); ``// At odd position, append the` `                          ``// next character` `        ``}` `        ``else` `{` `            ``EncryptedString.insert(` `                ``0, 1, strg[t]); ``// At Even position, prepend` `                                ``// the next character` `        ``}` `    ``}` `    ``// print the resultant string` `    ``return` `EncryptedString;` `}`   `// Function for decryption` `string decrypted_string(string strg)` `{` `    ``// Check the divisibility of length of string by 2` `    ``if` `(strg.length() % 2 != 0) {` `        ``string DecryptedString = { strg[0] };` `        ``for` `(``int` `t = 1; t < strg.length(); t++) {` `            ``DecryptedString.push_back(` `                ``strg[strg.length() - 1` `                     ``- t]); ``// First add the characters from` `                            ``// the back` `            ``DecryptedString.push_back(` `                ``strg[t]); ``// from the front` `        ``}` `        ``reverse(` `            ``DecryptedString.begin(),` `            ``DecryptedString.end()); ``// Reverse the final` `                                    ``// string to get output` `        ``return` `DecryptedString;` `    ``}` `    ``else` `{` `        ``string reverse_strg = strg;` `        ``reverse(` `            ``reverse_strg.begin(),` `            ``reverse_strg` `                ``.end()); ``// In case of even length, reverse` `                         ``// the given string first` `        ``string DecryptedString = { reverse_strg[0] };`   `        ``// Looping over the reversed string` `        ``for` `(``int` `t = 1; t < reverse_strg.length(); t++) {` `            ``DecryptedString.push_back(` `                ``reverse_strg[reverse_strg.length() - 1` `                             ``- t]); ``// First add the` `                                    ``// characters from the` `                                    ``// back` `            ``DecryptedString.push_back(` `                ``reverse_strg[t]); ``// and then from the front` `        ``}` `        ``reverse(` `            ``DecryptedString.begin(),` `            ``DecryptedString.end()); ``// Reverse the final` `                                    ``// string to get output` `        ``return` `DecryptedString;` `    ``}` `}`   `// Testing the algorithm with Driver Code` `int` `main()` `{` `    ``cout << encrypted_string(``"geeks"``) << endl;` `    ``cout << encrypted_string(``"geeksforgeeks"``) << endl;` `    ``cout << encrypted_string(``"strive"``) << endl;` `    ``cout << encrypted_string(``"vikaschitturi"``) << endl;` `    ``cout << encrypted_string(``"padmachitturi"``) << endl;` `    ``cout << encrypted_string(``"hackerrank"``) << endl;` `    ``cout << encrypted_string(``"hackerearth"``) << endl;` `    ``cout << encrypted_string(``"codechef"``) << endl;` `    ``cout << encrypted_string(``"IamVikas"``) << endl;` `    ``cout << encrypted_string(``"HelloHowareyou"``) << endl;` `    ``cout << encrypted_string(``"whatareyoudoing"``) << endl;`   `    ``cout << decrypted_string(``"segek"``) << endl;` `    ``cout << decrypted_string(``"segosegekfrek"``) << endl;` `    ``cout << decrypted_string(``"vrstie"``) << endl;` `    ``cout << decrypted_string(``"iuthskviacitr"``) << endl;` `    ``cout << decrypted_string(``"iuthadpamcitr"``) << endl;` `    ``cout << decrypted_string(``"nrechakrak"``) << endl;` `    ``cout << decrypted_string(``"hreechakrat"``) << endl;` `    ``cout << decrypted_string(encrypted_string(``"IamVikas"``))` `         ``<< endl;` `    ``cout << decrypted_string(` `        ``encrypted_string(``"HelloHowareyou"``))` `         ``<< endl;`   `    ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `public` `class` `GFG {` `    ``// Function for encryption` `    ``public` `static` `String encryptedString(String str) {` `        ``StringBuilder encryptedString = ``new` `StringBuilder();` `        ``encryptedString.append(str.charAt(``0``));`   `        ``for` `(``int` `t = ``1``; t < str.length(); t++) {` `            ``if` `(t % ``2` `== ``1``) {` `                ``encryptedString.append(str.charAt(t));` `            ``} ``else` `{` `                ``encryptedString.insert(``0``, str.charAt(t));` `            ``}` `        ``}`   `        ``return` `encryptedString.toString();` `    ``}`   `    ``// Function for decryption` `    ``public` `static` `String decryptedString(String str) {` `        ``if` `(str.length() % ``2` `!= ``0``) {` `            ``StringBuilder decryptedString = ``new` `StringBuilder();` `            ``decryptedString.append(str.charAt(``0``));`   `            ``for` `(``int` `t = ``1``; t < str.length(); t++) {` `                ``decryptedString.append(str.charAt(str.length() - ``1` `- t));` `                ``decryptedString.append(str.charAt(t));` `            ``}`   `            ``return` `decryptedString.reverse().toString();` `        ``} ``else` `{` `            ``StringBuilder reverseStr = ``new` `StringBuilder(str).reverse();` `            ``StringBuilder decryptedString = ``new` `StringBuilder();` `            ``decryptedString.append(reverseStr.charAt(``0``));`   `            ``for` `(``int` `t = ``1``; t < reverseStr.length(); t++) {` `                ``decryptedString.append(reverseStr.charAt(reverseStr.length() - ``1` `- t));` `                ``decryptedString.append(reverseStr.charAt(t));` `            ``}`   `            ``return` `decryptedString.reverse().toString();` `        ``}` `    ``}`   `    ``// Testing the algorithm with Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``System.out.println(encryptedString(``"geeks"``));` `        ``System.out.println(encryptedString(``"geeksforgeeks"``));` `        ``System.out.println(encryptedString(``"strive"``));` `        ``System.out.println(encryptedString(``"vikaschitturi"``));` `        ``System.out.println(encryptedString(``"padmachitturi"``));` `        ``System.out.println(encryptedString(``"hackerrank"``));` `        ``System.out.println(encryptedString(``"hackerearth"``));` `        ``System.out.println(encryptedString(``"codechef"``));` `        ``System.out.println(encryptedString(``"IamVikas"``));` `        ``System.out.println(encryptedString(``"HelloHowareyou"``));` `        ``System.out.println(encryptedString(``"whatareyoudoing"``));`   `        ``System.out.println(decryptedString(``"segek"``));` `        ``System.out.println(decryptedString(``"segosegekfrek"``));` `        ``System.out.println(decryptedString(``"vrstie"``));` `        ``System.out.println(decryptedString(``"iuthskviacitr"``));` `        ``System.out.println(decryptedString(``"iuthadpamcitr"``));` `        ``System.out.println(decryptedString(``"nrechakrak"``));` `        ``System.out.println(decryptedString(``"hreechakrat"``));` `        ``System.out.println(decryptedString(encryptedString(``"IamVikas"``)));` `        ``System.out.println(decryptedString(encryptedString(``"HelloHowareyou"``)));` `    ``}` `}`

## Python3

 `#Python 3 Code for encrypting a string according to given rules` `#Function for encryption` `def` `encrypted_string(strg):` `    ``EncryptedString ``=` `[strg[``0``]]` `    ``for` `t ``in` `range``(``1``,``len``(strg)):` `        ``if` `(t``%``2` `=``=` `1``):` `            ``EncryptedString.append(strg[t]) ``#At odd position, append the next character` `        ``else``:` `            ``EncryptedString.insert(``0``,strg[t]) ``#At Even position, prepend the next character ` `    ``#print the resultant string` `    ``return` `(''.join(EncryptedString))`     `#Python 3 Code for decrypting a string (Answer to the actual question)` `def` `decrypted_string(strg):` `    ``#CHeck the divisibility of length of string by 2` `    ``if` `(``len``(strg)``%``2``!``=``0``):` `        ``DecryptedString ``=` `[strg[``0``]]` `        ``for` `t ``in` `range``(``1``,``len``(strg)):` `            ``DecryptedString.append(strg[``-``1``*``t]) ``#First add the characters from the back` `            ``DecryptedString.append(strg[t]) ``#from the front` `        ``DecryptedString ``=` `DecryptedString[:``len``(strg)][::``-``1``] ``#Reverse the final string to get output` `        ``return` `(''.join(DecryptedString))` `    ``else``:` `        ``reverse_strg ``=` `strg[::``-``1``] ``#In case of even length, reverse the given string first ` `        ``DecryptedString``=``[reverse_strg[``0``]]`   `        ``#Looping over the reversed string` `        ``for` `t ``in` `range``(``1``,``len``(reverse_strg)):` `            ``DecryptedString.append(reverse_strg[``-``1``*``t]) ``#First add the characters from the back` `            ``DecryptedString.append(reverse_strg[t]) ``#and then from the front` `        ``DecryptedString ``=` `DecryptedString[:``len``(reverse_strg)][::``-``1``]` `        ``return` `(''.join(DecryptedString))` `    `  `    `  `#Testing the algorithm with Driver Code` `if` `__name__``=``=` `'__main__'``:` `    `  `    ``print` `(encrypted_string(``'geeks'``))` `    ``print` `(encrypted_string(``'geeksforgeeks'``))` `    ``print` `(encrypted_string(``'strive'``))` `    ``print` `(encrypted_string(``'vikaschitturi'``))` `    ``print` `(encrypted_string(``'padmachitturi'``))` `    ``print` `(encrypted_string(``'hackerrank'``))` `    ``print` `(encrypted_string(``'hackerearth'``))` `    ``print` `(encrypted_string(``'codechef'``))` `    ``print` `(encrypted_string(``'IamVikas'``))` `    ``print` `(encrypted_string(``'HelloHowareyou'``))` `    ``print` `(encrypted_string(``'whatareyoudoing'``))`   `    ``print``(decrypted_string(``'segek'``))` `    ``print``(decrypted_string(``'segosegekfrek'``))` `    ``print``(decrypted_string(``'vrstie'``))` `    ``print``(decrypted_string(``'iuthskviacitr'``))` `    ``print``(decrypted_string(``'iuthadpamcitr'``))` `    ``print``(decrypted_string(``'nrechakrak'``))` `    ``print``(decrypted_string(``'hreechakrat'``))` `    ``print``(decrypted_string(encrypted_string(``'IamVikas'``)))` `    ``print``(decrypted_string(encrypted_string(``'HelloHowareyou'``)))` `    ``print``(decrypted_string(encrypted_string(``'whatareyoudoing'``)))`

## C#

 `using` `System;` `using` `System.Text;`   `class` `Program` `{` `    ``// Function for encryption` `    ``static` `string` `EncryptedString(``string` `str)` `    ``{` `        ``StringBuilder encryptedString = ``new` `StringBuilder(str[0].ToString());`   `        ``for` `(``int` `i = 1; i < str.Length; i++)` `        ``{` `            ``if` `(i % 2 == 1)` `            ``{` `                ``encryptedString.Append(str[i]); ``// At odd position, append the next character` `            ``}` `            ``else` `            ``{` `                ``encryptedString.Insert(0, str[i].ToString()); ``// At even position, prepend the next character` `            ``}` `        ``}`   `        ``return` `encryptedString.ToString();` `    ``}`   `    ``// Function for decryption` `    ``static` `string` `DecryptedString(``string` `str)` `    ``{` `        ``if` `(str.Length % 2 != 0)` `        ``{` `            ``StringBuilder decryptedString = ``new` `StringBuilder(str[0].ToString());`   `            ``for` `(``int` `i = 1; i < str.Length; i++)` `            ``{` `                ``decryptedString.Append(str[str.Length - 1 - i]); ``// First add the characters from the back` `                ``decryptedString.Append(str[i]); ``// from the front` `            ``}`   `            ``char``[] charArray = decryptedString.ToString().ToCharArray();` `            ``Array.Reverse(charArray);` `            ``return` `new` `string``(charArray);` `        ``}` `        ``else` `        ``{` `            ``string` `reverseStr = ``new` `string``(str.ToCharArray());` `            ``Array.Reverse(reverseStr.ToCharArray());`   `            ``StringBuilder decryptedString = ``new` `StringBuilder(reverseStr[0].ToString());`   `            ``for` `(``int` `i = 1; i < reverseStr.Length; i++)` `            ``{` `                ``decryptedString.Append(reverseStr[reverseStr.Length - 1 - i]); ``// First add the characters from the back` `                ``decryptedString.Append(reverseStr[i]); ``// and then from the front` `            ``}`   `            ``char``[] charArray = decryptedString.ToString().ToCharArray();` `            ``Array.Reverse(charArray);` `            ``return` `new` `string``(charArray);` `        ``}` `    ``}`   `    ``static` `void` `Main()` `    ``{` `        ``Console.WriteLine(EncryptedString(``"geeks"``));` `        ``Console.WriteLine(EncryptedString(``"geeksforgeeks"``));` `        ``Console.WriteLine(EncryptedString(``"strive"``));` `        ``Console.WriteLine(EncryptedString(``"vikaschitturi"``));` `        ``Console.WriteLine(EncryptedString(``"padmachitturi"``));` `        ``Console.WriteLine(EncryptedString(``"hackerrank"``));` `        ``Console.WriteLine(EncryptedString(``"hackerearth"``));` `        ``Console.WriteLine(EncryptedString(``"codechef"``));` `        ``Console.WriteLine(EncryptedString(``"IamVikas"``));` `        ``Console.WriteLine(EncryptedString(``"HelloHowareyou"``));` `        ``Console.WriteLine(EncryptedString(``"whatareyoudoing"``));`   `        ``Console.WriteLine(DecryptedString(``"segek"``));` `        ``Console.WriteLine(DecryptedString(``"segosegekfrek"``));` `        ``Console.WriteLine(DecryptedString(``"vrstie"``));` `        ``Console.WriteLine(DecryptedString(``"iuthskviacitr"``));` `        ``Console.WriteLine(DecryptedString(``"iuthadpamcitr"``));` `        ``Console.WriteLine(DecryptedString(``"nrechakrak"``));` `        ``Console.WriteLine(DecryptedString(``"hreechakrat"``));` `        ``Console.WriteLine(DecryptedString(EncryptedString(``"IamVikas"``)));` `        ``Console.WriteLine(DecryptedString(EncryptedString(``"HelloHowareyou"``)));` `    ``}` `}`

## Javascript

 `// Function for encryption` `function` `encryptedString(strg) {` `    ``let encryptedString = strg[0];`   `    ``for` `(let t = 1; t < strg.length; t++) {` `        ``if` `(t % 2 === 1) {` `            ``encryptedString += strg[t];` `        ``} ``else` `{` `            ``encryptedString = strg[t] + encryptedString;` `        ``}` `    ``}`   `    ``return` `encryptedString;` `}`   `// Function for decryption` `function` `decryptedString(strg) {` `    ``if` `(strg.length % 2 !== 0) {` `        ``let decryptedString = strg[0];`   `        ``for` `(let t = 1; t < strg.length; t++) {` `            ``decryptedString += strg[strg.length - 1 - t];` `            ``decryptedString += strg[t];` `        ``}`   `        ``return` `decryptedString.split(``''``).reverse().join(``''``);` `    ``} ``else` `{` `        ``let reverseStrg = strg.split(``''``).reverse().join(``''``);` `        ``let decryptedString = reverseStrg[0];`   `        ``for` `(let t = 1; t < reverseStrg.length; t++) {` `            ``decryptedString += reverseStrg[reverseStrg.length - 1 - t];` `            ``decryptedString += reverseStrg[t];` `        ``}`   `        ``return` `decryptedString.split(``''``).reverse().join(``''``);` `    ``}` `}`   `// Testing the algorithm with Driver Code` `console.log(encryptedString(``"geeks"``));` `console.log(encryptedString(``"geeksforgeeks"``));` `console.log(encryptedString(``"strive"``));` `console.log(encryptedString(``"vikaschitturi"``));` `console.log(encryptedString(``"padmachitturi"``));` `console.log(encryptedString(``"hackerrank"``));` `console.log(encryptedString(``"hackerearth"``));` `console.log(encryptedString(``"codechef"``));` `console.log(encryptedString(``"IamVikas"``));` `console.log(encryptedString(``"HelloHowareyou"``));` `console.log(encryptedString(``"whatareyoudoing"``));`   `console.log(decryptedString(``"segek"``));` `console.log(decryptedString(``"segosegekfrek"``));` `console.log(decryptedString(``"vrstie"``));` `console.log(decryptedString(``"iuthskviacitr"``));` `console.log(decryptedString(``"iuthadpamcitr"``));` `console.log(decryptedString(``"nrechakrak"``));` `console.log(decryptedString(``"hreechakrat"``));` `console.log(decryptedString(encryptedString(``"IamVikas"``)));` `console.log(decryptedString(encryptedString(``"HelloHowareyou"``)));`

Output

```segek
segosegekfrek
vrstie
iuthskviacitr
nrechakrak
hreechakrat
ecdcoehf
aimIaVks
oeaoolHelHwryu
gidoeaawhtryuon
geeks
geeksforgeeks
strive
vikaschitturi
hackerrank
hackerearth
IamVikas
HelloHowareyou
whatareyoudoing

```

Complexity Analysis:

• Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
• Auxiliary Space: O(N), as we are using extra space. Where N is the length of the string.

Approach: Using 2 pointers

## C++

 `#include ` `using` `namespace` `std;`   `string decrypt(string encrypted_string)` `{` `  ``int` `i = 0;` `  ``int` `n = encrypted_string.size();` `  ``int` `j = n - 1;` `  ``string decrypted_string = ``""``;` `  ``if` `(n % 2 == 1) {` `    ``while` `(i < j) {` `      ``decrypted_string` `        ``= encrypted_string[i] + decrypted_string;` `      ``decrypted_string` `        ``= encrypted_string[j] + decrypted_string;` `      ``i++;` `      ``j--;` `    ``}` `    ``decrypted_string` `      ``= encrypted_string[i] + decrypted_string;` `  ``}` `  ``else` `{` `    ``while` `(i < j) {` `      ``decrypted_string` `        ``= encrypted_string[j] + decrypted_string;` `      ``decrypted_string` `        ``= encrypted_string[i] + decrypted_string;` `      ``i++;` `      ``j--;` `    ``}` `  ``}` `  ``return` `decrypted_string;` `}` `int` `main()` `{` `  ``cout << (decrypt(``"segosegekfrek"``)) << endl;` `  ``cout << (decrypt(``"vrstie"``)) << endl;` `  ``cout << (decrypt(``"segek"``)) << endl;` `}`   `// This code is contributed by garg28harsh.`

## Java

 `/*package whatever //do not write package name here */` `import` `java.util.*;`   `public` `class` `Solution {` `    ``static` `String decrypt(String encrypted_string)` `    ``{` `        ``int` `i = ``0``;` `        ``int` `n = encrypted_string.length();` `        ``int` `j = n - ``1``;` `        ``String decrypted_string = ``""``;` `        ``if` `(n % ``2` `== ``1``) {` `            ``while` `(i < j) {` `                ``decrypted_string` `                    ``= encrypted_string.charAt(i)` `                      ``+ decrypted_string;` `                ``decrypted_string` `                    ``= encrypted_string.charAt(j)` `                      ``+ decrypted_string;` `                ``i++;` `                ``j--;` `            ``}` `            ``decrypted_string = encrypted_string.charAt(i)` `                               ``+ decrypted_string;` `        ``}` `        ``else` `{` `            ``while` `(i < j) {` `                ``decrypted_string` `                    ``= encrypted_string.charAt(j)` `                      ``+ decrypted_string;` `                ``decrypted_string` `                    ``= encrypted_string.charAt(i)` `                      ``+ decrypted_string;` `                ``i++;` `                ``j--;` `            ``}` `        ``}` `        ``return` `decrypted_string;` `    ``}` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``System.out.println(decrypt(``"segosegekfrek"``));` `        ``System.out.println(decrypt(``"vrstie"``));` `        ``System.out.println(decrypt(``"segek"``));` `    ``}` `}` `// This code is contributed by karandeep1234`

## Python3

 `def` `decrypt(encrypted_string):` `    ``i ``=` `0` `    ``n ``=` `len``(encrypted_string)` `    ``j ``=` `n``-``1` `    ``decrypted_string ``=` `''` `    ``if` `n ``%` `2` `=``=` `1``:` `        ``while` `i < j:` `            ``decrypted_string ``=` `encrypted_string[i] ``+` `decrypted_string` `            ``decrypted_string ``=` `encrypted_string[j] ``+` `decrypted_string` `            ``i ``+``=` `1` `            ``j ``-``=` `1` `        ``decrypted_string ``=` `encrypted_string[i] ``+` `decrypted_string` `    ``else``:` `        ``while` `i < j:` `            ``decrypted_string ``=` `encrypted_string[j] ``+` `decrypted_string` `            ``decrypted_string ``=` `encrypted_string[i] ``+` `decrypted_string` `            ``i ``+``=` `1` `            ``j ``-``=` `1` `    ``return` `decrypted_string`     `# Testing sample inputs` `if` `__name__ ``=``=` `'__main__'``:` `    ``print``(decrypt(``'segosegekfrek'``)) ``# should print geeksforgeeks` `    ``print``(decrypt(``'vrstie'``)) ``# should print strive` `    ``print``(decrypt(``'segek'``)) ``# should print geeks`

## C#

 `using` `System;`   `public` `class` `GFG {` `  ``static` `string` `decrypt(``string` `encrypted_string)` `  ``{` `    ``int` `i = 0;` `    ``int` `n = encrypted_string.Length;` `    ``int` `j = n - 1;` `    ``String decrypted_string = ``""``;` `    ``if` `(n % 2 == 1) {` `      ``while` `(i < j) {` `        ``decrypted_string = encrypted_string[i]` `          ``+ decrypted_string;` `        ``decrypted_string = encrypted_string[j]` `          ``+ decrypted_string;` `        ``i++;` `        ``j--;` `      ``}` `      ``decrypted_string` `        ``= encrypted_string[i] + decrypted_string;` `    ``}` `    ``else` `{` `      ``while` `(i < j) {` `        ``decrypted_string = encrypted_string[j]` `          ``+ decrypted_string;` `        ``decrypted_string = encrypted_string[i]` `          ``+ decrypted_string;` `        ``i++;` `        ``j--;` `      ``}` `    ``}` `    ``return` `decrypted_string;` `  ``}`   `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``Console.WriteLine(decrypt(``"segosegekfrek"``));` `    ``Console.WriteLine(decrypt(``"vrstie"``));` `    ``Console.WriteLine(decrypt(``"segek"``));` `  ``}` `}`   `// This code is contributed by karandeep1234`

## Javascript

 `function` `decrypt(encrypted_string)` `{` `  ``let i = 0;` `  ``let n = encrypted_string.length;` `  ``let j = n - 1;` `  ``let decrypted_string = ``""``;` `  ``if` `(n % 2 == 1) {` `    ``while` `(i < j) {` `      ``decrypted_string = encrypted_string[i] + decrypted_string;` `      ``decrypted_string = encrypted_string[j] + decrypted_string;` `      ``i++;` `      ``j--;` `    ``}` `    ``decrypted_string = encrypted_string[i] + decrypted_string;` `  ``}` `  ``else` `{` `    ``while` `(i < j) {` `      ``decrypted_string = encrypted_string[j] + decrypted_string;` `      ``decrypted_string = encrypted_string[i] + decrypted_string;` `      ``i++;` `      ``j--;` `    ``}` `  ``}` `  ``return` `decrypted_string;` `}`   `console.log(decrypt(``"segosegekfrek"``));` `console.log(decrypt(``"vrstie"``));` `console.log(decrypt(``"segek"``));`   `// This code is contributed by Samim Hossain Mondal.`

Output

```geeksforgeeks
strive
geeks

```

Complexity Analysis:

• Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string.
• Auxiliary Space: O(N), as we are using extra space. Where N is the length of the string.

#### Decrypt a string according to given rules:

Approach:

1. Define a function “decrypt” that takes the “ciphertext” string as input.
2. Iterate over all the possible 26 shifts.
3. For each shift, create an empty string “decrypted”.
4. Iterate over each character in the “ciphertext” string.
5. If the character is an alphabet, then shift it using the current shift value and add it to the “decrypted” string.
6. If the character is not an alphabet, then add it directly to the “decrypted” string.
7. Print the current shift value and the decrypted message for that shift.
8. Time complexity: O(n^2) where n is the length of the “ciphertext” string since we are iterating over all the possible 26 shifts for each character in the string.
9. Space complexity: O(n) since we are creating a new string “decrypted” for each shift.

## C++

 `#include ` `#include `   `using` `namespace` `std;`   `void` `decrypt(string ciphertext) {` `  ``for` `(``int` `shift = 0; shift < 26; shift++) {` `    ``string decrypted = ``""``;` `    ``for` `(``char``& c : ciphertext) {` `      ``if` `(``isalpha``(c)) {` `        ``if` `(``isupper``(c)) {` `          ``decrypted += ((c - shift - ``'A'` `+ 26) % 26) + ``'A'``;` `        ``} ``else` `{` `          ``decrypted += ((c - shift - ``'a'` `+ 26) % 26) + ``'a'``;` `        ``}` `      ``} ``else` `{` `        ``decrypted += c;` `      ``}` `    ``}` `    ``cout << ``"Shift: "` `<< shift << ``", Decrypted message: "` `<< decrypted << endl;` `  ``}` `}`   `int` `main() {` `  ``string ciphertext = ``"Khoor, zruog!"``;` `  ``decrypt(ciphertext);` `  ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `public` `class` `Main {`   `  ``public` `static` `void` `decrypt(String ciphertext) {` `    ``for` `(``int` `shift = ``0``; shift < ``26``; shift++) {` `      ``String decrypted = ``""``;` `      ``for` `(``char` `c : ciphertext.toCharArray()) {` `        ``if` `(Character.isLetter(c)) {` `          ``if` `(Character.isUpperCase(c)) {` `            ``decrypted += (``char``) (((c - shift - ``'A'` `+ ``26``) % ``26``) + ``'A'``);` `          ``} ``else` `{` `            ``decrypted += (``char``) (((c - shift - ``'a'` `+ ``26``) % ``26``) + ``'a'``);` `          ``}` `        ``} ``else` `{` `          ``decrypted += c;` `        ``}` `      ``}` `      ``System.out.println(``"Shift: "` `+ shift + ``", Decrypted message: "` `+ decrypted);` `    ``}` `  ``}`   `  ``public` `static` `void` `main(String[] args) {` `    ``String ciphertext = ``"Khoor, zruog!"``;` `    ``decrypt(ciphertext);` `  ``}` `}`

## Python3

 `def` `decrypt(ciphertext):` `    ``for` `shift ``in` `range``(``26``):` `        ``decrypted ``=` `""` `        ``for` `char ``in` `ciphertext:` `            ``if` `char.isalpha():` `                ``if` `char.isupper():` `                    ``decrypted ``+``=` `chr``((``ord``(char) ``-` `shift ``-` `65``) ``%` `26` `+` `65``)` `                ``else``:` `                    ``decrypted ``+``=` `chr``((``ord``(char) ``-` `shift ``-` `97``) ``%` `26` `+` `97``)` `            ``else``:` `                ``decrypted ``+``=` `char` `        ``print``(f``"Shift: {shift}, Decrypted message: {decrypted}"``)`   `ciphertext ``=` `"Khoor, zruog!"` `decrypt(ciphertext)`

## C#

 `using` `System;`   `class` `Program {` `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``string` `ciphertext` `            ``= ``"Khoor, zruog!"``; ``// The encrypted message` `        ``Decrypt(ciphertext); ``// Call the Decrypt function` `                             ``// with the encrypted message` `                             ``// as an argument` `    ``}`   `    ``static` `void` `Decrypt(``string` `ciphertext)` `    ``{` `        ``for` `(``int` `shift = 0; shift < 26;` `             ``shift++) ``// Loop through all possible shifts` `        ``{` `            ``string` `decrypted` `                ``= ``""``; ``// Initialize an empty string to store` `                      ``// the decrypted message` `            ``foreach``(` `                ``char` `c ``in` `ciphertext) ``// Loop through each` `                                      ``// character in the` `                                      ``// encrypted message` `            ``{` `                ``if` `(``char``.IsLetter(` `                        ``c)) ``// Check if the character is a` `                            ``// letter` `                ``{` `                    ``if` `(``char``.IsUpper(` `                            ``c)) ``// Check if the letter is` `                                ``// uppercase` `                    ``{` `                        ``decrypted` `                            ``+= (``char``)(((c - shift - ``'A'``)` `                                       ``+ 26)` `                                          ``% 26` `                                      ``+ ``'A'``); ``// Decrypt` `                                              ``// uppercase` `                                              ``// letters` `                                              ``// using the` `                                              ``// shift value` `                    ``}` `                    ``else` `{` `                        ``decrypted` `                            ``+= (``char``)(((c - shift - ``'a'``)` `                                       ``+ 26)` `                                          ``% 26` `                                      ``+ ``'a'``); ``// Decrypt` `                                              ``// lowercase` `                                              ``// letters` `                                              ``// using the` `                                              ``// shift value` `                    ``}` `                ``}` `                ``else` `{` `                    ``decrypted += c;` `                ``}` `            ``}` `            ``Console.WriteLine(` `                ``"Shift: "` `+ shift + ``", Decrypted message: "` `                ``+ decrypted); ``// Print the shift value and` `                              ``// decrypted message for each` `                              ``// possible shift value` `        ``}` `    ``}` `}`

## Javascript

 `function` `decrypt(ciphertext) {` `  ``for` `(let shift = 0; shift < 26; shift++) {` `    ``let decrypted = ``""``;` `    ``for` `(let i = 0; i < ciphertext.length; i++) {` `      ``let char = ciphertext.charAt(i);` `      ``if` `(char.match(/[a-z]/i)) {` `        ``if` `(char === char.toUpperCase()) {` `          ``decrypted += String.fromCharCode((char.charCodeAt(0) - shift - 65 + 26) % 26 + 65);` `        ``} ``else` `{` `          ``decrypted += String.fromCharCode((char.charCodeAt(0) - shift - 97 + 26) % 26 + 97);` `        ``}` `      ``} ``else` `{` `        ``decrypted += char;` `      ``}` `    ``}` `    ``console.log(`Shift: \${shift}, Decrypted message: \${decrypted}`);` `  ``}` `}`   `let ciphertext = ``"Khoor, zruog!"``;` `decrypt(ciphertext);`

Output

```...: 3, Decrypted message: Hello, world!
Shift: 4, Decrypted message: Gdkkn, vnqkc!
Shift: 5, Decrypted message: Fcjjm, umpjb!
Shift: 6, Decrypted message: Ebiil, tloia!
Shift: 7, Decrypted message: Dahhk, sknhz!
Shift: 8, Decrypted message: Czggj, rjmgy!
Shift: 9, Decrypted message: Byffi, qilfx!
Shift: 10, Decrypted message: Axeeh, phkew!
Shift: 11, Decrypted message: Zwddg, ogjdv!
Shift: 12, Decrypted message: Yvccf, nficu!
Shift: 13, Decrypted message: Xubbe, mehbt!
Shift: 14, Decrypted message: Wtaad, ldgas!
Shift: 15, Decrypted message: Vszzc, kcfzr!
Shift: 16, Decrypted message: Uryyb, jbeyq!
Shift: 17, Decrypted message: Tqxxa, iadxp!
Shift: 18, Decrypted message: Spwwz, hzcwo!
Shift: 19, Decrypted message: Rovvy, gybvn!
Shift: 20, Decrypted message: Qnuux, fxaum!
Shift: 21, Decrypted message: Pmttw, ewztl!
Shift: 22, Decrypted message: Olssv, dvysk!
Shift: 23, Decrypted message: Nkrru, cuxrj!
Shift: 24, Decrypted message: Mjqqt, btwqi!
Shift: 25, Decrypted message: Lipps, asvph!

```

The time complexity of the “decrypt” function in the given Python code is O(n * 26), where n is the length of the input “ciphertext” string. This is because the function iterates over all the 26 possible shift values and for each shift value, it iterates over each character in the “ciphertext” string.

The auxiliary space of the function is also O(n * 26), where n is the length of the input “ciphertext” string. This is because for each shift value, a new string “decrypted” is created and its length is equal to the length of the “ciphertext” string. Therefore, the total space required by the function is proportional to the product of the length of the “ciphertext” string and the number of shift values, which is 26 in this case.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!