Maximum Xor

  • + 0 comments

    Python solution O(30*n+30*m) - time, O(30*n) - space for the trie of bits prefixes:

    def maxXor(arr, queries):
        trie = dict()
        cur = trie
        #build a trie of numbers' bits prefixes
        for a in arr:
            for bit in map(int, bin(a)[2:].zfill(30)):
                if bit not in cur:
                    cur[bit] = {}
                cur = cur[bit]
            cur = trie
        
        rez = []
        #given a trie of bits prefixes and a query, do a greedy search on it
        for q in queries:
            sub_rez = ''
            for bit in map(int, bin(q)[2:].zfill(30)):
                if 1 - bit in cur:
                    sub_rez += '1'
                    cur = cur[1 - bit]
                else:
                    sub_rez += '0'
                    cur = cur[bit]
            rez.append(int(sub_rez, 2))
            cur = trie
        return rez