Caesar Cipher with a Precomputed Alphabet
Updated
Problem 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.
More Amazon Onsite Interview questions
- Number of IslandsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Cheapest Flights Within K StopsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Dungeon GameONSITE INTERVIEW · Seen Nov 2026
- Integer BreakONSITE INTERVIEW · Seen Nov 2026
- LFU CacheONSITE INTERVIEW · Seen Nov 2026
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
- First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Most Cost-Effective MachineCapital One · ONSITE INTERVIEWCapital One interview questions
- Count Multiples of Three with Two SevensHudson River Trading · OAHudson River Trading interview questions
- Closest ColorTwo Sigma · OATwo Sigma interview questions
- Add Signed Character ArraysByteDance · PHONE SCREENByteDance interview questions
- Eight-Direction Keyboard Typing TimeBenchling · PHONE SCREENBenchling interview questions
- Longest Common PrefixKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Plus OneDruva · ONSITE INTERVIEW
- Rotate a Flat Image ClockwiseGoogle · ONSITE INTERVIEWGoogle interview questions
- Map and Accumulate Learning QueriesPalantir · ONSITE INTERVIEWPalantir interview questions
- Matrix MultiplicationeBay · ONSITE INTERVIEWeBay interview questions