Caesar Cipher

Medium · rating 1150 · strings, implementation

Read a line of text, then an integer shift k on the next line. Print the text with every letter shifted forward k places in the alphabet (wrapping around), preserving case. Non-letter characters are unchanged.

Constraints: 0 ≤ k ≤ 25

Editorial

The Caesar Cipher shifts each letter a fixed number of places through the alphabet — one of the oldest ciphers and a classic string / modular-arithmetic exercise.

Approach

Map each letter to 0–25, add the shift, wrap with mod 26, and map back — preserving case and leaving non-letters untouched.

def shift(c, k):
    if c.isupper():
        return chr((ord(c) - 65 + k) % 26 + 65)
    if c.islower():
        return chr((ord(c) - 97 + k) % 26 + 97)
    return c

Complexity

Time: O(n). Space: O(n) for the output. A shift of 13 is the well-known ROT13.

Open Caesar Cipher in Code Arena →