<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,10,5,25,2,8]
<strong>Output:</strong> 28
<strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70]
<strong>Output:</strong> 127
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        from collections import defaultdict

        nums = sorted(set(nums), reverse=True)
        if len(nums) == 1:
            return 0

        def get_first_bit(n):
            b = 0
            while n > 0:
                n >>= 1
                b += 1
            return b
        
        while True:
            first_bit = get_first_bit(nums[0])

            group1 = []
            group2 = []
            for n in nums:
                if get_first_bit(n) == first_bit:
                    group1.append(n)
                else:
                    group2.append(n)
            if group2:
                break
            for i in range(len(nums)):
                nums[i] ^= 1 << first_bit - 1
        
        bit_to_nums = defaultdict(set)
        for n in nums:
            for i in range(first_bit):
                if (1 << i) & n:
                    bit_to_nums[(i, 1)].add(n)
                else:
                    bit_to_nums[(i, 0)].add(n)

        max_value = 0

        def walk(group1, group2, bit):
            nonlocal max_value
            if len(group1) == 0 or len(group2) == 0:
                return
            if len(group1) == 1 and len(group2) == 1:
                value = group1[0] ^ group2[0]
                if value > max_value:
                    max_value = value
                return
            group1_0 = []
            group1_1 = []
            group2_0 = []
            group2_1 = []
            for n in group1:
                if n in bit_to_nums[(bit, 0)]:
                    group1_0.append(n)
                else:
                    group1_1.append(n)
            for n in group2:
                if n in bit_to_nums[(bit, 0)]:
                    group2_0.append(n)
                else:
                    group2_1.append(n)
            walk(group1_0, group2_1, bit - 1)
            walk(group1_1, group2_0, bit - 1)
            if not group1_1 and not group2_1:
                walk(group1_0, group2_0, bit - 1)
            elif not group1_0 and not group2_0:
                walk(group1_1, group2_1, bit - 1)
        
        walk(group1, group2, first_bit)
        return max_value

253884