Cheese with Holes (Emmental) - Developing
Cheese with Holes (Emmental) - Developing
Useful note with basic structure, but still has holes to fill.
Click the cheese icon to learn more

Minimum XOR

Author: guiferviz Created: Last Modified:

Given a list of numbers, identify the pair of numbers that results in the smallest XOR value.

Solution 1: Sorting

Finding the pair of numbers with the minimum XOR value can be done in nlog(n)n \cdot log(n). This can be achieved by first sorting the list of numbers and then comparing the XOR of each consecutive pair in the sorted list. When numbers are sorted, consecutive numbers are closer in value compared to non-consecutive numbers. This closeness often results in a smaller XOR value because XOR tends to produce smaller results when the binary representations of the numbers are similar.

Code

Solution 2: Trie

Using a trie (prefix tree) is another efficient approach to solve the problem of finding the pair of numbers with the minimum XOR value. A binary trie can be constructed where each path from the root to a leaf node represents the binary representation of a number. By inserting all numbers into the trie, we can then find the minimum XOR for each number by traversing the trie in a way that tries to match the same bits first (to minimize the XOR result).

This method can be more efficient than sorting for large datasets, especially when the range of numbers is limited, as it can achieve a time complexity of O(nb)O(n \cdot b), where bb is the number of bits required to represent the numbers.

Code

Note Connections

© 2026 Cheese 🧀 Bytes