L1 · FoundationsText basics~5 min · 6 tests

Caesar Cipher Encryption

Shift every letter of a message by k positions with wrap-around, keeping case and leaving other characters alone. Modular arithmetic in Python, tested.

The problem

Shift every letter in text forward by k positions in the alphabet, wrapping around (z → a). Keep upper/lower case; leave non-letters unchanged. k may be larger than 26 or negative.

Examples

  1. Example 1

    Input

    caesar('abc', 1)

    Expected output

    'bcd'
  2. Example 2

    Input

    caesar('Hello, World!', 3)

    Expected output

    'Khoor, Zruog!'

+ 4 hidden tests on Submit — wrap around, negative shift.

Edge cases to ask about

  • Wrap-around
  • Negative k
  • k > 26
  • Punctuation

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · caesar
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    ord/chr with modulo 26O(n)O(n)Python's % is always non-negative for a positive divisor, so negative k works.
    Walkthrough of the optimal approach (try it yourself first)

    Map a letter to 0–25 (ord(ch) - ord('a')), add k, wrap with % 26, and map back with chr. In Python -1 % 26 == 25, so negative shifts work without special cases.

    Complexity: O(n) time, O(n) space. Each character is converted once.

    Reveal the reference solution
    def caesar(text, k):
        out = []
        for ch in text:
            if "a" <= ch <= "z":
                out.append(chr((ord(ch) - ord("a") + k) % 26 + ord("a")))
            elif "A" <= ch <= "Z":
                out.append(chr((ord(ch) - ord("A") + k) % 26 + ord("A")))
            else:
                out.append(ch)
        return "".join(out)

    Follow-ups interviewers ask

    • Write the decoder.
    • Break it without knowing k.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Caesar Cipher Encryption in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. Each character is converted once.

    What follow-up questions do interviewers ask about Caesar Cipher Encryption?

    Write the decoder. Break it without knowing k.