Count Caesar Cipher Pairs

You are given an array words of n strings. Each string has length m and contains only lowercase English letters.

Two strings s and t are similar if we can apply the following operation any number of times (possibly zero times) so that s and t become equal.

  • Choose either s or t.
  • Replace every letter in the chosen string with the next letter in the alphabet cyclically. The next letter after 'z' is 'a'.

Count the number of pairs of indices (i, j) such that:

  • i < j
  • words[i] and words[j] are similar.

Return an integer denoting the number of such pairs.

Example 1
Inputwords = ["fusion","layout"]
Output1
words[0] = "fusion" and words[1] = "layout" are similar because applying the operation to "fusion" 6 times changes it into "layout".
Example 2
Inputwords = ["ab","aa","za","aa"]
Output2
words[0] = "ab" and words[2] = "za" are similar, and words[1] = "aa" and words[3] = "aa" are similar.

Constraints

  • 1 <= n == words.length <= 10^5
  • 1 <= m == words[i].length <= 10^5
  • 1 <= n * m <= 10^5
  • words[i] consists only of lowercase English letters.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate