Caesar Shift Check
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L4
- Asked in
- Tata Consultancy Services
Problem
Given two equal-length strings a and b consisting of lowercase letters, return True if there exists an integer k (0..25) such that every character of b equals the corresponding character of a shifted by exactly k (wrapping z->a). Return False otherwise.
The key turns. Does it open?
Example 1
Input:
a = "abc", b = "bcd"
Output:
true
Example 2
Input:
a = "xyz", b = "zab"
Output:
true
Worked solution and explanation
Why this problem exists in real interviews
This probes modular arithmetic and character ordinal manipulation, both essential for string transformation problems. It reveals whether a candidate can reason about wrap-around behavior and derive a consistent shift from character pairs.
Break down the requirements
Step 1: Check length equality
Different-length strings cannot be Caesar shifts of each other. Return False immediately.
Step 2: Compute the expected shift from the first pair
Use (ord(b[0]) - ord(a[0])) % 26 to get the shift. The modulo ensures negative differences wrap correctly.
Step 3: Verify all remaining pairs match the shift
For each position, check that (ord(b[i]) - ord(a[i])) % 26 equals the expected shift. If any pair disagrees, return False.
The solution
def can_shift(a, b):
if len(a) != len(b):
return False
if not a:
return True
expected_shift = (ord(b[0]) - ord(a[0])) % 26
for i in range(len(a)):
actual_shift = (ord(b[i]) - ord(a[i])) % 26
if actual_shift != expected_shift:
return False
return TrueCommon follow-up questions
- What if the strings contain uppercase and lowercase letters? (Tests whether you normalize case before computing shifts or handle separate ranges.)
- How would you return the shift value itself instead of a boolean? (Tests minor API design: return the shift or -1 if no valid shift exists.)
- What if the alphabet is not English but an arbitrary character set? (Tests generalization of modular arithmetic to arbitrary alphabet sizes.)