Number of identical pairs of numbers in an array

array,陣列 | 21 September 2022

Problem

Problem is from Leetcode 1512. Number of Good Pairs. A pair is identical if A[i] == A[j] & i < j.

  • Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Use collections.Counter, creates a dictionary of frequencies. Note that because the keys of the dictionary are integers, we cannot use for key, value in Counter(A).

All my solutions here are brute force.

Counter

Instead, we can use for value in Counter(A).values().

from collections import Counter
def countSame(A):
    res = 0
    for v in Counter(A).values():
        if v >= 2:
            res += v * (v - 1) /2
    return int(res)

nums = [1,2,3,1,1,3]
print(countSame(nums))
# 4

defaultdict

Or, if you don’t want to use collections.Counter, and prefer to do your own counting, then use collections.defaultdict. It is slightly more convenient to use than plain dict: can skip the extra step of checking whether a key already existed.

from collections import defaultdict
def numIdenticalPairs(nums):
    ct = defaultdict(int)
    for n in nums:
        ct[n] += 1
    # compute
    res = 0
    for i in ct.values():
        res += i*(i - 1) / 2
    return res
nums = [1,2,3,1,1,3]
print(numIdenticalPairs(nums))
# 4

Dict

Lastly, we use plain old dictionary and plain old loops.

def numIdenticalPairs(ums) -> int:
    pairs = 0
    ct = {}
    for i in nums:
        if i in ct:
            ct[i] += 1
        else:
            ct[i] = 1
    res = 0
    for i in ct.values():
        res += i*(i - 1) / 2
    return res