Fixed-Width Substitution Cipher: Encode and Decode
StringsAuto-graded · 19 test casesLast updated
Tests your ability to apply character-to-code substitution and reverse it using an inverted dictionary for O(1) chunk lookups.
Problem
You are given a substitution table: a dictionary where every lowercase letter maps to a unique two-character code. Your job is to apply that table in one direction or the other, depending on a mode flag.
Encode mode ("encrypt")
Replace each character in the input with its two-character code and concatenate the results.
Decode mode ("decrypt")
The input is an encoded string whose total length is always even. Split it into consecutive two-character chunks — positions [0:2], [2:4], [4:6], and so on — and replace each chunk with the original character it represents.
If a chunk appears in the input but has no entry in the table, leave it unchanged in the output (same rule applies to unmapped characters during encoding).
Constraints
textcontains only lowercase English letters when encoding, and only characters produced by a valid encoding when decoding.mappinghas exactly one entry per lowercase letter ("a"through"z"), and every value is a string of exactly length 2.- All values in
mappingare distinct (decoding is always unambiguous). modeis either"encrypt"or"decrypt".0 ≤ len(text) ≤ 10⁴- When
modeis"decrypt",len(text)is always even.
Examples
Example 1
Input: run_cipher('abc', {'a': '1x', 'b': '2y', 'c': '3z'}, 'encrypt')
Output: '1x2y3z'
Example 2
Input: run_cipher('1x2y3z', {'a': '1x', 'b': '2y', 'c': '3z'}, 'decrypt')
Output: 'abc'
Hints
Hint 1
For encoding, iterate over each character and look it up directly in the mapping dictionary — a single pass is all you need.
Hint 2
For decoding, you cannot use the forward mapping directly. Build a reverse dictionary (code → character) once before you start scanning, so each two-character lookup is O(1).
Hint 3
Step through the encoded string in increments of 2 using range(0, len(text), 2), slice out each chunk, then look it up in your reverse dictionary.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Encoding
Walk the input one character at a time and replace each character with its two-character code from mapping. Characters that have no entry are kept as-is. Collect the pieces in a list and join at the end — this avoids the O(n²) cost of repeated string concatenation.
Decoding
Because every code is exactly two characters long, the boundary between consecutive codes always falls at an even index. There is no ambiguity about where one code ends and the next begins: chunk i occupies indices [2i : 2i+2].
The key insight is to invert the mapping once before scanning. The forward dictionary maps char → code; the reverse maps code → char. Building it up front takes O(k) time (k ≤ 26) and makes every chunk lookup O(1) instead of O(k).
Why it is correct
- Every code has length 2, so splitting at even offsets always recovers the original chunks exactly.
- All codes are distinct (guaranteed by the constraints), so the reverse dictionary is a true inverse: no two characters share a code, and the mapping is one-to-one.
- For any valid encoded string,
run_cipher(run_cipher(s, m, "encrypt"), m, "decrypt") == s.
Complexity
| Time | Space | |
|---|---|---|
| Encode | O(n) | O(n) for the output |
| Decode | O(n + k) | O(n + k) for the output and reverse map |
n = length of text, k = alphabet size (≤ 26).
Reference solution
from typing import Dict
def run_cipher(text: str, mapping: Dict[str, str], mode: str) -> str:
if mode == "encrypt":
# Replace each character with its 2-character code; pass through unknowns.
return "".join(mapping.get(char, char) for char in text)
if mode == "decrypt":
# Invert the mapping once: code -> original character.
reverse = {value: key for key, value in mapping.items()}
result = []
# Step through the encoded string two characters at a time.
for i in range(0, len(text), 2):
chunk = text[i:i + 2]
result.append(reverse.get(chunk, chunk)) # pass through unknowns
return "".join(result)
raise ValueError("mode must be 'encrypt' or 'decrypt'")