Katkat

Implement String Encryption and Decryption

DuolingoSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to manage character mapping and reverse lookups using dictionaries to perform basic string transformation and reconstruction.

Problem Statement

You are tasked with building a simple cipher mechanism. You are provided with a 'mapping' dictionary where each character in the alphabet maps to a unique list of characters (a string representation). Since a character might map to multiple characters, you must also provide a way to reverse this process.

Task 1: Encryption

Implement a function encrypt(text, mapping) that converts a plaintext string into an encrypted string based on the provided dictionary.

Task 2: Decryption

Implement a function decrypt(encrypted_text, mapping) that reconstructs the original plaintext.

Note: Each character in the original plaintext maps to a unique sequence in the encrypted text. You may assume that the encrypted values are distinct enough to be parsed, or are delimited if necessary. For this implementation, assume each character in the plaintext maps to a fixed-length string of length 2.

Constraints

  • text contains only lowercase English letters.
  • mapping is a dictionary where each key is a character 'a'-'z' and the value is a string of length 2.

Example

mapping = {'a': '1x', 'b': '2y', 'c': '3z'}

# Encryption
encrypt("abc", mapping) # Returns "1x2y3z"

# Decryption
decrypt("1x2y3z", mapping) # Returns "abc"

Edge Cases

  • Empty input string.
  • Input string containing characters not found in the mapping dictionary.

Hints

Hint 1

To encrypt, iterate through each character in the input string, retrieve its value from the dictionary, and append it to a result list or string.

Hint 2

To decrypt, process the encrypted string in chunks of 2 characters at a time.

Hint 3

For efficient decryption lookups, consider pre-processing the mapping dictionary by reversing the key-value pairs (i.e., mapping '1x' back to 'a').

Follow-up questions

  • How would your approach change if the encrypted values had variable lengths instead of a fixed length of 2?
  • What modifications would be needed to make the encryption more secure against frequency analysis?
  • How would you handle errors if the encrypted string contains a segment that does not exist in the reverse mapping?