1512. Number of Good Pairs LeetCode Solution

In this guide, you will get 1512. Number of Good Pairs LeetCode Solution with the best time and space complexity. The solution to Number of Good Pairs problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Good Pairs solution in C++
  4. Number of Good Pairs solution in Java
  5. Number of Good Pairs solution in Python
  6. Additional Resources
1512. Number of Good Pairs LeetCode Solution image

Problem Statement of Number of Good Pairs

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 (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:

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

Example 3:

Input: nums = [1,2,3]
Output: 0

Constraints:

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(101) = O(1)

1512. Number of Good Pairs LeetCode Solution in C++

class Solution {
 public:
  int numIdenticalPairs(vector<int>& nums) {
    int ans = 0;
    vector<int> count(101);

    for (const int num : nums)
      ans += count[num]++;

    return ans;
  }
};
/* code provided by PROGIEZ */

1512. Number of Good Pairs LeetCode Solution in Java

N/A
// code provided by PROGIEZ

1512. Number of Good Pairs LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

See also  1830. Minimum Number of Operations to Make String Sorted LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.