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

Single-pass shift verification with modular arithmetic
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 True

Common follow-up questions