Caesar cipher with wraparound shifts

0
Sign in

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.

TeslaAmazonCodingEasyLast asked Jun 2026

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.