[Coding Challenge] Secure My Conversation by Encryption and Decryption
This is competitive coding question was asked in Goldman Sachs coding round. There were two coding questions which are needed to be solved in two hours.
Basically you can take one hour to solve this question.
Problem Statement: Secure My Conversation by Encryption and Decryption
Person A and B use an encryption-based system for their conversation.
Each conversation message is encrypted from the source and decrypted in the destination using a shared private positive number key known to each other.
The algorithm is illustrated with an example.
Input format with explanation:
- Operation (1 for Encryption and 2 for Decryption)
- Input message
- Input private key
Output format with explanation:
- Output message
1 Open 123
Here, the input message characters are duplicated based on each digit in the key.
2 Oppeeen 123
Here, the input message characters are compressed based on each digit in the key.
The conversation message and the private key need NOT be in equal length and the encoding/decoding takes place till the end is reached either conversation message or private key while retaining the rest of the conversation message.
Programming Solution in Python:
#!/bin/python3 import math import os import random import re import sys # Complete the secureChannel function below. def secureChannel(operation, message, key): if len(message)==0 or len(key)==0: return "-1" strRet="" if operation==1: index=0 for keyVal in key: nKeyVal=int(keyVal) if index>=len(message): return strRet strRet=strRet+message[index]*nKeyVal index=index+1 if index < len(message): strRet=strRet+message[index:] elif operation==2: index=0 for keyVal in key: nKeyVal=int(keyVal) if index>=len(message): return strRet for i in range(0,nKeyVal): if (index+i)>=len(message): return "-1" if message[index] != message[index+i]: return "-1" strRet=strRet+message[index] index=index+nKeyVal if index < len(message): strRet=strRet+message[index:] else: return "-1" return strRet if __name__ == '__main__': print(secureChannel(1, 'Open', '123')) print(secureChannel(2, 'Oppeeen', '123'))
The program is self-explanatory. If you have any doubt or finding I difficult to understand the code, kindly comment your query below.
You can solve this coding question in any programming languages. I choose Python as I feel more comfortable with.
For more practice check other competitive coding challenge questions.