Similar Problems

Similar Problems not available

Number Of Excellent Pairs - Leetcode Solution

Companies:

LeetCode:  Number Of Excellent Pairs Leetcode Solution

Difficulty: Hard

Topics: hash-table binary-search bit-manipulation array  

The problem statement for Number Of Excellent Pairs on LeetCode is as follows:

Given an integer array nums, return the number of excellent pairs.

An excellent pair is a pair of indices (i, j) where i < j and nums[i] == nums[j].

Solution:

To solve the above problem, we can use a hash map to keep track of the frequency of each element in the array. Then, we can iterate through the frequency map and calculate the number of excellent pairs.

  1. Initialize a hash map to store the frequency of each element in the array.
Map<Integer, Integer> freqMap = new HashMap<>();
  1. Iterate through the array and update the hash map with the frequency of each element.
for (int num : nums) {
    freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
  1. Initialize a variable count to store the number of excellent pairs.
int count = 0;
  1. Iterate through the frequency map and calculate the number of excellent pairs.
for (int freq : freqMap.values()) {
    count += freq * (freq - 1) / 2;
}
  1. Return the count.
return count;

The time complexity of the above solution is O(n) since we are iterating through the array and the frequency map only once. The space complexity is also O(n) since we are using a hash map to store the frequency of each element in the array.

Number Of Excellent Pairs Solution Code

1