Lossless Run-Length Codec With Backslash Escaping

Difficulty: Hard · Unit 1: Core Foundations & Text · Featured in: Tough Challenge

Standard run-length encoding breaks on strings containing digits or backslashes. Implement a lossless codec: ENCODE compresses maximal consecutive runs as `<count><escaped_char>`, where digits (`0`-`9`) and `\` are escaped with a leading `\`. DECODE reverses the process. If the input to DECODE is malformed (dangling escape, missing character after count, zero count), output INVALID.

Input & Output Format

Input: Line 1: mode (`ENCODE` or `DECODE`). Line 2: the raw payload string (excluding the trailing newline).

Output: Print the transformed string, or `INVALID` if decoding fails.

Sample 1

ENCODE
AA222\B
2A3\21\\1B

Two A's -> 2A, three '2's -> 3\2, one '\' -> 1\\, one B -> 1B.

Sample 2

DECODE
2A3\21\\1B
AA222\B

Reconstructs the exact original string including digits and backslash.

Free forever — sign in with email at poorvithmp.com to unlock the dry run, verified Python 3 solution, edge-case traps, and downloads.

Back to Python Notes Hub