LeetCode 2354: Number of Excellent Pairs Solution

Master LeetCode problem 2354 (Number of Excellent Pairs), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2354. Number of Excellent Pairs

Problem Explanation

Explanation

To solve this problem, we can iterate through all pairs of numbers in the array and check if the pair satisfies the conditions for being an excellent pair. We can use bitwise operations to calculate the number of set bits in the OR and AND of the pair, and then compare it with the given threshold k. By counting the number of distinct excellent pairs, we can return the final count as the result.

  • Initialize a counter to keep track of the number of excellent pairs.
  • Iterate through all pairs of numbers in the array.
  • For each pair, calculate the number of set bits in the OR and AND of the pair.
  • Compare the sum of set bits with k and increment the counter if the condition is met.
  • Return the final count as the number of distinct excellent pairs.

Time Complexity: O(n^2) where n is the length of the input array nums. Space Complexity: O(1)

Solution Code

class Solution {
    public int countExcellentPairs(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int num1 = nums[i];
                int num2 = nums[j];
                int setBitsOR = Integer.bitCount(num1 | num2);
                int setBitsAND = Integer.bitCount(num1 & num2);
                if (setBitsOR + setBitsAND >= k) {
                    count++;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2354 (Number of Excellent Pairs)?

This page provides optimized solutions for LeetCode problem 2354 (Number of Excellent Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2354 (Number of Excellent Pairs)?

The time complexity for LeetCode 2354 (Number of Excellent Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2354 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2354 in Java, C++, or Python.

Back to LeetCode Solutions