Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Number of Good Pairs
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 2 years ago
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())
A
Anonymous
· 3 years ago
class Solution { numGoodPairs(nums) { let pairCount = 0; for(let i = 0; i < nums.length; i++) { for(let j = i + 1; j < nums.length; j++) { if (nums[i] == nums[j]) pairCount++; } } return pairCount; } }
A
Anonymous
· 3 years ago
class Solution: def numGoodPairs(self, nums): pairCount = 0 # TODO: Write your code here left, right = 0,0 while left < len(nums) - 1: right += 1 if nums[left] == nums[right] and left < right: pairCount += 1 if right == len(nums) - 1: left += 1 right = left return pairCount
Show 1 reply
A
Anonymous
· 3 years ago
and the examples don't really help. this could be explained a lot better.
Show 4 replies
Reading Progress
0%