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>& A) {
    constexpr int kMax = 1 << 16;
    int ans = 0;
    vector<int> count(kMax);  // {A[i] & A[j]: times}

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

    for (const int a : A)
      for (int i = 0; i < kMax; ++i)
        if (!(a & i))
          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[] A) {
    final int kMax = 1 << 16;
    int ans = 0;
    int[] count = new int[kMax]; // {A[i] & A[j]: times}

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

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

    return ans;
  }
}