Skip to content

982. Triples with Bitwise AND Equal To Zero

  • Time: $O(n^2)$
  • Space: $O(2^{16}) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int countTriplets(vector<int>& nums) {
    constexpr int kMax = 1 << 16;
    int ans = 0;
    vector<int> count(kMax);  // {nums[i] & nums[j]: times}

    for (const int a : nums)
      for (const int b : nums)
        ++count[a & b];

    for (const int num : nums)
      for (int i = 0; i < kMax; ++i)
        if ((num & i) == 0)
          ans += count[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int countTriplets(int[] nums) {
    final int kMax = 1 << 16;
    int ans = 0;
    int[] count = new int[kMax]; // {nums[i] & nums[j]: times}

    for (final int a : nums)
      for (final int b : nums)
        ++count[a & b];

    for (final int num : nums)
      for (int i = 0; i < kMax; ++i)
        if ((num & i) == 0)
          ans += count[i];

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def countTriplets(self, nums: list[int]) -> int:
    kMax = 1 << 16
    ans = 0
    count = [0] * kMax  # {nums[i] & nums[j]: times}

    for a in nums:
      for b in nums:
        count[a & b] += 1

    for num in nums:
      for i in range(kMax):
        if (num & i) == 0:
          ans += count[i]

    return ans