Caesar Cipher: Rotate Letters
๐ฆ Caesar Cipher: Rotate Letters
Difficulty: Beginner Tags: strings, cipher, modular arithmetic Series: CS 101
Problem
Implement a Caesar cipher - one of the oldest and simplest encryption techniques!
Your task: shift each lowercase letter in a string by k positions in the alphabet. When you reach 'z', wrap around back to 'a'. Leave all non-letter characters (spaces, punctuation, numbers) unchanged.
Input
data = {'text': str, 'k': int}
text: The string to encryptk: How many positions to shift (0-25)
Output
str # The encrypted text
Constraints
0 โค k < 26(shift amount)- Text length โค 100,000 characters
- Only shift lowercase letters (leave everything else unchanged)
Examples
Example 1: Basic Shift
Input: {'text': 'abc xyz!', 'k': 2}
Output: 'cde zab!'
Step-by-step: - 'a' + 2 = 'c' - 'b' + 2 = 'd' - 'c' + 2 = 'e' - ' ' stays ' ' (space) - 'x' + 2 = 'z' - 'y' + 2 = 'a' (wraps around!) - 'z' + 2 = 'b' (wraps around!) - '!' stays '!' (punctuation)
Example 2: Wrap-around
Input: {'text': 'xyz', 'k': 3}
Output: 'abc'
Why? - 'x' is the 24th letter โ shift by 3 โ 27th position โ wraps to 'a' (1st letter) - 'y' is the 25th letter โ shift by 3 โ 28th position โ wraps to 'b' (2nd letter) - 'z' is the 26th letter โ shift by 3 โ 29th position โ wraps to 'c' (3rd letter)
Example 3: Non-letters Unchanged
Input: {'text': 'a-b', 'k': 1}
Output: 'b-c'
The hyphen '-' stays in place, only letters shift.