Caesar Cipher

Medium~15 min

Given a string s and an integer shift, apply a Caesar cipher by shifting every letter in the string by shift positions in the alphabet.

Rules:

  • Uppercase letters remain uppercase, lowercase letters remain lowercase
  • Non-letter characters (digits, spaces, punctuation) are left unchanged
  • The shift wraps around: shifting 'z' by 1 gives 'a', shifting 'a' by -1 gives 'z'
  • shift can be any integer (positive, negative, or zero)

Examples

Example 1
Input: s = "abc", shift = 3
Output: "def"
Explanation: Each letter is shifted forward by 3: a->d, b->e, c->f.
Example 2
Input: s = "Hello, World!", shift = 13
Output: "Uryyb, Jbeyq!"
Explanation: Letters are shifted by 13 (ROT13). Non-letters stay the same.
Example 3
Input: s = "xyz", shift = 3
Output: "abc"
Explanation: The shift wraps around: x->a, y->b, z->c.

Constraints

  • 0 <= s.length <= 10^4
  • -10^6 <= shift <= 10^6
  • s contains printable ASCII characters
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run