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);
});
}
function caesarCipher(s: string, shift: number): string {
return s.replace(/[a-z]/gi, (ch) => {
const base = ch <= 'Z' ? 65 : 97;
return String.fromCharCode(((ch.charCodeAt(0) - base + shift) % 26) + base);
});
}
def caesar_cipher(s: str, shift: int) -> str:
out = []
for ch in s:
if ch.isalpha() and ch.isascii():
base = ord('A') if ch.isupper() else ord('a')
out.append(chr((ord(ch) - base + shift) % 26 + base))
else:
out.append(ch)
return ''.join(out)
<?php
function caesarCipher(string $s, int $shift): string
{
$out = '';
foreach (str_split($s) as $ch) {
if (ctype_alpha($ch)) {
$base = ctype_upper($ch) ? 65 : 97;
$out .= chr((ord($ch) - $base + $shift) % 26 + $base);
} else {
$out .= $ch;
}
}
return $out;
}
class Solution {
public String caesarCipher(String s, int shift) {
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
if (ch >= 'a' && ch <= 'z') sb.append((char) ((ch - 'a' + shift) % 26 + 'a'));
else if (ch >= 'A' && ch <= 'Z') sb.append((char) ((ch - 'A' + shift) % 26 + 'A'));
else sb.append(ch);
}
return sb.toString();
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy