Skip to content

Commit 0cc33a3

Browse files
authored
Update 1803-count-pairs-with-xor-in-a-range.js
1 parent 8caa8cb commit 0cc33a3

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

1803-count-pairs-with-xor-in-a-range.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,51 @@ class Trie {
4444
return ans
4545
}
4646
}
47+
48+
49+
// another
50+
51+
/**
52+
* @param {number[]} nums
53+
* @param {number} low
54+
* @param {number} high
55+
* @return {number}
56+
*/
57+
const countPairs = function(nums, low, high) {
58+
let res = 0, n = nums.length, trie = { cnt: 0 }
59+
for(const e of nums) {
60+
res += helper(e, high + 1) - helper(e, low)
61+
insert(e)
62+
}
63+
return res
64+
65+
function helper(e, limit) {
66+
let res = 0, cur = trie
67+
for(let i = 14; i >= 0; i--) {
68+
const a = (e >> i) & 1
69+
const b = (limit >> i) & 1
70+
if(cur == null) break
71+
if(b === 0) {
72+
cur = cur[a]
73+
continue
74+
}
75+
if(cur[a]) {
76+
res += cur[a].cnt
77+
}
78+
cur = cur[1 - a]
79+
}
80+
81+
return res
82+
}
83+
84+
function insert(e) {
85+
let cur = trie
86+
for(let i = 14; i >= 0; i--) {
87+
const tmp = (e >> i) & 1
88+
if(!(tmp in cur)) cur[tmp] = {cnt:0}
89+
cur[tmp].cnt++
90+
cur = cur[tmp]
91+
}
92+
}
93+
94+
};

0 commit comments

Comments
 (0)