Coding problem · Easy · Basics

Caesar Cipher

Easy Algorithms & data structures

Encrypt s with a Caesar cipher: shift each letter forward by shift places in the alphabet, wrapping around (z + 1 = a). Keep upper and lower case, and leave other characters unchanged. 0 <= shift <= 25.

Example 1

Input: s = "abc", shift = 1
Output: "bcd"

Example 2

Input: s = "Hello, World!", shift = 3
Output: "Khoor, Zruog!"

Hints

Hint 1

Turn a letter into a number 0-25 by subtracting the code of 'a' (or 'A').

Hint 2

Add the shift, take the remainder modulo 26, and turn it back into a letter.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

For each letter, compute (code - base + shift) % 26 + base, where base is the code of 'a' or 'A'. The modulo handles the wrap-around.

Reference solution

function caesarCipher(s, shift) {
  return s.replace(/[a-z]/gi, (ch) => {
    const base = ch <= 'Z' ? 65 : 97;
    return String.fromCharCode(((ch.charCodeAt(0) - base + shift) % 26) + base);
  });
}

Was this page helpful?