Problem · String
Caesar Cipher with a Precomputed Alphabet
Learn this problemProblem statement
Given a string text and an integer shift, apply a Caesar cipher to every English letter.
- Uppercase letters wrap within
AthroughZ. - Lowercase letters wrap within
athroughz. - Digits, spaces, punctuation, and every other character remain unchanged.
Return the transformed string. The shift may be positive, zero, or negative. Normalize it once modulo 26 and precompute the fixed mapping for the two alphabets before scanning a long input.
Function
caesarCipher(text: String, shift: int) → StringExamples
Example 1
text = "Abc-Z9"shift = 2return = "Cde-B9"Each letter moves two positions with wraparound. The hyphen and digit are unchanged.
Example 2
text = "aZ!"shift = -1return = "zY!"A negative shift moves letters backward, wrapping a to z. The exclamation mark is unchanged.
Example 3
text = "Hello, World!"shift = 26return = "Hello, World!"A shift of 26 completes one full alphabet rotation, so the text does not change.
Constraints
0 <= text.length <= 2 * 10^5.-10^9 <= shift <= 10^9.textcontains printable ASCII characters.