ROT13 Encoder/Decoder - Problem

Implement a ROT13 encoder/decoder function that transforms alphabetic characters by shifting them 13 positions in the alphabet. ROT13 is a simple letter substitution cipher that replaces each letter with the letter 13 positions after it in the alphabet.

Key Rules:

  • Only rotate alphabetic characters (a-z, A-Z)
  • Preserve case: uppercase letters stay uppercase, lowercase stay lowercase
  • Keep all non-alphabetic characters unchanged (numbers, spaces, punctuation)
  • ROT13 is its own inverse: applying it twice returns the original string

For example: 'A' becomes 'N', 'B' becomes 'O', ..., 'N' becomes 'A', 'Z' becomes 'M'

Input & Output

Example 1 — Basic Mixed Case
$ Input: text = "Hello World!"
Output: "Uryyb Jbeyq!"
💡 Note: H→U, e→r, l→y, l→y, o→b, space stays, W→J, o→b, r→e, l→y, d→q, ! stays unchanged
Example 2 — Numbers and Punctuation
$ Input: text = "Test123!@#"
Output: "Grfg123!@#"
💡 Note: Only alphabetic characters are rotated: T→G, e→r, s→f, t→g. Numbers and symbols remain unchanged
Example 3 — Wraparound Case
$ Input: text = "XYZ abc"
Output: "KLM nop"
💡 Note: Shows alphabet wraparound: X→K, Y→L, Z→M, a→n, b→o, c→p

Constraints

  • 1 ≤ text.length ≤ 1000
  • text contains ASCII characters only
  • Mix of uppercase, lowercase, numbers, and special characters

Visualization

Tap to expand
INPUTALGORITHMRESULTHello World!Mixed case text with spaceand punctuationHello 1Check if alphabetic2ASCII math: (char-base+13)%263Convert back to character4Keep non-alphabetic unchangedExample TransformH: (72-65+13)%26+65 = 85 = Ue: (101-97+13)%26+97 = 114 = rSpace: unchangedUryyb Jbeyq!ROT13 encoded resultSame structure preservedUryyb Key Insight:ROT13 uses modular arithmetic (char - base + 13) % 26 to shift letters while preserving case and leaving non-alphabetic characters unchangedTutorialsPoint - ROT13 Encoder/Decoder | ASCII Math Optimization
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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