Problem 982

Abstract / Summary

Given an integer array, count how many triplets have a bitwise AND of zero.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0982.cpp

class Solution {
public:
    int countTriplets(vector<int>& nums) {
        const int limit = 1 << 16;
        vector<short> two(limit, 0);

        for (int i = 0; i < nums.size(); i++)
            two[nums[i]]++; // a & a

        for (int i = 0; i < nums.size(); i++)
            for (int j = i+1; j < nums.size(); j++)
            {
                auto x = nums[i] & nums[j];
                two[x] += 2; // a & b = b & a
            }

        // brute-force
        int result = 0;
        for (int i = 0; i < nums.size(); i++)
            for (int mask = 0; mask < limit; mask++)
                if ((mask & nums[i]) == 0)
                    result += two[mask];

        return result;
    }
};
26 lines | 731 bytes | submitted August 9, 2023 | GitHub   14% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (30k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation computes the number of ordered triplets (i, j, k) drawn from the input vector nums such that the bitwise AND of the first two elements is disjoint from the third element, i.e. (nums[i] & nums[j]) & nums[k] == 0. The algorithm proceeds in three logical phases: building a frequency table for all possible pairwise AND results, augmenting that table with contributions from distinct element pairs, and finally scanning the table to accumulate the answer for each element of nums.

Pre-processing

A fixed-size array two of length 2^16 is allocated, each entry being a 16-bit signed integer. The size matches the maximum value that can appear in nums assuming a 16-bit domain.

const int limit = 1 << 16;
vector<short> two(limit, 0);

The first loop iterates over nums and records the count of each value as a self-AND result. Because a & a equals a, this step seeds the table with the contribution of ordered pairs where the two indices coincide.

for (int i = 0; i < nums.size(); i++)
    two[nums[i]]++;               // a & a

Pairwise accumulation

The second nested loop enumerates every unordered pair of distinct indices (i, j) with i < j. For each pair the bitwise AND x is computed, and the table entry two[x] is increased by 2. The increment of 2 reflects the two ordered permutations (i, j) and (j, i) that share the same AND value.

for (int i = 0; i < nums.size(); i++)
    for (int j = i + 1; j < nums.size(); j++) {
        auto x = nums[i] & nums[j];
        two[x] += 2;               // a & b = b & a
    }

At the end of this phase two[m] holds the total number of ordered pairs (p, q) (including p == q) whose bitwise AND equals the mask m.

Final counting

The last double loop walks through each element of nums and, for every possible mask, checks whether the mask is disjoint from the current element. The condition (mask & nums[i]) == 0 guarantees that the AND of the pair represented by the mask does not share any set bit with nums[i]. Whenever the condition holds, the pre-computed count two[mask] is added to the running total result.

int result = 0;
for (int i = 0; i < nums.size(); i++)
    for (int mask = 0; mask < limit; mask++)
        if ((mask & nums[i]) == 0)
            result += two[mask];

The final value of result is returned as the answer.

Edge-case handling

The algorithm naturally accommodates duplicate values because the initial self-AND loop records each occurrence separately, and the pairwise loop adds contributions for every distinct index pair. When an element equals 0, its self-AND contribution is recorded at index 0, and the final counting loop treats mask 0 as always disjoint, thereby adding the full count of pairs whose AND is 0.

If nums contains the maximum 16-bit value (0xFFFF), the mask loop still iterates over the full range 0 … 65535, and the condition (mask & 0xFFFF) == 0 succeeds only for mask 0, correctly limiting contributions to pairs whose AND is zero.

An empty input vector results in no increments to two and a zero result, which the loops handle without special casing.

Performance considerations

The use of a fixed-size vector<short> limits memory consumption to a predictable 128 KB (65536 entries × 2 bytes). Storing counts in a 16-bit type is sufficient because the maximum number of ordered pairs for a vector of length N is N * N, which fits within the range of a signed short for typical problem constraints.

By pre-computing the pairwise AND frequencies, the algorithm avoids recomputing the same AND value repeatedly during the final counting phase. The symmetry exploitation (two[x] += 2) halves the number of pairwise AND evaluations compared to a naïve double loop over ordered pairs.

Restricting the mask enumeration to the 16-bit domain (limit = 1 << 16) ensures that the inner loop of the final counting phase has a constant upper bound, independent of the size of nums. This deterministic bound enables the compiler to generate efficient loop unrolling and branch prediction patterns.

Overall, the design trades a modest amount of extra memory for a reduction in repeated bitwise operations, yielding a solution that scales well for inputs where the value range is bounded by 16 bits.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box of numbered blocks. Some of these blocks are special because when you put two of them together in a secret game called binary and, they turn into a zero. This code is like a helper that wants to find every group of three blocks from your pile that play this game perfectly together.

First, the code makes a giant checklist to remember how many ways any two blocks can combine. It looks at every single block by itself, and then it looks at every possible pair of blocks to see what mystery number they create when combined. It writes these counts down on the checklist so it does not have to do the same math over and over again.

After the checklist is ready, the code goes through the pile one more time. For every block in the pile, it looks at the checklist to see which other mystery numbers would play nicely and result in a zero. If it finds a match, it adds that to a growing pile of points. By the time it finishes looking at every block, it knows exactly how many special groups of three exist.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5.5 | μ = 5.38 | σ = 1.57

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
suxrobGM C#
25 links | 12 authors | 7 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality