FastPrepCaesar Cipher with a Precomputed Alphabet
Problem · String

Caesar Cipher with a Precomputed Alphabet

Learn this problem
EasyAmazon logoAmazonNEW GRADONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given a string text and an integer shift, apply a Caesar cipher to every English letter.

  • Uppercase letters wrap within A through Z.
  • Lowercase letters wrap within a through z.
  • 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) → String

Examples

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.
  • text contains printable ASCII characters.

More Amazon problems

drafts saved locally
public String caesarCipher(String text, int shift) {
  // Write your code here
}
text"Abc-Z9"
shift2
expected"Cde-B9"
checking account