|
| 1 | +/** |
| 2 | + * 1707. Maximum XOR With an Element From Array |
| 3 | + * https://leetcode.com/problems/maximum-xor-with-an-element-from-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array nums consisting of non-negative integers. You are also given a queries |
| 7 | + * array, where queries[i] = [xi, mi]. |
| 8 | + * |
| 9 | + * The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that |
| 10 | + * does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that |
| 11 | + * nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. |
| 12 | + * |
| 13 | + * Return an integer array answer where answer.length == queries.length and answer[i] is the |
| 14 | + * answer to the ith query. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} nums |
| 19 | + * @param {number[][]} queries |
| 20 | + * @return {number[]} |
| 21 | + */ |
| 22 | +var maximizeXor = function(nums, queries) { |
| 23 | + nums.sort((a, b) => a - b); |
| 24 | + const sortedQueries = queries.map((q, i) => [q[0], q[1], i]).sort((a, b) => a[1] - b[1]); |
| 25 | + const result = new Array(queries.length).fill(-1); |
| 26 | + |
| 27 | + const trie = {}; |
| 28 | + let numIndex = 0; |
| 29 | + |
| 30 | + for (const [x, m, queryIndex] of sortedQueries) { |
| 31 | + while (numIndex < nums.length && nums[numIndex] <= m) { |
| 32 | + let node = trie; |
| 33 | + for (let bit = 30; bit >= 0; bit--) { |
| 34 | + const bitValue = (nums[numIndex] >> bit) & 1; |
| 35 | + if (!node[bitValue]) node[bitValue] = {}; |
| 36 | + node = node[bitValue]; |
| 37 | + } |
| 38 | + numIndex++; |
| 39 | + } |
| 40 | + |
| 41 | + if (numIndex === 0) continue; |
| 42 | + |
| 43 | + let maxXor = 0; |
| 44 | + let node = trie; |
| 45 | + for (let bit = 30; bit >= 0; bit--) { |
| 46 | + const bitValue = (x >> bit) & 1; |
| 47 | + const oppositeBit = bitValue ^ 1; |
| 48 | + if (node[oppositeBit]) { |
| 49 | + maxXor |= (1 << bit); |
| 50 | + node = node[oppositeBit]; |
| 51 | + } else { |
| 52 | + node = node[bitValue]; |
| 53 | + } |
| 54 | + } |
| 55 | + result[queryIndex] = maxXor; |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +}; |
0 commit comments