Caesar Cipher - Problem

Implement the Caesar Cipher encryption algorithm that shifts each letter in a message by a given number of positions in the alphabet.

Given a string message and an integer shift, return the encrypted message where each letter is shifted by shift positions. When shifting goes past 'z', it wraps around to 'a' (and similarly for uppercase letters).

Requirements:

  • Only alphabetic characters (a-z, A-Z) should be shifted
  • Non-alphabetic characters (spaces, punctuation, numbers) remain unchanged
  • Preserve the original case (uppercase/lowercase)
  • Handle both positive and negative shift values

Input & Output

Example 1 — Basic Positive Shift
$ Input: message = "Hello", shift = 3
Output: Khoor
💡 Note: Each letter shifts forward by 3: H→K, e→h, l→o, l→o, o→r. Non-alphabetic characters remain unchanged.
Example 2 — Wrapping Around Alphabet
$ Input: message = "xyz", shift = 3
Output: abc
💡 Note: When shift goes past 'z', it wraps to 'a': x→a, y→b, z→c. Demonstrates alphabet wrapping.
Example 3 — Mixed Case with Punctuation
$ Input: message = "Hello, World!", shift = 1
Output: Ifmmp, Xpsme!
💡 Note: Preserves case and punctuation: H→I, e→f, l→m, comma and space unchanged, W→X, etc.

Constraints

  • 1 ≤ message.length ≤ 1000
  • -100 ≤ shift ≤ 100
  • Message contains printable ASCII characters

Visualization

Tap to expand
INPUTALGORITHMRESULTMessage: "Hello"Shift: 3Hello1Check if alphabetic2Convert to 0-25 range3Apply (pos + shift) % 264Convert back to characterEncrypted: "Khoor"Each letter shifted by 3KhoorKey Insight:ASCII arithmetic with modulo 26 automatically handles alphabet wrapping,eliminating manual counting and complex boundary checks.TutorialsPoint - Caesar Cipher | ASCII Arithmetic Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen