Count Caesar Cipher Pairs Problem
Description
LeetCode Problem 3805.
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
sort. - 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 < jwords[i]andwords[j]are similar.
Return an integer denoting the number of such pairs.
Example 1:
Input: words = ["fusion","layout"]
Output: 1
Explanation:
words[0] = "fusion" and words[1] = "layout" are similar because we can apply the operation to "fusion" 6 times. The string "fusion" changes as follows.
- "fusion"
- "gvtjpo"
- "hwukqp"
- "ixvlrq"
- "jywmsr"
- "kzxnts"
- "layout"
Example 2:
Input: words = ["ab","aa","za","aa"]
Output: 2
Explanation:
words[0] = "ab" and words[2] = "za" are similar. words[1] = "aa" and words[3] = "aa" are similar.
Constraints:
1 <= n == words.length <= 10^51 <= m == words[i].length <= 10^51 <= n * m <= 10^5words[i]consists only of lowercase English letters.
Solution
Approach: Normalize Each String
Shifting a string changes every letter by the same amount, so two strings are similar exactly when they look the same after we shift the first letter to 'z' and apply that same shift to the rest. Build this normalized form for each word and count how often each form appears in a hash map.
A form that appears v times contributes v * (v - 1) / 2 pairs. Add these up.
Complexity: Time O(n * m), space O(n * m), where n is the number of words and m the word length.
from collections import defaultdict
class Solution:
def countPairs(self, words: List[str]) -> int:
cnt = defaultdict(int)
for s in words:
t = list(s)
k = ord("z") - ord(t[0])
for i in range(1, len(t)):
t[i] = chr((ord(t[i]) - ord("a") + k) % 26 + ord("a"))
t[0] = "z"
cnt["".join(t)] += 1
return sum(v * (v - 1) // 2 for v in cnt.values())