LeetCode Solutions

982. Triples with Bitwise AND Equal To Zero

Time: $O(n^2)$

Space: $O(2^{16}) = O(1)$

			

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;
  }
};
			

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;
  }
}