• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Coding Challenge] Secure My Conversation by Encryption and Decryption

Aniruddha Chaudhari/25725/6
Code

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:

  1. Operation (1 for Encryption and 2 for Decryption)
  2. Input message
  3. Input private key

Output format with explanation:

  1. Output message

Example 1:

Input:

1
Open
123

Output:

Oppeeen

Here, the input message characters are duplicated based on each digit in the key.

Example 2:

Input:

2
Oppeeen 
123

Output:

Open

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

Just don’t read the coding solution. To get the maximum out of it. Try to execute this code in our online compiler and understand the logic implemented.

Python Code

#!/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'))

To understand this code, you can refer Python Programming tutorial.

C++ Code

(This solution in C++ is shared by the Shivani Singh.)

#include <string>
#include <iostream>

using namespace std;

string encoding( string msg, string key)
{
  string ans;
  int i=0;//for msg
  int j=0;//for key
  int keysize = key.size();
  int msgsize= msg.size();
  if(keysize==0 || msgsize==0)
    return "";//to be defined in question
  while(j<keysize && i<msgsize)
  {
    int count= key[j]-'0';
    for(int it=0;it<count;it++)
      ans.push_back(msg[i]);
    j++; i++;
  }
  while(i< msgsize)
  {
    ans.push_back(msg[i]);
    i++;
  }
  return ans;
}

string decoding(string msg, string key)
{
  string ans;
  int i=0;//for msg
  int j=0;//for key
  int keysize = key.size();
  int msgsize= msg.size();
  if(keysize==0 || msgsize==0)
  return " ";//to be defined in question
  while(i<msgsize && j<keysize)
  {
    ans.push_back(msg[i]);
    i=i+(key[j]-'0');
    j++;
  }
  while(i<msgsize)
  {
    ans.push_back(msg[i]);
    i++;
  }
  return ans;
}

int main()
{
  string msg= "open";
  string key= "123";
  cout<<encoding(msg,key)<<endl;
  cout<<decoding("oppeeen","123");
  return 0;
}

To understand this code, refer C/C++ programming tutorial.

Output:

Oppeeen
Open

Java Code

(This solution in Java is shared by the Bharath Kalyan S.)

public static String EncryptMessage(String message, String key) {
        if (message.length() == 0 || key.length() == 0)
            return "";

        StringBuilder builder = new StringBuilder();
        int i = 0, j = 0;
        int messageLength = message.length();
        int keyLength = key.length();

        while (i < messageLength && j < keyLength) {
            char character = message.charAt(i);
            int repeat = key.charAt(j) - '0';
            for (int k = 0; k < repeat; k++) {
                builder.append(character);
            }
            i++;
            j++;
        }
        if (i != messageLength) {
            builder.append(message.substring(i));
        }

        return builder.toString();
    }

    public static String DecryptMessage(String encryptedMessage, String key) {
        if (encryptedMessage.length() == 0 || key.length() == 0)
            return "";

        StringBuilder builder = new StringBuilder();
        int i = 0, j = 0;
        int messageLength = encryptedMessage.length();
        int keyLength = key.length();

        while (j < keyLength) {
            char mainChar = encryptedMessage.charAt(i);
            builder.append(mainChar);
            i = i + key.charAt(j) - '0';
            j++;
        }

        builder.append(encryptedMessage.substring(i));
        return builder.toString();
    }

Refer complete Java tutorial.

The program is self-explanatory. If you have any doubt or finding it difficult to understand the code, kindly comment your query below.

You can solve this coding question in any programming language.

For more practice check other competitive coding challenge questions.

Python Interview Questions eBook

coding challenge
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Shivani Singh
    August 5, 2020 at 5:30 pm

    hey, I tried solving this question in c++.. but since I can’t test my code anywhere, feedbacks and corrections are welcome.

    • Reply
      Aniruddha Chaudhari
      August 6, 2020 at 10:56 pm

      Hi Shivani, I tested your code and it’s working. Awesome! I have added your code in our article.

      This will help many. Thanks for submitting your code.

      If you are interested to share your knowledge and contribute to our portal, kindly check here.

  • Reply
    Vaishnavi
    April 10, 2021 at 11:31 pm

    Hi, I tried this question and got the solution in python but as I can’t test it, can you please give me a feedback

    m=int(input())
    if m==1:
        str=input()
        num=input()
        nums=[]
        for i in num:
            if i.isdigit():
                nums.append(int(i))
        d={}
        s=""
        for i in str:
            if i.isalnum() and i not in d:
                d[i]=str.count(i)
        j=0 
    
        for key,val in d.items():
           
            if j<len(nums):    
                for i in range(nums[j]):
                    s+=key
                j+=1    
    
            else:
                s+=key              
    elif m==2:    
        str=input()
        num=input()
        nums=[]
        for i in num:
            if i.isdigit():
                nums.append(int(i))
        d={}
        s=""
        for i in str:
            if i.isalnum() and i not in d:
                d[i]=str.count(i)
        i=0        
        for key,val in d.items():
            if i<len(nums):
                if val==nums[i]:
                    s+=key
            else:
                for i in range(val):
                    s+=key
            i+=1   
    print(s)
    
  • Reply
    Vaishnavi
    April 10, 2021 at 11:38 pm

    I’m unable to attach the picture and in the above-shared code the comments section is not considering the syntax of the code.

    m=int(input())
    if m==1:
        str=input()
        # 
        num=input()
        nums=[]
        for i in num:
            if i.isdigit():
                nums.append(int(i))
        d={}
        s=""
        for i in str:
            if i.isalnum() and i not in d:
                d[i]=str.count(i)
        j=0 
    
        for key,val in d.items():
            if j<len(nums):    
                for i in range(nums[j]):
                    s+=key
                j+=1    
            else:
                s+=key
                        
    elif m==2:    
        str=input()
    
        num=input()
        nums=[]
        for i in num:
            if i.isdigit():
                nums.append(int(i))
        d={}
        s=""
        for i in str:
            if i.isalnum() and i not in d:
                d[i]=str.count(i)
        i=0        
        for key,val in d.items():
            if i<len(nums):
                if val==nums[i]:
                    s+=key
            else:
                for i in range(val):
                    s+=key
            i+=1   
    print(s)
    
  • Reply
    Bharath Kalyan S
    June 16, 2021 at 8:29 pm

    Hey, I tried this in Java and I am attaching the Snippet!

    • Reply
      Aniruddha Chaudhari
      June 17, 2021 at 10:59 am

      Hi Bharath, that’s great. Thanks for sharing the Java code. I have added your solution in the tutorial.

Leave a Reply Cancel reply

Why?

Why Competitive Programming Important?

Coding Challenges for Practice

  1. Count Common Factor
  2. Does it Divide
  3. Sum of Sub Arrays
  4. Pair of Desired Sum
  5. Remove Duplicate Char from String
  6. Sort String by Char Freq (Python)
  7. Sort String by Char Freq (Java)
  8. Split Array into Equal Sum Subarray
  9. Validate IP Address
  10. Validate PAN Card Number
  11. Validate Sudoku
  12. Sort Circular Rotated Array
  13. Min Arrow to Burst Bubbles
  14. Min Cost to Paint All Houses [Amazon]
  15. HourGlass with Largest Sum
  16. Max Profit by Buying/Selling Stocks
  17. Hailstone Sequence
  18. Reverse String without affecting Special Characters
  19. Secure Conversation by Encry/Decry
  20. Special Elements in Matrix
  21. Next Greater No with Same set of Digits
  22. Smallest Subarray with Sum Greater than Given Number
  23. Group Anagrams
  24. Find Duplicates in Array in O(n)
  25. Find Two Unique Numbers from Array in O(n)
  26. Number Patterns & Finding Smallest Number
  27. First Unique Element in a Stream
  28. Flip Equivalent Binary Trees [TeachMint]
  29. Minimum Cost of Merging Files [Amazon]
  30. Minimum Distance for Truck to Deliver Order [Amazon]
  31. Order Task for Given Dependencies
  32. Design Music Player
  33. Multilevel Parking System Design
  34. Minimum Coins Required
  35. Max Sum Subarray
  36. Max Avg Sum of Two Subsequences
  37. Merge Overlapping Intervals
  38. Longest Balanced Subarray
  39. Longest Path in a Weighted Tree
  40. Generate Balanced Parentheses
  41. PostOrder Traversal Without Recursion

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard