Back to course home
0% completed
Vote For New Content
Using a HashMap and a modified triangular numbers formula
Lukas Marquardt
May 15, 2024
I realized there was a way to solve this in a single line (excluding the import) by using the triangular number formula. There's no real advantage here, except that we don't need to count the pairs separately:
Instead, we count the occurrences n for each number and calculate the number of pairs from 0…n-1
from collections import Counter class Solution: def numGoodPairs(self, nums): return sum((v * (v - 1) // 2) for _, v in Counter(nums).items())
1
0
Comments
Comments