KatInterview

421. Maximum XOR of Two Numbers in an Array

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum XOR (exclusive OR) result of any two numbers in a given array nums. A brute-force approach would be to check every pair of numbers, which would take O(N^2) time. Given the constraint N can be up to 2 * 10^5, an O(N^2) solution is too slow. We need a more efficient approach, likely one with O(N) or O(N log N) time complexity. This suggests a solution that leverages the bitwise nature of the XOR operation.

Solution

Maximum XOR of Two Numbers in an Array in Python

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        # The highest bit for a 32-bit integer is 30 (since it's 0-indexed).
        # The max value is 2^31 - 1.
        L = 30
        
        # Trie is represented as a nested dictionary.
        trie = {}

        # 1. Build the Trie with all numbers.
        for num in nums:
            node = trie
            for i in range(L, -1, -1):
                bit = (num >> i) & 1
                if bit not in node:
                    node[bit] = {}
                node = node[bit]
        
        max_xor = 0
        # 2. For each number, find the maximum XOR by traversing the Trie.
        for num in nums:
            node = trie
            current_xor = 0
            for i in range(L, -1, -1):
                bit = (num >> i) & 1
                # To maximize XOR, we look for the opposite bit.
                opposite_bit = 1 - bit
                
                if opposite_bit in node:
                    # If the ideal opposite bit exists, we take that path.
                    # This contributes a '1' to the XOR result at this position.
                    current_xor |= (1 << i)
                    node = node[opposite_bit]
                else:
                    # Otherwise, we must take the path of the same bit.
                    # This contributes a '0' to the XOR result.
                    node = node[bit]
            
            max_xor = max(max_xor, current_xor)
            
        return max_xor

Maximum XOR of Two Numbers in an Array in Java

class Solution {
    // Inner class for TrieNode
    class TrieNode {
        TrieNode[] children;
        public TrieNode() {
            children = new TrieNode[2]; // 0 and 1
        }
    }

    public int findMaximumXOR(int[] nums) {
        TrieNode root = new TrieNode();
        int L = 30; // Max bit position for numbers up to 2^31 - 1

        // 1. Build the Trie with all numbers
        for (int num : nums) {
            TrieNode curr = root;
            for (int i = L; i >= 0; i--) {
                int bit = (num >> i) & 1;
                if (curr.children[bit] == null) {
                    curr.children[bit] = new TrieNode();
                }
                curr = curr.children[bit];
            }
        }

        int maxXor = 0;
        // 2. For each number, find the maximum XOR value by traversing the Trie
        for (int num : nums) {
            TrieNode curr = root;
            int currentXor = 0;
            for (int i = L; i >= 0; i--) {
                int bit = (num >> i) & 1;
                // We want to find the opposite bit to maximize XOR
                int oppositeBit = 1 - bit;

                if (curr.children[oppositeBit] != null) {
                    // If the opposite bit exists, we take that path
                    // and add 1 to the currentXor at this bit position.
                    currentXor |= (1 << i);
                    curr = curr.children[oppositeBit];
                } else {
                    // Otherwise, we have to take the path of the same bit.
                    // The XOR result for this bit will be 0.
                    curr = curr.children[bit];
                }
            }
            maxXor = Math.max(maxXor, currentXor);
        }

        return maxXor;
    }
}

Maximum XOR of Two Numbers in an Array in C++

class Solution {
private:
    // TrieNode structure for binary representation of numbers
    struct TrieNode {
        TrieNode* children[2];
        TrieNode() {
            children[0] = nullptr;
            children[1] = nullptr;
        }
    };

public:
    int findMaximumXOR(vector<int>& nums) {
        TrieNode* root = new TrieNode();
        int L = 30; // Max bit position for numbers up to 2^31 - 1

        // 1. Build the Trie with all numbers
        for (int num : nums) {
            TrieNode* curr = root;
            for (int i = L; i >= 0; --i) {
                int bit = (num >> i) & 1;
                if (curr->children[bit] == nullptr) {
                    curr->children[bit] = new TrieNode();
                }
                curr = curr->children[bit];
            }
        }

        int maxXor = 0;
        // 2. For each number, find the maximum XOR value by traversing the Trie
        for (int num : nums) {
            TrieNode* curr = root;
            int currentXor = 0;
            for (int i = L; i >= 0; --i) {
                int bit = (num >> i) & 1;
                // We want to find the opposite bit to maximize XOR
                int oppositeBit = 1 - bit;

                if (curr->children[oppositeBit] != nullptr) {
                    // If the opposite bit exists, we take that path
                    // and add 1 to the currentXor at this bit position.
                    currentXor |= (1 << i);
                    curr = curr->children[oppositeBit];
                } else {
                    // Otherwise, we have to take the path of the same bit.
                    // The XOR result for this bit will be 0.
                    curr = curr->children[bit];
                }
            }
            maxXor = max(maxXor, currentXor);
        }
        
        // Note: Memory for the Trie should be freed in a real-world scenario, 
        // but it's often omitted in competitive programming.
        return maxXor;
    }
};

Maximum XOR of Two Numbers in an Array in TypeScript

function findMaximumXOR(nums: number[]): number {
    // TrieNode class to represent nodes in the binary Trie
    class TrieNode {
        children: Map<number, TrieNode>;
        constructor() {
            this.children = new Map(); // Using Map for children (0 or 1)
        }
    }

    const root = new TrieNode();
    const L = 30; // Max bit position for numbers up to 2^31 - 1

    // 1. Build the Trie with all numbers
    for (const num of nums) {
        let curr = root;
        for (let i = L; i >= 0; i--) {
            const bit = (num >> i) & 1;
            if (!curr.children.has(bit)) {
                curr.children.set(bit, new TrieNode());
            }
            curr = curr.children.get(bit)!;
        }
    }

    let maxXor = 0;
    // 2. For each number, find the maximum XOR value by traversing the Trie
    for (const num of nums) {
        let curr = root;
        let currentXor = 0;
        for (let i = L; i >= 0; i--) {
            const bit = (num >> i) & 1;
            // We want to find the opposite bit to maximize XOR
            const oppositeBit = 1 - bit;

            if (curr.children.has(oppositeBit)) {
                // If the opposite bit exists, we take that path
                // and add 1 to the currentXor at this bit position.
                currentXor |= (1 << i);
                curr = curr.children.get(oppositeBit)!;
            } else {
                // Otherwise, we have to take the path of the same bit.
                // The XOR result for this bit will be 0.
                curr = curr.children.get(bit)!;
            }
        }
        maxXor = Math.max(maxXor, currentXor);
    }

    return maxXor;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.