#2354

Number of Excellent Pairs

Hard
ArrayHash TableBinary SearchBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

By using a frequency map to count the occurrences of each number and leveraging the properties of bit manipulation, we can reduce the time complexity significantly. We can precompute the number of set bits for each unique number and then check combinations efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map to count occurrences of each number in nums.
  2. 2Step 2: Create a list of unique numbers and compute the number of set bits for each.
  3. 3Step 3: For each unique number, check how many other unique numbers can form an excellent pair based on their set bits.
  4. 4Step 4: Use binary search or two pointers to efficiently find pairs that meet the condition.
solution.py15 lines
1# Full working Python code
2from collections import Counter
3
4
5def countExcellentPairs(nums, k):
6    freq = Counter(nums)
7    unique_nums = list(freq.keys())
8    set_bits = [bin(num).count('1') for num in unique_nums]
9    count = 0
10    for i in range(len(unique_nums)):
11        for j in range(len(unique_nums)):
12            if set_bits[i] + set_bits[j] >= k:
13                count += freq[unique_nums[i]] * freq[unique_nums[j]]
14    return count
15

Complexity note: The time complexity is O(n) for counting frequencies and O(n²) in the worst case for checking pairs, but since we leverage the frequency map, it can be optimized further. The space complexity is O(n) for storing the frequency map.

  • 1Understanding bit manipulation is key to solving this problem efficiently.
  • 2Using a frequency map allows us to count pairs without explicitly generating them.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.