Open In App

Decrypt the Message string by using Key Phrases

Last Updated : 14 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings Encrypted message and a key phrase. The message is encrypted using a key phrase. Find the original message by decrypting the  encrypted message using a key phrase by following the below-mentioned rules:

  • The number of words in the message and key phrase will always be equal.
  • The first word of the message will be encrypted with the last word of the phrase and the second word of the message will be encrypted using the second last word of the key phrase and the same continues for the rest of the words.
  • If the keyword has an even number of characters, the word is encrypted by incrementing each of its characters by the length of the keyword.
  • If the keyword has an odd number of characters, the word is encrypted by decrementing each of its characters by the length of the keyword.

Constraints:

  • The number of words in the message to be encrypted and the key phrase should be equal.
  • Only lowercase characters are allowed.
  • For this type of encryption, consider only the English alphabet only that too they repeat in a cycle. 

For example, while incrementing the characters, after ‘z’ the next character after incrementing will be ‘a’ and then ‘b’, etc. And for decrementing, before ‘a’ previous character will be ‘z’, and the previous letter for ‘z’ will be ‘y’, etc.

Examples:

Input: Message = “qiix gz clro”, Key = “one orange ball”
Output : meet at four
Explanation :

The message is decrypted as follows :

  • The first encrypted word ‘qiix‘ is decrypted using the last word of the key phrase, ‘ball‘ .’ball’ is 4 letters long. Since, 4 is an even number, the encryption is done by incrementing every character by 4. For decrypting we have to do reverse the encryption process i.e. decrement each character by 4. This gives ‘qiix’ = ‘meet‘.
  • The second encrypted word ‘gz‘ is decrypted using the second last word of the key phrase, ‘orange‘ .’orange’ is 6 letters long. Since, 6 is an even number, the encryption is done by incrementing every character by 6. For decrypting we have to do reverse the encryption process i.e. decrement each character by 6. This gives ‘gz’ = ‘at‘.
  • The last encrypted word ‘clro‘ is decrypted using the first word of the key phrase, ‘one‘ .’one’ is 3 letters long. Since, 3 is an odd number, the encryption is done by decrementing every character by 3. For decrypting we have to do reverse the encryption process i.e. increment each character by 3. This gives ‘clro’ = ‘four‘.

Input: Message = “luaxzn vsa filmrh bpm jxoh”, Key = “the greatest game ever played”
Output: fourth row behind the mark

Approach & Steps involved in implementation:

The entire decryption will work according to the rules which are described in the problem statement so initially we will extract the words of message in a vector of strings and do the same for key phrase. Now, iterate over the vector which contains words of message and do the following steps for every iteration:

  • Find the corresponding word from phrase’s vector and follow the steps as per the rules according to the size of word.
  • If the word contain even number of characters then decrement all the characters by its size.
  • If the word contain odd number of characters then increment all the characters  by its size.

At the end make the output string by combining all the words of message vector.

Below is the code the implementation of code:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find original message
string Decryption(string s, string key)
{
 
    // Vector for storing words of
    // encrypted message
    vector<string> msg;
 
    // Vector for storing words
    // of key phrase
    vector<string> ans;
 
    istringstream s1(s);
    istringstream s2(key);
 
    string word;
 
    while (s1 >> word) {
 
        // Extracting words from encrypted
        // message and pushing
        // into msg vector
        msg.push_back(word);
    }
 
    while (s2 >> word) {
 
        // Extracting words from Key
        // Phrase and pushing
        // into ans vector
        ans.push_back(word);
    }
 
    // Iterating over the encrypted
    // message to find corresponding word
    // from key phrase and
    // decrypting the message
    for (int i = 0; i < msg.size(); i++) {
 
        // Message is the current word on
        // which decryption operation
        // will be performed
        string message = msg[i];
 
        // Hint is the current word of
        // key phrase which will be used
        // to define rules of decryption
        string hint = ans[msg.size() - i - 1];
        int value = hint.size();
 
        // When the phrase's word is of
        // odd length
        if (value % 2) {
            for (int i = 0; i < message.size(); i++) {
 
                // If incrementing the
                // characters will cross
                // the given range then we
                // will make cycle
                if ((message[i] - 0) + value > 122) {
 
                    // Finding the number
                    // of characters we
                    // need to increment
                    // after completing
                    // one cycle at 'z'
                    int val = message[i] + value - 122;
                    int temp = 96 + val;
                    message[i] = (char)temp;
                }
                else {
 
                    // Incrementing the
                    // character by size
                    // of corresponding
                    // phrase's word
                    int val = message[i] + value;
                    message[i] = (char)val;
                }
            }
        }
 
        // When the phrase's word
        // is of even length
        else {
 
            // If decrementing the
            // characters will cross the
            // given range then
            // we will make cycle
            for (int i = 0; i < message.size(); i++) {
                if ((message[i] - 0) - value < 97) {
 
                    // Finding how much we
                    // need to decrement
                    // after 'a' to start
                    // new cycle from 'z'
                    // followed by
                    // 'y', 'x'.....
                    int val = message[i] - 96 - value;
                    int temp = 122 + val;
                    message[i] = (char)temp;
                }
                else {
 
                    // Decrementing
                    // characters by size
                    // of corresponding
                    // word of phrase
                    int val = message[i] - value;
                    message[i] = (char)val;
                }
            }
        }
 
        // Saving the changes we made by
        // manipulating the encrypted
        // string's characters
        msg[i] = message;
    }
 
    // String used for returning final
    // answer(decrypted message)
    string f_ans = "";
    for (int i = 0; i < msg.size(); i++) {
        f_ans += msg[i];
        if (i < msg.size() - 1)
            f_ans += ' ';
    }
    return f_ans;
}
 
// Driver code
int main()
{
    string Message = "qiix gz clro";
    string Key = "one orange ball";
 
    // Function call
    cout << Decryption(Message, Key);
 
    return 0;
}


Java




// Java code for the above approach
import java.util.*;
 
class Main {
    // Function to find original message
    public static String Decryption(String s, String key)
    {
        // Vector for storing words of encrypted message
        List<String> msg = new ArrayList<String>();
 
        // Vector for storing words of key phrase
        List<String> ans = new ArrayList<String>();
 
        Scanner s1 = new Scanner(s);
        Scanner s2 = new Scanner(key);
 
        String word;
 
        while (s1.hasNext()) {
            // Extracting words from encrypted message and
            // pushing into msg vector
            word = s1.next();
            msg.add(word);
        }
 
        while (s2.hasNext()) {
            // Extracting words from Key Phrase and pushing
            // into ans vector
            word = s2.next();
            ans.add(word);
        }
 
        // Iterating over the encrypted message to find
        // corresponding word from key phrase and decrypting
        // the message
        for (int i = 0; i < msg.size(); i++) {
            // Message is the current word on which
            // decryption operation will be performed
            String message = msg.get(i);
 
            // Hint is the current word of key phrase which
            // will be used to define rules of decryption
            String hint = ans.get(msg.size() - i - 1);
            int value = hint.length();
 
            // When the phrase's word is of odd length
            if (value % 2 != 0) {
                for (int j = 0; j < message.length(); j++) {
                    // If incrementing the characters will
                    // cross the given range then we will
                    // make cycle
                    if ((message.charAt(j) - 0) + value
                        > 122) {
                        // Finding the number of characters
                        // we need to increment after
                        // completing one cycle at 'z'
                        int val = message.charAt(j) + value
                                  - 122;
                        int temp = 96 + val;
                        message
                            = message.substring(0, j)
                              + (char)temp
                              + message.substring(j + 1);
                    }
                    else {
                        // Incrementing the character by
                        // size of corresponding phrase's
                        // word
                        int val = message.charAt(j) + value;
                        message
                            = message.substring(0, j)
                              + (char)val
                              + message.substring(j + 1);
                    }
                }
            }
 
            // When the phrase's word is of even length
            else {
                // If decrementing the characters will cross
                // the given range then we will make cycle
                for (int j = 0; j < message.length(); j++) {
                    if ((message.charAt(j) - 0) - value
                        < 97) {
                        // Finding how much we need to
                        // decrement after 'a' to start new
                        // cycle from 'z' followed by 'y',
                        // 'x'.....
                        int val = message.charAt(j) - 96
                                  - value;
                        int temp = 122 + val;
                        message
                            = message.substring(0, j)
                              + (char)temp
                              + message.substring(j + 1);
                    }
                    else {
                        // Decrementing characters by size
                        // of corresponding word of phrase
                        int val = message.charAt(j) - value;
                        message
                            = message.substring(0, j)
                              + (char)val
                              + message.substring(j + 1);
                    }
                }
            }
 
            // Saving the changes we made by manipulating
            // the encrypted string's characters
            msg.set(i, message);
        }
 
        // String used for returning final answer(decrypted
        // message)
        String f_ans = "";
        for (int i = 0; i < msg.size(); i++) {
            f_ans += msg.get(i);
            if (i < msg.size() - 1) {
                f_ans += ' ';
            }
        }
        return f_ans;
    }
    // Driver code
    public static void main(String[] args)
    {
        String Message = "qiix gz clro";
        String Key = "one orange ball";
 
        // Function call
        System.out.println(Decryption(Message, Key));
    }
}


Python3




# Python code for the above approach
import math
 
# Function to find original message
def decryption(s, key):
    # List for storing words of encrypted message
    msg = s.split()
 
    # List for storing words of key phrase
    ans = key.split()
 
    # Reversing the key phrase list
    ans = ans[::-1]
 
    # Iterating over the encrypted message to find
    # corresponding word from key phrase and decrypting
    # the message
    for i in range(len(msg)):
        # Message is the current word on which decryption
        # operation will be performed
        message = msg[i]
 
        # Hint is the current word of key phrase which
        # will be used to define rules of decryption
        hint = ans[i]
        value = len(hint)
 
        # When the phrase's word is of odd length
        if value % 2:
            for j in range(len(message)):
                # If incrementing the characters will cross
                # the given range then we will make cycle
                if (ord(message[j]) + value) > 122:
                    # Finding the number of characters we
                    # need to increment after completing one
                    # cycle at 'z'
                    val = (ord(message[j]) + value) - 122
                    temp = 96 + val
                    message = message[:j] + chr(temp) + message[j + 1:]
                else:
                    # Incrementing the character by size
                    # of corresponding phrase's word
                    val = ord(message[j]) + value
                    message = message[:j] + chr(val) + message[j + 1:]
        # When the phrase's word is of even length
        else:
            # If decrementing the characters will cross
            # the given range then we will make cycle
            for j in range(len(message)):
                if (ord(message[j]) - value) < 97:
                    # Finding how much we need to decrement
                    # after 'a' to start new cycle from 'z'
                    # followed by 'y', 'x'.....
                    val = ord(message[j]) - 96 - value
                    temp = 122 + val
                    message = message[:j] + chr(temp) + message[j + 1:]
                else:
                    # Decrementing characters by size of
                    # corresponding word of phrase
                    val = ord(message[j]) - value
                    message = message[:j] + chr(val) + message[j + 1:]
 
        # Saving the changes we made by manipulating
        # the encrypted string's characters
        msg[i] = message
 
    # String used for returning final answer(decrypted message)
    f_ans = " ".join(msg)
    return f_ans
 
# Driver code
def main():
    Message = "qiix gz clro"
    Key = "one orange ball"
 
    # Function call
    print(decryption(Message, Key))
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static string Decryption(string s, string key)
    {
        // Vector for storing words of encrypted message
        List<string> msg = s.Split(' ').ToList();
 
        // Vector for storing words of key phrase
        List<string> ans = key.Split(' ').ToList();
 
        // Iterating over the encrypted message to find corresponding word
        // from key phrase and decrypting the message
        for (int i = 0; i < msg.Count; i++)
        {
            // Message is the current word on which decryption operation
            // will be performed
            string message = msg[i];
 
            // Hint is the current word of key phrase which will be used
            // to define rules of decryption
            string hint = ans[msg.Count - i - 1];
            int value = hint.Length;
 
            // When the phrase's word is of odd length
            if (value % 2 == 1)
            {
                for (int j = 0; j < message.Length; j++)
                {
                    // If incrementing the characters will cross the given range
                    // then we will make cycle
                    if ((message[j] - 0) + value > 122)
                    {
                        // Finding the number of characters we need to increment
                        // after completing one cycle at 'z'
                        int val = message[j] + value - 122;
                        int temp = 96 + val;
                        message = message.Remove(j, 1).Insert(j, ((char)temp).ToString());
                    }
                    else
                    {
                        // Incrementing the character by size of corresponding
                        // phrase's word
                        int val = message[j] + value;
                        message = message.Remove(j, 1).Insert(j, ((char)val).ToString());
                    }
                }
            }
            // When the phrase's word is of even length
            else
            {
                // If decrementing the characters will cross the given range then
                // we will make cycle
                for (int j = 0; j < message.Length; j++)
                {
                    if ((message[j] - 0) - value < 97)
                    {
                        // Finding how much we need to decrement after 'a' to start
                        // new cycle from 'z' followed by 'y', 'x'.....
                        int val = message[j] - 96 - value;
                        int temp = 122 + val;
                        message = message.Remove(j, 1).Insert(j, ((char)temp).ToString());
                    }
                    else
                    {
                        // Decrementing characters by size of corresponding
                        // word of phrase
                        int val = message[j] - value;
                        message = message.Remove(j, 1).Insert(j, ((char)val).ToString());
                    }
                }
            }
 
            // Saving the changes we made by manipulating the encrypted
            // string's characters
            msg[i] = message;
        }
 
        // String used for returning final answer(decrypted message)
        string f_ans = string.Join(" ", msg);
        return f_ans;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        string Message = "qiix gz clro";
        string Key = "one orange ball";
 
        // Function call
        Console.WriteLine(Decryption(Message, Key));
    }
}


Javascript




// Function to find original message
function decryption(s, key) {
    // List for storing words of encrypted message
    let msg = s.split(" ");
 
    // List for storing words of key phrase
    let ans = key.split(" ");
 
    // Reversing the key phrase list
    ans = ans.reverse();
 
    // Iterating over the encrypted message to find
    // corresponding word from key phrase and decrypting
    // the message
    for (let i = 0; i < msg.length; i++) {
        // Message is the current word on which decryption
        // operation will be performed
        let message = msg[i];
 
        // Hint is the current word of key phrase which
        // will be used to define rules of decryption
        let hint = ans[i];
        let value = hint.length;
 
        // When the phrase's word is of odd length
        if (value % 2) {
            for (let j = 0; j < message.length; j++) {
                // If incrementing the characters will cross
                // the given range then we will make cycle
                if ((message.charCodeAt(j) + value) > 122) {
                    // Finding the number of characters we
                    // need to increment after completing one
                    // cycle at 'z'
                    let val = (message.charCodeAt(j) + value) - 122;
                    let temp = 96 + val;
                    message = message.substring(0, j) + String.fromCharCode(temp) + message.substring(j + 1);
                } else {
                    // Incrementing the character by size
                    // of corresponding phrase's word
                    let val = message.charCodeAt(j) + value;
                    message = message.substring(0, j) + String.fromCharCode(val) + message.substring(j + 1);
                }
            }
        }
        // When the phrase's word is of even length
        else {
            // If decrementing the characters will cross
            // the given range then we will make cycle
            for (let j = 0; j < message.length; j++) {
                if ((message.charCodeAt(j) - value) < 97) {
                    // Finding how much we need to decrement
                    // after 'a' to start new cycle from 'z'
                    // followed by 'y', 'x'.....
                    let val = message.charCodeAt(j) - 96 - value;
                    let temp = 122 + val;
                    message = message.substring(0, j) + String.fromCharCode(temp) + message.substring(j + 1);
                } else {
                    // Decrementing characters by size of
                    // corresponding word of phrase
                    let val = message.charCodeAt(j) - value;
                    message = message.substring(0, j) + String.fromCharCode(val) + message.substring(j + 1);
                }
            }
        }
 
        // Saving the changes we made by manipulating
        // the encrypted string's characters
        msg[i] = message;
    }
 
    // String used for returning final answer(decrypted message)
    let f_ans = msg.join(" ");
    return f_ans;
}
 
// Driver code
function main() {
    let Message = "qiix gz clro";
    let Key = "one orange ball";
 
    // Function call
    console.log(decryption(Message, Key));
}
 
main();
// This code is contributed by Prajwal Kandekar


Output

meet at four

Time Complexity: O(N * Maxlength(word))
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads