Engineering platform~30 min2s · 256 MBtarget O((n + m) × 20) time, O(n × 20) spaceclassic twin: lc-421trie · bit-manipulation
A platform team compares two releases of a service. Every build has a fingerprint, a number whose bits record which features and settings it contains. Two builds that differ in many high bits differ in important ways.
The team scores a pair of builds, one from the old release and one from the new release, by the xor of their fingerprints. A pair that differs in a higher bit scores more than any pair that differs only in lower bits. Find the highest score.
Write max_xor_across(old_builds, new_builds).
old_builds and new_builds are lists of fingerprints, whole numbers from 0 to 10^6. Neither list is empty.Input: old_builds = [3, 10, 5, 25], new_builds = [8, 2, 14]
Output: 27Build a trie of the old fingerprints, one level for each bit from the highest down. For each new fingerprint, walk down and prefer the child with the opposite bit. Only the last five bits matter here, since the higher bits are all 0.
| New build | Best old build | Walk (opposite bit found?) | Xor |
|---|---|---|---|
| 8 (01000) | 25 | opposite at bits 4, 3, 2, 1 and 0 as far as 25 allows | 17 |
| 2 (00010) | 25 | bit 4: yes, bit 3: yes, bit 2: no, bit 1: yes, bit 0: yes | 27 |
| 14 (01110) | 25 | bit 4: yes, bit 3: no, bit 2: no, bit 1: yes, bit 0: yes | 23 |
The best score is 27, from 25 and 2.
Input: old_builds = [7], new_builds = [7]
Output: 0The only pair is equal, so the xor is 0.
Input: old_builds = [1024], new_builds = [0]
Output: 1024The only pair differs in bit 10, so the score is 1024. A method that looks at only 10 bits would miss it.
1 ≤ len(old_builds), len(new_builds) ≤ 20,0000 ≤ every fingerprint ≤ 10^6, so 20 bits are enoughTrying every pair costs 20,000 × 20,000 = 400 million xor operations. That is too slow for a limit of two seconds.
Every fingerprint has 20 bits. Walking a trie takes one step for each bit, so 40,000 numbers cost under a million steps.