Algo-Sim › Tries

Maximum XOR of Two Numbers in an Array

Medium · Tries · step through it in Java, Python and C++ on your own input

A binary trie of the numbers, highest bit first. For each number, walk down taking the opposite bit whenever it exists: greedy from the top is optimal.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why highest bit first?
A 1 in a higher bit beats any combination of lower bits, so taking the opposite bit greedily from the top is optimal: O(32·n).
What if queries limit the values used?
Sort queries by their limit and insert numbers as the limit grows (offline), or keep the minimum value in each trie node (LC 1707).

Solution

Java

public int findMaximumXOR(int[] nums) {
    int max = Arrays.stream(nums).max().getAsInt();
    int high = 31 - Integer.numberOfLeadingZeros(Math.max(max, 1));
    Node root = new Node();
    for (int num : nums) {
        Node node = root;
        for (int b = high; b >= 0; b--) {
            int bit = (num >> b) & 1;
            if (node.next[bit] == null) node.next[bit] = new Node();
            node = node.next[bit];
        }
    }
    int best = 0;
    for (int num : nums) {
        Node node = root;
        int x = 0;
        for (int b = high; b >= 0; b--) {
            int bit = (num >> b) & 1;
            // A 1 in a higher bit beats every lower bit, so take the opposite bit if it exists.
            if (node.next[1 - bit] != null) {
                x |= 1 << b;
                node = node.next[1 - bit];
            } else node = node.next[bit];
        }
        best = Math.max(best, x);
    }
    return best;
}

static class Node {
    Node[] next = new Node[2];
}

Python

def find_maximum_xor(nums):
    high = max(max(nums), 1).bit_length() - 1
    root = {}
    for num in nums:
        node = root
        for b in range(high, -1, -1):
            bit = (num >> b) & 1
            node = node.setdefault(bit, {})
    best = 0
    for num in nums:
        node, x = root, 0
        for b in range(high, -1, -1):
            bit = (num >> b) & 1
            # A 1 in a higher bit beats every lower bit, so take the opposite bit if it exists.
            if 1 - bit in node:
                x |= 1 << b
                node = node[1 - bit]
            else:
                node = node[bit]
        best = max(best, x)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    struct Node {
        Node *next[2] = {nullptr, nullptr};
    };

  public:
    int findMaximumXOR(vector<int> &nums) {
        int high = __lg(max(*max_element(nums.begin(), nums.end()), 1));
        Node *root = new Node();
        for (int num : nums) {
            Node *node = root;
            for (int b = high; b >= 0; b--) {
                int bit = (num >> b) & 1;
                if (!node->next[bit]) node->next[bit] = new Node();
                node = node->next[bit];
            }
        }
        int best = 0;
        for (int num : nums) {
            Node *node = root;
            int x = 0;
            for (int b = high; b >= 0; b--) {
                int bit = (num >> b) & 1;
                // A 1 in a higher bit beats every lower bit, so take the opposite bit if it exists.
                if (node->next[1 - bit]) {
                    x |= 1 << b;
                    node = node->next[1 - bit];
                } else node = node->next[bit];
            }
            best = max(best, x);
        }
        return best;
    }
};

More Tries problems