Caesar Cipher Encryptor

A corgi smiling happily

Given a non-empty string of lowercase letters and a non-negative integer representing a key, write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet, where k is the key.

Note that letters should “wrap” around the alphabet; in other words, the letter z shifted by one returns the letter a.

Sample Input

1string = "xyz"
2key = 2

Sample Output



Hint 1

Most languages have built-in functions that give you the Unicode value of a character as well as the character corresponding to a Unicode value. Consider using such functions to determine which letters the input string’s letters should be mapped to.

Hint 2

Try creating your own mapping of letters to codes. In other words, try associating each letter in the alphabet with a specific number - its position in the alphabet, for instance - and using that to determine which letters the input string’s letters should be mapped to.

Hint 3

How do you handle cases where a letter gets shifted to a position that requires wrapping around the alphabet? What about cases where the key is very large and causes multiple wrappings around the alphabet? The modulo operator should be your friend here.

Optimal Space & Time Complexity

O(n) time | O(n) space - where n is the length of the input string

1function caesarCipherEncryptor(string, key) {
2 let newString = ''
3 key = key % 26;
4 for (let i = 0; i < string.length; i++) {
5 let newAlpha = string.charCodeAt(i) + key;
6 if (newAlpha > 122) {
7 let howMuchGreater = newAlpha - 122;
8 newAlpha = 97 + howMuchGreater - 1;
9 }
10 newString += String.fromCharCode(newAlpha)
11 }
12 return newString;


Do you have any questions, or simply wish to contact me privately? Don’t hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.