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": Translatetextcharacter by character from left to right, replacing each charactercwithmapping[c]and joining the 2-character codes directly with no separator. Raise an exception (such asValueError) iftextcontains any character absent frommapping. - When
mode == "decrypt": Partitiontextinto 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 iflen(text)is odd, if any 2-character segment does not match a value inmapping, or ifmappingassigns the same code to multiple letters. - Empty input: When
text == "", return""in both"encrypt"and"decrypt"modes. - Invalid mode: Raise an exception if
modeis 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^51 <= 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
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 codebookmapping:- Every lowercase letter in
mappingcorresponds to a distinct 2-character code, such as{"d": "k9", "e": "r2", "m": "t5", "o": "p7"}. - Encryption translates each letter of
textto 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 descriptiveValueError. Silently dropping characters loses information, and leaving a 1-character symbol inside the output shifts every subsequent 2-character boundary out of alignment!- Every lowercase letter in
Encrypting: one dictionary lookup per character
To encode
text, step throughtextone character at a time, look upmapping[ch], collect each 2-character code inencoded_pieces, and join them once at the end via"".join(encoded_pieces).Why step character by character instead of calling
text.replace(ch, code)acrossmapping? Because 2-character codes can contain letters that are also keys inmapping! Watch what happens withmapping = {'a': 'ba', 'b': 'ab'}ontext = "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 guaranteesO(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)Why decryption must slice aligned 2-character chunks
Decryption suffers a mirror-image bug if you call
encrypted_text.replace(code, ch). Supposemapping = {'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 indices2*kand2*k + 1. Steppingstartby2(0, 2, 4, ...) and slicingencrypted_text[start : start + 2]inspects only true block boundaries and never sees straddling pairs.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'). Scanningmapping.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 inO(1)average lookup time. Buildingreverse_mapis 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_mapDecrypting with validation and dispatching by mode
Now
decryptcomes together in three phases: 1. Checklen(encrypted_text) % 2 == 0—an odd length means a 2-character block was truncated. 2. Constructreverse_map = build_reverse_mapping(mapping). 3. Advancestartin steps ofCODE_LENGTH = 2, look up eachchunkinreverse_map(raisingValueErrorif missing), and join the recovered letters.Finally,
transform_cipherdispatches"encrypt"toencryptand"decrypt"todecrypt.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}")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"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 spendsO(k)time once to constructreverse_map(k <= 26) and then performsm / 2constant-time slices and dictionary lookups followed by oneO(m)join. - Space: O(n) for encryption and O(m + k) for decryption. Encryption stores
n2-character strings inencoded_piecesplus the2n-character output; decryption stores up tokentries inreverse_map(O(1)for a 26-letter alphabet) plusm / 2decoded letters indecoded_chars.
Edge cases
- Empty string (
""): Length0is divisible by2, neither loop runs, and both modes return"". - Unmapped plaintext character: Raises
ValueErrornaming the offending character instead of silently dropping it or passing it through. - Odd-length ciphertext:
len(encrypted_text) % 2 != 0raisesValueErrorimmediately because a valid concatenation of 2-character codes always has even length. - Unknown 2-character chunk: Raises
ValueErrorreporting 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'): Steppingrange(0, len, 2)inspects only even boundaries0, 2, ..., never odd offsets like1..3. - Duplicate codes in
mapping: Caught insidebuild_reverse_mappingand rejected withValueErrorsince two letters sharing one code cannot be uniquely decoded.
Common mistakes
- Using
str.replaceto encrypt or decrypt: Corrupts already-encoded characters during encryption and matches unaligned cross-boundary substrings during decryption. - Stepping by
1instead of2indecrypt: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 intoO(k)instead ofO(1)average via a prebuiltreverse_map. - Repeatedly concatenating
out += piecein a loop: Can degrade toO(n^2)string copies across Python runtimes; collecting into a list and calling"".join(...)is guaranteedO(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 inO(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
ValueErrorthat 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-inerrors="replace"policy (modeled after Python'sbytes.decode) that emits'?'or'\ufffd'for unreadable segments while logging their positions.
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?
- Why is a static substitution table vulnerable to letter-frequency attacks, and how would you harden the scheme?
- What error-handling strategies make sense when decoding encounters an unrecognized chunk or a truncated string?
Similar questions
- Object-Oriented Animal Chess Engine
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One