LeetCode in Kotlin

2354. Number of Excellent Pairs

Hard

You are given a 0-indexed positive integer array nums and a positive integer k.

A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:

Return the number of distinct excellent pairs.

Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.

Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.

Example 1:

Input: nums = [1,2,3,1], k = 3

Output: 5

Explanation: The excellent pairs are the following:

So the number of excellent pairs is 5.

Example 2:

Input: nums = [5,1,1], k = 10

Output: 0

Explanation: There are no excellent pairs for this array.

Constraints:

Solution

class Solution {
    fun countExcellentPairs(nums: IntArray, k: Int): Long {
        val cnt = LongArray(30)
        var res = 0L
        val set: MutableSet<Int> = HashSet()
        for (a in nums) {
            set.add(a)
        }
        for (a in set) {
            cnt[Integer.bitCount(a)]++
        }
        for (i in 1..29) {
            for (j in 1..29) {
                if (i + j >= k) {
                    res += cnt[i] * cnt[j]
                }
            }
        }
        return res
    }
}