-2

Given an array of integers P = [P1, P2, ...] and a function F(M) that returns the XOR of all integers present in set M. If M is empty, then F(M) = 0.

The task is to find the maximum possible value of the expression N XOR F(M) over all possible subsets M of P. Here, N is an integer given to us as an input.

Formally, find the value of max(N XOR F(M)), where M is a subset of P and N can be any integer that is less than or equal to 1000.

Example: 

Sample Input:
N = 4
P = [1, 2, 3]
Numofintegers = 3

Sample Output :
7

Constraints :
Pi <= 1000
Number of integers <= 1000
N <= 1000

Need an optimized solution for this preferably in Python

I used this approach to solve this but the complexity is too bad - O(2 ^ N) with brute force

from itertools import combinations
def find_max_xor(N,P):
    # find the maximum XOR value
    comb = []

    for i in range(len(P) + 1):
        comb += [list(j) for j in combinations([1,2,3], i)]

    arr = []
    for i in comb:
        if len(i):
            res = 0
            for l in range(len(i)):
                res ^= i[l]
            arr.append(N ^ res)
    return max(arr)

n = 4
p = [1,2,3]
# numIntegers = 3
result = find_max_xor(n,p)
print("result : ", result)

1 Answers1

1

Simple one, which in the worst case takes at most ~0.1 seconds:

def find_max_xor(N, P):
    xors = {N}
    for p in P:
        xors |= {xor ^ p for xor in xors}
    return max(xors)

Benchmark

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • 1
    That one doesn't have a quadratic runtime. In the worst case the set `xors` doubles every iteration. So the set can/will have exponential many values in it. However if all numbers are smaller than some constant T, then the runtime is O(T * S), where S is the size of P. – Jakube Mar 24 '23 at 15:00
  • @Jakube Right, I removed that. I guess I took it as not a coincidence that the limits for T and S are the same, and with T=S, it's quadratic in that. – Kelly Bundy Mar 24 '23 at 15:14
  • That doubling is btw why my test case starts with powers of 2, so we quickly reach the maximum set size, making it a worst case. But with the numbers being limited to ≤1000, doubling can happen only ten times. – Kelly Bundy Mar 24 '23 at 15:21
  • @KellyBundy My bad. I have edited the question. Here, N is an integer and not the length of the array. – Niul Panvalkar Mar 24 '23 at 16:03
  • @NiulPanvalkar OK, thanks. Doesn't affect my answer, so would've been more appropriate to reply under my comment under the question. (If you reply under an answer instead, that makes it look like the answer needs to adjust to the change.) – Kelly Bundy Mar 24 '23 at 16:13