Skip to main content
Back to problems
Leetcode
Medium
Hash Maps
Strings
Arrays
Count Caesar Cipher Pairs

Count how many pairs of strings match under a Caesar-cipher-style shift.

Acceptance 0%
Problem Statement

Problem

You are given an array of strings. Two strings are considered a matching pair if one can be turned into the other by shifting every letter by the same amount in the alphabet, with wraparound from z to a.

For example, shifting by 1 turns abc into bcd, and shifting by 2 turns xyz into zab.

Your task is to count the number of index pairs (i, j) with i < j such that words[i] and words[j] are matching pairs.

Two strings are only comparable if they have the same length.

Input Format

  • A list of strings words.
  • Each string contains lowercase English letters only.

Output Format

  • Return an integer representing the number of matching pairs.

Constraints

  • 1 <= words.length
  • All strings contain only lowercase English letters.
  • Only strings of equal length can form a pair.
  • A valid pair must share the same relative character differences under a uniform cyclic shift.
Examples
Sample cases returned by the problem API.

Example 1

Input

words = ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]

Output

4

Explanation

The matching pairs are:

  • abc with bcd
  • abc with xyz
  • bcd with xyz
  • az with ba Single-letter strings a and z also match, giving one more pair. Total: 4.

Example 2

Input

words = ["aa", "bb", "cc"]

Output

3

Explanation

All three strings are equivalent under a uniform shift, so every pair matches: (aa, bb), (aa, cc), and (bb, cc).

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.