Maximum Xor

  • + 1 comment

    Accidentally deleted my first post. Thanks so much for your help, helped me solve this in two hours and I knew nothing of Tries before hand! Not sure why this is formatting incorrectly, but I fixed it (kinda) with p tags

    // Class I use to construct the Trie:

    class BinTrie:

    head = {}

    def add(self, integer):
        cur = self.head
        b = "{:032b}".format(integer)
    
        for l in b:
            l = int(l)
            if l not in cur:
                cur[l] = {}
            cur = cur[l]
        cur['*'] = True
    
    def max_companion(self, integer):
        cur = self.head
        b = "{:032b}".format(integer)
        m_comp = ''
    
        for l in b:
            l = int(l)
            opp = l ^ 1
            if opp in cur:
                l = opp
            cur = cur[l]
            m_comp += str(l)
        return int(m_comp, 2)
    

    def maxXor(arr, queries):

    d = BinTrie()

    out = []

    for x in arr:

    d.add(x)

    for v in queries:

    out.append(v ^ d.max_companion(v))

    return out