Caesar Cipher Encryptor
Caesar Cipher Encryptor
Category
Strings
Difficulty
Easy
Problem Statement
Given a non-empty string of lowercase letters and a non-negative integer representing a key, shift every letter in the string by key positions in the alphabet, wrapping around from z back to a. Return the new encrypted string.
Intuition
Each letter in the alphabet can be mapped to a number (a=0, b=1, ..., z=25). Shifting a letter by key positions is equivalent to adding key to its numeric value and taking the result modulo 26 to handle wrapping. This transforms the problem into simple arithmetic.
Approach
- Reduce the key modulo 26 to handle keys larger than the alphabet size.
- Initialize an empty result list.
- For each character in the input string:
- Compute the new character code:
(charCode - 'a' + key) % 26 + 'a'. - Append the new character to the result.
- Compute the new character code:
- Join the result list into a string and return it.
Pseudocode
function caesarCipherEncryptor(string, key):
key = key % 26
result = []
for char in string:
newCharCode = (charCode(char) - charCode('a') + key) % 26
newChar = characterFromCode(newCharCode + charCode('a'))
result.append(newChar)
return join(result, "")
Time & Space Complexity
- Time: O(n) where n is the length of the string. Each character is processed exactly once.
- Space: O(n) for the output string.
Key Insights
- Always reduce the key modulo 26 first to avoid unnecessary full rotations through the alphabet.
- The modulo operation handles the wrap-around from
ztoaelegantly. - Building the result in a list and joining at the end is more efficient than repeated string concatenation in many languages.
Edge Cases
- Key of 0: the output is identical to the input.
- Key of 26 (or any multiple of 26): the output is identical to the input since a full rotation returns to the original letter.
- Very large key values: handled correctly by the modulo operation.
- Single character string: works correctly with the same logic.