Problem 450943 · hard · Level 04 Non-Linear Data Structures

Two Badge Codes That Differ the Most

trie · bit manipulation · greedy

Every security badge stores a non-negative integer code, listed in nums. XOR-ing two codes marks the bits where they disagree, and a bigger result means they disagree in higher bits. Return the largest nums[i] XOR nums[j] over all pairs of different positions i != j, or 0 if there are fewer than two badges.

Examples

Input:  nums = [4, 9, 22, 13, 2]
Output: 31
Explanation: 9 XOR 22 = 31 (01001 XOR 10110 = 11111).

Input:  nums = [8, 1, 2, 12, 7, 6]
Output: 15

Constraints

  • 0 <= len(nums) <= 2 * 10**4
  • 0 <= nums[i] < 2**31
  • Target: O(n * 31); the O(n**2) pairwise check is too slow for the largest tests

Goals

  • Store integers bit by bit in a binary trie
  • Greedily prefer the opposite bit from the most significant position down
Starting Python…