Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Number of Good Pairs (easy)

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

def numGoodPairs(self, nums): pair_count = 0 seen_nums = {} for num in nums: if num not in seen_nums: seen_nums[num] = 1 else: pair_count += seen_nums[num] seen_nums[num] += 1 return pair_count
A

Anonymous

· 3 years ago

if we use this approach time complexity is high?

public int numGoodPairs(int[] nums) { int pairCount = 0; // TODO: Write your code here for(int i=0; i<nums.length; i++){ for (int j=i+1; j<nums.length; j++){ if (nums[i]== nums[j]){ pairCount++; } } } return pairCount; }
Show 1 reply
A

Anonymous

· 3 years ago

class Solution {   public int numGoodPairs(int[] nums) {     int pairCount = 0;     Map<Integer, Integer> frequency = new HashMap<>();     for (Integer num : nums) {       frequency.put(num, frequency.getOrDefault(num, 0) + 1);     }     for (Map.Entry<Integer, Integer> entry : frequency.entrySet()) {       int value = entry.getValue();       pairCount += value * (value - 1) / 2;     }     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

HI

Reading Progress

0%


Vote for new content