Maximum XOR of Two Numbers in an Array using Trie

 Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.


 


Example 1:


Input: nums = [3,10,5,25,2,8]

Output: 28

Explanation: The maximum result is 5 XOR 25 = 28.

Example 2:


Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]

Output: 127


// Trie node to store binary representation (0 or 1)
class TriesNode {
    TriesNode[] child = new TriesNode[2]; // child[0] and child[1]
}

class Solution {

    TriesNode root = new TriesNode(); // root of Trie

    // Insert number into Trie
    public void insert(int num) {
        TriesNode curr = root;
        for (int i = 31; i >= 0; i--) { // 32-bit integer
            int bit = (num >> i) & 1; // extract i-th bit
            if (curr.child[bit] == null) {
                curr.child[bit] = new TriesNode(); // create if not exists
            }
            curr = curr.child[bit]; // move to next bit
        }
    }

    //  Compute max XOR for this num using Trie
    public int getMaxXor(int num) {
        TriesNode current = root;
        int maxxor = 0;

        for (int i = 31; i >= 0; i--) {
            int bit = (num >> i) & 1; // extract i-th bit
            int opposite = 1 - bit;   // find opposite bit

            // Prefer opposite bit for higher XOR
            if (current.child[opposite] != null) {
                maxxor |= (1 << i); // set i-th bit in result
                current = current.child[opposite]; // move in opposite path
            } else {
                current = current.child[bit]; // fallback to same bit
            }
        }
        return maxxor;
    }

    //  Main function to find max XOR
    public int findMaximumXOR(int[] nums) {
        // Step 1: Build Trie
        for (int n : nums) {
            insert(n);
        }

        // Step 2: Traverse and get max XOR
        int max = 0;
        for (int num : nums) {
            max = Math.max(max, getMaxXor(num));
        }

        return max;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence