Problem · String

Double Substitution Decryption

Learn this problem
MediumUpstart logoUpstartFULLTIMEOA

Problem statement

A message was transformed by two one-to-one character substitutions:

  1. Alice's characters were substituted into Bob's characters.
  2. Bob's characters were substituted into Carol's characters.

You receive aligned clear/cipher training text for each stage:

  • alicePlain and bobCipher define the Alice-to-Bob mapping.
  • bobPlain and carolCipher define the Bob-to-Carol mapping.

When learning either mapping, remove all whitespace from both aligned strings before pairing their characters. The non-whitespace strings have equal lengths and consistently define one-to-one mappings.

Decrypt encryptedMessage from Carol's alphabet back to Bob's alphabet, then from Bob's alphabet back to Alice's alphabet. Preserve every whitespace character in encryptedMessage unchanged. Return the fully decrypted message.

Function

decryptDoubleSubstitution(alicePlain: String, bobCipher: String, bobPlain: String, carolCipher: String, encryptedMessage: String) → String

Examples

Example 1

alicePlain = "abc"bobCipher = "bcd"bobPlain = "bcd"carolCipher = "cde"encryptedMessage = "edc cde"return = "cba abc"

Reversing the Carol-to-Bob mapping changes edc cde to dcb bcd. Reversing the Bob-to-Alice mapping then produces cba abc.

Example 2

alicePlain = "a b c"bobCipher = "x y z"bobPlain = "x y z"carolCipher = "m n o"encryptedMessage = "mno onm"return = "abc cba"

Whitespace in the training text does not create mapping entries. The single space in the encrypted message is preserved.

Constraints

  • Each input string has length from 1 through 10^5.
  • After whitespace removal, each training pair has equal length.
  • Each training pair defines a consistent one-to-one mapping.
  • Every non-whitespace character needed while decrypting is covered by the corresponding inverse mapping.
  • Characters are case-sensitive.

More Upstart problems

drafts saved locally
public String decryptDoubleSubstitution(String alicePlain, String bobCipher, String bobPlain, String carolCipher, String encryptedMessage) {
    // Write your code here.
}
alicePlain"abc"
bobCipher"bcd"
bobPlain"bcd"
carolCipher"cde"
encryptedMessage"edc cde"
expected"cba abc"
checking account