Number of Excellent Pairs — LeetCode 2354 Python Solution
- Problem
- #2354
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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: Both the numbers num1 and num2 exist in the array nums.
Example
- Input
- nums = [1,2,3,1], k = 3
- Output
- 5
- Explanation
- The excellent pairs are the following:
Python solution
class Solution:
def countExcellentPairs(self, nums: List[int], k: int) -> int:
s = set(nums)
ans = 0
cnt = Counter()
for v in s:
cnt[v.bit_count()] += 1
for v in s:
t = v.bit_count()
for i, x in cnt.items():
if t + i >= k:
ans += x
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2354. Number of Excellent Pairs is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2354. Number of Excellent Pairs?
- LeetCode 2354. Number of Excellent Pairs is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2354. Number of Excellent Pairs?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2354. Number of Excellent Pairs?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2354. Number of Excellent Pairs cover?
- LeetCode 2354. Number of Excellent Pairs is tagged Bit Manipulation, Array, Hash Table and Binary Search on LeetCode.