Fixed-Width Two-Character Cipher

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement transform_cipher(text, mapping, mode) to encode and decode strings using a reversible, fixed-width two-character codebook.

def transform_cipher(text: str, mapping: Dict[str, str], mode: str) -> str:

You are given:

  • text: the source string to process (either raw plaintext or two-character encoded text).
  • mapping: a codebook whose keys are single lowercase ASCII letters ('a'–'z') and whose values are unique 2-character strings (no two letters share the same 2-character code).
  • mode: "encrypt" to encode plaintext, or "decrypt" to recover plaintext.

Transformation Rules

  • When mode == "encrypt": Translate text character by character from left to right, replacing each character c with mapping[c] and joining the 2-character codes directly with no separator. Raise an exception (such as ValueError) if text contains any character absent from mapping.
  • When mode == "decrypt": Partition text into consecutive, non-overlapping 2-character segments (text[0:2], text[2:4], ...) and replace each segment with the single letter that maps to it. Raise an exception if len(text) is odd, if any 2-character segment does not match a value in mapping, or if mapping assigns the same code to multiple letters.
  • Empty input: When text == "", return "" in both "encrypt" and "decrypt" modes.
  • Invalid mode: Raise an exception if mode is neither "encrypt" nor "decrypt".

Examples

Example 1

Input:

text = "demo"
mapping = {"d": "k9", "e": "r2", "m": "t5", "o": "p7"}
mode = "encrypt"

Output:

"k9r2t5p7"

Explanation: Substituting 'd' -> "k9", 'e' -> "r2", 'm' -> "t5", and 'o' -> "p7" in order and concatenating produces "k9r2t5p7".

Example 2

Input:

text = "t5p7p7k9"
mapping = {"d": "k9", "e": "r2", "m": "t5", "o": "p7"}
mode = "decrypt"

Output:

"mood"

Explanation: Reading aligned 2-character pairs gives "t5" -> 'm', "p7" -> 'o', "p7" -> 'o', and "k9" -> 'd', reconstructing "mood".

Constraints

  • 0 <= len(text) <= 10^5
  • 1 <= len(mapping) <= 26, with single-character keys in 'a'–'z' and distinct 2-character string values.
  • Valid plaintext inputs use lowercase ASCII letters; unmapped characters, odd-length encoded inputs, or unrecognized 2-character segments must raise an exception rather than failing silently.

Step-by-step walkthrough

  1. Understand the cipher contract

    We need to implement transform_cipher(text, mapping, mode), which encodes (mode == "encrypt") or decodes (mode == "decrypt") a string using a codebook mapping:

    • Every lowercase letter in mapping corresponds to a distinct 2-character code, such as {"d": "k9", "e": "r2", "m": "t5", "o": "p7"}.
    • Encryption translates each letter of text to its 2-character code: "demo" becomes "k9r2t5p7".
    • Decryption walks the inverse direction, turning "t5p7p7k9" into "mood".
    • Empty strings ("") produce "" in both modes.

    How should we treat malformed inputs—such as a character absent from mapping, a 2-character chunk that matches no entry, or an odd-length ciphertext? Raise a descriptive ValueError. Silently dropping characters loses information, and leaving a 1-character symbol inside the output shifts every subsequent 2-character boundary out of alignment!

  2. Encrypting: one dictionary lookup per character

    To encode text, step through text one character at a time, look up mapping[ch], collect each 2-character code in encoded_pieces, and join them once at the end via "".join(encoded_pieces).

    Why step character by character instead of calling text.replace(ch, code) across mapping? Because 2-character codes can contain letters that are also keys in mapping! Watch what happens with mapping = {'a': 'ba', 'b': 'ab'} on text = "ab":

    Wrong (chained str.replace):
      Start:               "ab"
      Replace 'a' -> 'ba': "bab"
      Replace 'b' -> 'ab': "abaab"   <- mutated already-encoded 'b's!
    
    Correct (single pass over input characters):
      ch = 'a' -> 'ba'
      ch = 'b' -> 'ab'
      Join ['ba', 'ab'] -> "baab"
    

    Accumulating into a list and calling "".join(...) once also guarantees O(n) runtime without repeated string copies.

    from typing import Dict, List
    
    
    def encrypt(text: str, mapping: Dict[str, str]) -> str:
        # encoded_pieces: list of 2-char code strings in order, e.g. ['k9', 'r2', 't5', 'p7']
        encoded_pieces: List[str] = []
        for ch in text:
            if ch not in mapping:
                raise ValueError(f"No mapping found for plaintext character {ch!r}")
            encoded_pieces.append(mapping[ch])
        return "".join(encoded_pieces)
    
  3. Why decryption must slice aligned 2-character chunks

    Decryption suffers a mirror-image bug if you call encrypted_text.replace(code, ch). Suppose mapping = {'a': 'xy', 'b': 'yx'} and we encode "bb" into "yxyx":

    Index:        0   1   2   3
    Ciphertext:   y   x | y   x
                  -----   -----
                  chunk0  chunk1   -> 'yx' + 'yx' = "bb"
    
    Trap! Indices 1..2 spell "xy", straddling the border between chunk0 and chunk1!
    Calling .replace('xy', 'a') would corrupt "yxyx" into "yax"!
    

    Because every letter encodes to strictly 2 characters, the k-th letter always sits at indices 2*k and 2*k + 1. Stepping start by 2 (0, 2, 4, ...) and slicing encrypted_text[start : start + 2] inspects only true block boundaries and never sees straddling pairs.

  4. Invert the mapping once for O(1) chunk lookups

    When we slice a 2-character block like 't5', we need the letter that generated it ('m'). Scanning mapping.items() for every block would repeat linear work across long inputs.

    Instead, construct reverse_map (code -> ch) once up front so each 2-character block decodes in O(1) average lookup time. Building reverse_map is also the right place to confirm no two letters share the same 2-character code.

    from typing import Dict
    
    
    def build_reverse_mapping(mapping: Dict[str, str]) -> Dict[str, str]:
        # reverse_map: maps 2-char code -> original letter, e.g. {'k9': 'd', 'r2': 'e'}
        reverse_map: Dict[str, str] = {}
        for ch, code in mapping.items():
            # Guard against two letters sharing the same code, which would make decoding ambiguous.
            if code in reverse_map:
                raise ValueError(
                    f"Ambiguous mapping: code {code!r} is used by both {reverse_map[code]!r} and {ch!r}"
                )
            reverse_map[code] = ch
        return reverse_map
    
  5. Decrypting with validation and dispatching by mode

    Now decrypt comes together in three phases: 1. Check len(encrypted_text) % 2 == 0—an odd length means a 2-character block was truncated. 2. Construct reverse_map = build_reverse_mapping(mapping). 3. Advance start in steps of CODE_LENGTH = 2, look up each chunk in reverse_map (raising ValueError if missing), and join the recovered letters.

    Finally, transform_cipher dispatches "encrypt" to encrypt and "decrypt" to decrypt.

    from typing import Dict, List
    
    CODE_LENGTH = 2
    
    
    def decrypt(encrypted_text: str, mapping: Dict[str, str]) -> str:
        # Phase 1: Every valid ciphertext is made of 2-char blocks, so odd lengths are corrupted.
        if len(encrypted_text) % CODE_LENGTH != 0:
            raise ValueError(
                f"Ciphertext length {len(encrypted_text)} is not a multiple of {CODE_LENGTH}"
            )
    
        # Phase 2: Invert the codebook once so each chunk lookup takes O(1) average time.
        reverse_map = build_reverse_mapping(mapping)
    
        # Phase 3: Slice aligned 2-character blocks [0:2], [2:4], ... to avoid boundary overlaps.
        decoded_chars: List[str] = []
        for start in range(0, len(encrypted_text), CODE_LENGTH):
            chunk = encrypted_text[start : start + CODE_LENGTH]
            if chunk not in reverse_map:
                raise ValueError(f"Unknown 2-character code {chunk!r} at index {start}")
            decoded_chars.append(reverse_map[chunk])
    
        return "".join(decoded_chars)
    
    
    def transform_cipher(text: str, mapping: Dict[str, str], mode: str) -> str:
        if mode == "encrypt":
            return encrypt(text, mapping)
        if mode == "decrypt":
            return decrypt(text, mapping)
        raise ValueError(f"Mode must be 'encrypt' or 'decrypt', got {mode!r}")
    
  6. Trace Examples 1 and 2

    Let's walk through both examples using mapping = {"d": "k9", "e": "r2", "m": "t5", "o": "p7"}:

    Example 1 (mode = "encrypt", text = "demo"):
      'd' -> 'k9'
      'e' -> 'r2'
      'm' -> 't5'
      'o' -> 'p7'
      "".join(['k9', 'r2', 't5', 'p7']) -> "k9r2t5p7"
    
    Example 2 (mode = "decrypt", text = "t5p7p7k9"):
      1. len("t5p7p7k9") == 8 (divisible by 2)
      2. reverse_map = {'k9': 'd', 'r2': 'e', 't5': 'm', 'p7': 'o'}
      3. start = 0: chunk [0:2] = 't5' -> 'm'
         start = 2: chunk [2:4] = 'p7' -> 'o'
         start = 4: chunk [4:6] = 'p7' -> 'o'
         start = 6: chunk [6:8] = 'k9' -> 'd'
      4. "".join(['m', 'o', 'o', 'd']) -> "mood"
    
  7. Complete solution

    Here is the complete solution ready for submission:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Every plaintext letter encodes to a fixed 2-character code, e.g. 'd' -> 'k9'.
    CODE_LENGTH = 2
    
    
    def encrypt(text: str, mapping: Dict[str, str]) -> str:
        # encoded_pieces: list of 2-char code strings in order, e.g. ['k9', 'r2', 't5', 'p7']
        encoded_pieces: List[str] = []
        for ch in text:
            if ch not in mapping:
                raise ValueError(f"No mapping found for plaintext character {ch!r}")
            encoded_pieces.append(mapping[ch])
        return "".join(encoded_pieces)
    
    
    def build_reverse_mapping(mapping: Dict[str, str]) -> Dict[str, str]:
        # reverse_map: maps 2-char code -> original letter, e.g. {'k9': 'd', 'r2': 'e'}
        reverse_map: Dict[str, str] = {}
        for ch, code in mapping.items():
            # Guard against two letters sharing the same code, which would make decoding ambiguous.
            if code in reverse_map:
                raise ValueError(
                    f"Ambiguous mapping: code {code!r} is used by both {reverse_map[code]!r} and {ch!r}"
                )
            reverse_map[code] = ch
        return reverse_map
    
    
    def decrypt(encrypted_text: str, mapping: Dict[str, str]) -> str:
        # Phase 1: Every valid ciphertext is made of 2-char blocks, so odd lengths are corrupted.
        if len(encrypted_text) % CODE_LENGTH != 0:
            raise ValueError(
                f"Ciphertext length {len(encrypted_text)} is not a multiple of {CODE_LENGTH}"
            )
    
        # Phase 2: Invert the codebook once so each chunk lookup takes O(1) average time.
        reverse_map = build_reverse_mapping(mapping)
    
        # Phase 3: Slice aligned 2-character blocks [0:2], [2:4], ... to avoid boundary overlaps.
        decoded_chars: List[str] = []
        for start in range(0, len(encrypted_text), CODE_LENGTH):
            chunk = encrypted_text[start : start + CODE_LENGTH]
            if chunk not in reverse_map:
                raise ValueError(f"Unknown 2-character code {chunk!r} at index {start}")
            decoded_chars.append(reverse_map[chunk])
    
        return "".join(decoded_chars)
    
    
    def transform_cipher(text: str, mapping: Dict[str, str], mode: str) -> str:
        if mode == "encrypt":
            return encrypt(text, mapping)
        if mode == "decrypt":
            return decrypt(text, mapping)
        raise ValueError(f"Mode must be 'encrypt' or 'decrypt', got {mode!r}")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of mapping as a two-column codebook for a substitution cipher (an encoding scheme that swaps each character of a message with a fixed substitute token). Because every letter maps to a fixed 2-character badge and the pairing is a bijection (a one-to-one mapping where every letter owns a distinct badge and every badge belongs to only one letter), we can glue the 2-character badges side by side with no separator when encoding, then slice the ribbon cleanly every 2 characters when decoding and look each badge up in the inverted codebook.

Naive shortcuts fail in subtle ways. Calling str.replace in a loop while encoding mutates characters inside badges that were already substituted (for example, 'a' -> 'ba' followed by 'b' -> 'ab' rewrites 'ba'), while calling str.replace during decoding matches fake pairs straddling the border between two neighboring badges. Scanning mapping.items() on every 2-character slice also wastes time doing linear searches when inverting the dictionary once makes every lookup instant.

Walk through mapping = {'a': 'xy', 'b': 'yx'} on "abb": - Encrypt "abb": Look up 'a' -> 'xy', 'b' -> 'yx', 'b' -> 'yx', and join ['xy', 'yx', 'yx'] into "xyyxyx". - Decrypt "xyyxyx": First invert mapping into reverse_map = {'xy': 'a', 'yx': 'b'}. Then read aligned 2-character slices [0:2] = 'xy' -> 'a', [2:4] = 'yx' -> 'b', and [4:6] = 'yx' -> 'b' (completely ignoring the straddling 'yy' at [1:3]), joining ['a', 'b', 'b'] back into "abb".

Complexity

  • Time: O(n) to encrypt a string of length n, and O(m + k) to decrypt a string of length m with k mapping entries. Encryption performs one O(1) average dictionary lookup per character and one linear "".join(...) at the end. Decryption spends O(k) time once to construct reverse_map (k <= 26) and then performs m / 2 constant-time slices and dictionary lookups followed by one O(m) join.
  • Space: O(n) for encryption and O(m + k) for decryption. Encryption stores n 2-character strings in encoded_pieces plus the 2n-character output; decryption stores up to k entries in reverse_map (O(1) for a 26-letter alphabet) plus m / 2 decoded letters in decoded_chars.

Edge cases

  • Empty string (""): Length 0 is divisible by 2, neither loop runs, and both modes return "".
  • Unmapped plaintext character: Raises ValueError naming the offending character instead of silently dropping it or passing it through.
  • Odd-length ciphertext: len(encrypted_text) % 2 != 0 raises ValueError immediately because a valid concatenation of 2-character codes always has even length.
  • Unknown 2-character chunk: Raises ValueError reporting both the unrecognized chunk and its starting index.
  • Codes composed of plaintext letters ({'a': 'ba', 'b': 'ab'}): Handled cleanly because each input character is translated once without re-scanning output characters.
  • Straddling false matches ("yxyx" with 'xy' and 'yx'): Stepping range(0, len, 2) inspects only even boundaries 0, 2, ..., never odd offsets like 1..3.
  • Duplicate codes in mapping: Caught inside build_reverse_mapping and rejected with ValueError since two letters sharing one code cannot be uniquely decoded.

Common mistakes

  • Using str.replace to encrypt or decrypt: Corrupts already-encoded characters during encryption and matches unaligned cross-boundary substrings during decryption.
  • Stepping by 1 instead of 2 in decrypt: range(len(encrypted_text)) reads overlapping pairs at every index instead of non-overlapping 2-character blocks.
  • Scanning mapping.items() inside the decryption loop: Turns each chunk lookup into O(k) instead of O(1) average via a prebuilt reverse_map.
  • Repeatedly concatenating out += piece in a loop: Can degrade to O(n^2) string copies across Python runtimes; collecting into a list and calling "".join(...) is guaranteed O(n).
  • Silently ignoring missing keys with mapping.get(ch, ""): Produces truncated output that looks valid while quietly discarding characters.

Follow-up questions

  • How would you redesign encoding and decoding if replacement codes could have varying character lengths rather than always being two characters long? Without fixed width, range(0, len, 2) slicing no longer knows where one code ends and the next starts, so you must either insert a reserved delimiter character (such as ':') that never appears inside any code, or require a prefix-free code (a codebook where no valid code is the prefix of another valid code, as in Huffman coding). With a prefix-free codebook, walk the encoded string one character at a time down a trie (a prefix tree whose edges are characters and whose leaves store letters), emitting a decoded character and resetting to the root whenever a leaf is reached in O(m) total time.
  • Why is a static substitution table vulnerable to letter-frequency attacks, and how would you harden the scheme? Frequency analysis is a cryptanalysis technique that counts how often each code block appears and matches the highest-count blocks to frequent English letters such as 'e', 't', and 'a', while repeated pairs (like "p7p7" in "mood") expose double letters immediately. A simple toy mitigation is homophonic substitution (assigning several distinct codes to common letters and picking one randomly per occurrence to flatten single-block counts), though multi-letter patterns still leak; for genuine confidentiality, replace custom substitution with authenticated encryption (a standard cryptographic cipher such as AES-GCM that combines a secret key with a unique per-message random nonce so identical plaintexts encrypt differently and tampering is detected).
  • What error-handling strategies make sense when decoding encounters an unrecognized chunk or a truncated string? Default to failing fast by raising a ValueError that reports the bad segment and character offset without emitting partial plaintext, ensuring truncated or corrupted payloads are never silently accepted downstream. When callers explicitly need best-effort inspection (for instance, diagnosing damaged text streams), offer an opt-in errors="replace" policy (modeled after Python's bytes.decode) that emits '?' or '\ufffd' for unreadable segments while logging their positions.

Follow-up questions

Similar questions

More Duolingo interview questions

All 2 Duolingo questions →