#3514
Medium Algorithms Number of unique xor triplets ii
Array Math Bit Manipulation Enumeration
32.4% acceptance
Feb 25, 2026
43
9
You are given an integer array nums.
A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k.
Return the number of unique XOR triplet values from all possible triplets (i, j, k).
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn unique_xor_triplets(nums: Vec<i32>) -> i32 {
// All values <= 1500 < 2048 = 2^11
const MAX_VAL: usize = 2048;
let mut s1 = [false; MAX_VAL]; // set of element values
for &v in &nums {
s1[v as usize] = true;
}
// s2 = { a XOR b | a, b in s1 }
let mut s2 = [false; MAX_VAL];
for a in 0..MAX_VAL {
if !s1[a] { continue; }
for b in 0..MAX_VAL {
if !s1[b] { continue; }
s2[a ^ b] = true;
}
}
// s3 = { c XOR e | c in s2, e in s1 }
let mut s3 = [false; MAX_VAL];
for c in 0..MAX_VAL {
if !s2[c] { continue; }
for e in 0..MAX_VAL {
if !s1[e] { continue; }
s3[c ^ e] = true;
}
}
s3.iter().filter(|&&v| v).count() as i32
}
}