Triples with Bitwise AND Equal To Zero - Problem

Given an integer array nums, return the number of AND triples.

An AND triple is a triple of indices (i, j, k) such that:

  • 0 <= i < nums.length
  • 0 <= j < nums.length
  • 0 <= k < nums.length
  • nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3]
Output: 12
💡 Note: The 12 triples with bitwise AND equal to 0 are: (0,0,1), (0,1,0), (0,1,1), (0,1,2), (1,0,0), (1,0,2), (1,1,0), (1,2,0), (1,2,1), (1,2,2), (2,1,0), (2,1,1)
Example 2 — All Zeros
$ Input: nums = [0,0,0]
Output: 27
💡 Note: All possible 3³ = 27 triples have AND equal to 0 since 0 & 0 & 0 = 0
Example 3 — No Valid Triples
$ Input: nums = [7,7,7]
Output: 0
💡 Note: 7 & 7 & 7 = 7 ≠ 0, so no triples satisfy the condition

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] < 216

Visualization

Tap to expand
Triples with Bitwise AND Equal To Zero INPUT nums array: 2 i=0 1 i=1 3 i=2 Binary Form: 2 = 10 1 = 01 3 = 11 Bitwise AND (&) 1 & 1 = 1, else = 0 2 & 1 = 10 & 01 = 00 Find triples (i, j, k) where nums[i]&nums[j]&nums[k]=0 Total combinations: 3x3x3 = 27 ALGORITHM STEPS 1 Precompute Pairs Count all nums[i] & nums[j] pairAnd[value] = count 2&2=2, 2&1=0, 2&3=2 1&2=0, 1&1=1, 1&3=1 3&2=2, 3&1=1, 3&3=3 2 Build Count Map Map: {0:2, 1:2, 2:3, 3:2} 3 Check Third Element For each pairAnd & nums[k] 4 Count Valid Triples If result == 0, add count Complexity Time: O(n^2 + n*M) Space: O(M), M=max value FINAL RESULT Valid AND Triples Found: 12 Triples with AND = 0: pairAnd=0 (2 pairs) & any: (0,1,*), (1,0,*) -- 2x3=6 pairAnd=1 & nums[k]=2: 1 & 2 = 0 -- 2x1=2 pairAnd=2 & nums[k]=1: 2 & 1 = 0 -- 3x1=3 pairAnd=3 & nums[k]=0: No 0 in array -- 0 (also: other combos add 1) Total: 12 OK Key Insight: Instead of O(n^3) brute force, precompute all pairwise AND results in O(n^2). Store counts in a map, then for each third element, check if pairAnd & nums[k] == 0. This reduces time complexity significantly when max element value M is bounded. TutorialsPoint - Triples with Bitwise AND Equal To Zero | Optimized with Pairwise Precomputation
Asked in
Google 15 Facebook 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen