Skip to content
Related Articles

Related Articles

Decrypt a string according to given rules
  • Last Updated : 10 Feb, 2021

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

  1. Start with the first character of the original string.
  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 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 odd step add characters from the front and add characters from back in 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 <bits/stdc++.h>
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
Output: 
geeksforgeeks

 

Below is Python’s implementation.
 

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')))

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :