Given an array of integers nums, a pair (i, j) is called a good pair if nums[i] == nums[j] and i < j. Return the number of good pairs.
Input: An array of integers
nums.Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Output: An integer representing the total count of good pairs.
Example: Input:
nums = [1,2,3,1,1,3]Output:4Explanation: The good pairs are(0,3),(0,4),(3,4),(2,5).nums[0] == nums[3] (1 == 1) nums[0] == nums[4] (1 == 1) nums[3] == nums[4] (1 == 1) nums[2] == nums[5] (3 == 3)
Solution
The problem asks us to find pairs (i, j) where nums[i] == nums[j] and i < j.
- Optimized Approach (using a frequency map):
- We can count the occurrences of each unique number in the
numsarray. - For a number that appears
ktimes, the number of good pairs it forms isk * (k - 1) / 2. This is the combination formula "k choose 2", representing the number of ways to pick 2 distinct indices fromkavailable indices. - Use a hash map (or a frequency array since
nums[i]values are small) to store the counts of each number. - Iterate through the
numsarray to populate the frequency map. - After counting, iterate through the values (counts) in the frequency map. For each count
k, addk * (k - 1) / 2to a running total. - Time Complexity: O(n), where n is the length of
nums. We iterate throughnumsonce to count frequencies and then iterate through the map (at mostmax(nums[i])ornunique elements) once to calculate pairs. - Space Complexity: O(U), where U is the number of unique elements in
nums(at mostmax(nums[i])orn).
- We can count the occurrences of each unique number in the
class Solution:
def numIdenticalPairs(self, nums: list[int]) -> int:
good_pairs_count = 0
freq_map = {}
# Count frequencies of each number
for num in nums:
freq_map[num] = freq_map.get(num, 0) + 1
# Calculate good pairs from frequencies
for num_count in freq_map.values():
if num_count >= 2:
# If a number appears k times, it forms k * (k - 1) / 2 good pairs.
good_pairs_count += (num_count * (num_count - 1)) // 2
return good_pairs_count
