#982
Triples with Bitwise AND Equal To Zero
HardArrayHash TableBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n³) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution leverages the properties of bitwise operations and counts how many numbers can form valid triples without checking every combination. We can use a hashmap to store the frequency of each number and calculate combinations based on their counts.
⚙️
Algorithm
4 steps- 1Step 1: Create a hashmap to count the frequency of each number in the array.
- 2Step 2: For each unique pair of numbers, calculate their bitwise AND and check if it equals zero.
- 3Step 3: If it does, calculate the number of valid triples using the counts from the hashmap.
- 4Step 4: Return the total count of valid triples.
solution.py14 lines
1from collections import Counter
2
3def countTriplets(nums):
4 count = 0
5 freq = Counter(nums)
6 unique_nums = list(freq.keys())
7 for i in range(len(unique_nums)):
8 for j in range(i, len(unique_nums)):
9 if unique_nums[i] & unique_nums[j] == 0:
10 if i == j:
11 count += freq[unique_nums[i]] ** 3
12 else:
13 count += 3 * freq[unique_nums[i]] ** 2 * freq[unique_nums[j]]
14 return countℹ
Complexity note: The complexity is O(n²) due to the nested loops over unique numbers, but we only consider unique pairs, making it more efficient than the brute force approach.
- 1The bitwise AND operation results in zero when at least one bit position is zero in all three numbers.
- 2Using frequency counts can significantly reduce the number of checks needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.