KatInterview

Fixed-Width Substitution Cipher: Encode and Decode

StringsAuto-graded · 19 test cases
EasyAuto-gradedStringsstringshash-mapsimulation

Last 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

  • text contains only lowercase English letters when encoding, and only characters produced by a valid encoding when decoding.
  • mapping has exactly one entry per lowercase letter ("a" through "z"), and every value is a string of exactly length 2.
  • All values in mapping are distinct (decoding is always unambiguous).
  • mode is either "encrypt" or "decrypt".
  • 0 ≤ len(text) ≤ 10⁴
  • When mode is "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.