Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Number of Good Pairs (easy)

Problem Statement

Given an array of integers nums, return the number of good pairs.

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

Example 1:

Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs, here are the indices: (0,3), (0,4), (3,4), (2,5).

Example 2:

Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array is a 'good pair'.

Example 3:

Input:  nums = [1,2,3]
Output: 0
Explanation: No number is repeating.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

.....

.....

.....

Like the course? Get enrolled and start learning!
E

Ejike Nwude

· 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;   } }
Show 1 reply
Roman Pisani

Roman Pisani

· 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
Toni Dezman

Toni Dezman

· a year ago

from collections import Counter class Solution: def numGoodPairs(self, nums): seen = Counter() res = 0 for num in nums: res += seen[num] seen[num] += 1 return res
A

amazonintern101

· 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
V

venkatlearning11

· 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
wasim ahmed

wasim ahmed

· 5 months ago

class Solution: def numGoodPairs(self, nums): pairCount = 0 # TODO: Write your code here hashmap = {} for i, num in enumerate(nums): hashmap[num] = hashmap.get(num, []) + [i] for k, v in hashmap.items(): pairCount += len(v) * (len(v)-1)//2 return pairCount