Leetcode 1512: Number of Good Pairs

grid47
grid47
Exploring patterns and algorithms
Jun 8, 2024 4 min read

You are given an array of integers. A pair (i, j) is called a good pair if nums[i] == nums[j] and i < j. Your task is to find the number of good pairs in the array.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array nums where each element can range from 1 to 100.
Example: nums = [4, 5, 6, 4, 4, 6]
Constraints:
• 1 <= nums.length <= 100
• 1 <= nums[i] <= 100
Output: Return the total number of good pairs in the array.
Example: 4
Constraints:
• Return the result as an integer.
Goal: The goal is to calculate the number of good pairs by checking all pairs of indices in the array where the elements are equal and the first index is less than the second.
Steps:
• Step 1: Iterate through the array and store the frequency of each element using a hashmap.
• Step 2: For each element, calculate the number of good pairs that can be formed using the frequency of that element.
• Step 3: Return the total count of good pairs.
Goal: Ensure the input array meets the constraints given in the problem description.
Steps:
• 1 <= nums.length <= 100
• 1 <= nums[i] <= 100
Assumptions:
• The array has at least one element.
• The elements are integers between 1 and 100.
Input: nums = [4, 5, 6, 4, 4, 6]
Explanation: In this case, the good pairs are formed by the elements 4 and 6. We can count the pairs by using the frequency of each element.

Input: nums = [2, 2, 2, 2]
Explanation: Since all elements are equal, every pair is a good pair. The total number of good pairs is calculated by the combination formula C(n, 2), where n is the number of occurrences of the element.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus