Given an array of integers nums
, a pair (i, j)
is called “good” if nums[i] == nums[j]
and i < j
. We need to count the number of good pairs.
To solve this problem efficiently, we can use a dictionary to keep track of the count of each number as we iterate through the array. For each number, the count of good pairs for that number can be calculated using the number of times it has appeared so far. Here’s how:
nums[i]
, check if it has been seen before.This approach ensures that we only pass through the array once, resulting in efficient time complexity.
from collections import defaultdict
def numIdenticalPairs(nums):
count = defaultdict(int)
good_pairs = 0
for num in nums:
if num in count:
good_pairs += count[num]
count[num] += 1
return good_pairs
# Example Usage
nums = [1,2,3,1,1,3]
print(numIdenticalPairs(nums)) # Output: 4
This ensures an optimal solution for the given problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?