#3805
Count Caesar Cipher Pairs
MediumArrayHash TableMathStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Normalize each word by converting it to a key based on relative character differences. Use a hash map to count occurrences of each key.
⚙️
Algorithm
3 steps- 1Step 1: Normalize each word to a key representing its character differences.
- 2Step 2: Use a hash map to count how many times each key appears.
- 3Step 3: For each key, calculate the number of similar pairs using the formula k * (k - 1) / 2.
solution.py11 lines
1from collections import defaultdict
2
3def countPairs(words):
4 count = 0
5 freq = defaultdict(int)
6 for word in words:
7 key = tuple((ord(word[i]) - ord(word[0])) % 26 for i in range(len(word)))
8 freq[key] += 1
9 for k in freq.values():
10 count += k * (k - 1) // 2
11 return countℹ
Complexity note: We traverse the list once and use a hash map for counting, leading to linear time complexity.
- 1Strings are similar based on cyclic shifts of characters.
- 2Character differences can be normalized to create unique keys.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.