Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
s or t.'z' is 'a'.Count the number of pairs of indices (i, j) such that:
i < jwords[i] and words[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 <= 1051 <= m == words[i].length <= 1051 <= n * m <= 105words[i] consists only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math
["fusion","layout"]
["ab","aa","za","aa"]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
class Solution {
public long countPairs(String[] words) {
Map<String, Integer> cnt = new HashMap<>();
long ans = 0;
for (String s : words) {
char[] t = s.toCharArray();
int k = 'z' - t[0];
for (int i = 1; i < t.length; i++) {
t[i] = (char) ('a' + (t[i] - 'a' + k) % 26);
}
t[0] = 'z';
cnt.merge(new String(t), 1, Integer::sum);
}
for (int v : cnt.values()) {
ans += 1L * v * (v - 1) / 2;
}
return ans;
}
}
// Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
func countPairs(words []string) int64 {
cnt := make(map[string]int)
var ans int64 = 0
for _, s := range words {
t := []rune(s)
k := 'z' - t[0]
for i := 1; i < len(t); i++ {
t[i] = 'a' + (t[i]-'a'+k)%26
}
t[0] = 'z'
key := string(t)
cnt[key]++
}
for _, v := range cnt {
ans += int64(v) * int64(v-1) / 2
}
return ans
}
# Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
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())
// Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
// class Solution {
// public long countPairs(String[] words) {
// Map<String, Integer> cnt = new HashMap<>();
// long ans = 0;
// for (String s : words) {
// char[] t = s.toCharArray();
// int k = 'z' - t[0];
// for (int i = 1; i < t.length; i++) {
// t[i] = (char) ('a' + (t[i] - 'a' + k) % 26);
// }
// t[0] = 'z';
// cnt.merge(new String(t), 1, Integer::sum);
// }
// for (int v : cnt.values()) {
// ans += 1L * v * (v - 1) / 2;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3805: Count Caesar Cipher Pairs
function countPairs(words: string[]): number {
const cnt = new Map<string, number>();
let ans = 0;
for (const s of words) {
const t = s.split('');
const k = 'z'.charCodeAt(0) - t[0].charCodeAt(0);
for (let i = 1; i < t.length; i++) {
t[i] = String.fromCharCode(97 + ((t[i].charCodeAt(0) - 97 + k) % 26));
}
t[0] = 'z';
const key = t.join('');
cnt.set(key, (cnt.get(key) || 0) + 1);
}
for (const v of cnt.values()) {
ans += (v * (v - 1)) / 2;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.