← Questions

Caesar cipher with wraparound shifts

0
TeslaAmazonCodingLast asked Jun 2026

Implement caesar_encrypt(text: str, k: int) -> str, which applies a Caesar cipher to text.

Every ASCII letter moves k places forward in the alphabet. The alphabet is circular, so a shift that goes past z continues from a (and past Z from A).

Rules:

  • Keep each letter's case: uppercase stays uppercase and lowercase stays lowercase.
  • Copy every other character (digits, spaces, punctuation, non-ASCII) to the output unchanged.
  • k can be any integer, including 0, negative values (which shift backward), and values far larger than 26.
  • The output has the same length as the input.

Also write caesar_decrypt(text: str, k: int) -> str, which reverses the encryption.

Constraints: 0 <= len(text) <= 10^6, -10^9 <= k <= 10^9.

Example 1

caesar_encrypt("Zebra-42", 1)  ->  "Afcsb-42"

Z wraps to A. The hyphen and the digits are unchanged.

Example 2

caesar_encrypt("Hello, World!", -23)  ->  "Khoor, Zruog!"
caesar_decrypt("Khoor, Zruog!", -23)  ->  "Hello, World!"

A shift of -23 is the same as a shift of 3.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding