I'm trying to solve this hackerrank problem https://www.hackerrank.com/challenges/xor-subsequence/problem
from functools import reduce
def xor_sum(arr):
return reduce(lambda x,y: x^y, arr)
def xorSubsequence(arr):
freq = {}
max_c = float("-inf") # init val
min_n = float("inf") # init val
for slice_size in range(1, len(arr)+1):
for step in range(0, len(arr)+1-slice_size):
n = xor_sum(arr[i] for i in range(step,step+slice_size))
freq[n] = freq.get(n,0)+1
if freq[n] >= max_c and (n < min_n or freq[n]> max_c):
min_n = n
max_c = freq[n]
return min_n, freq[min_n]
But it times out since it's ~O(n^3). I feel like there is some math trick, can someone explain the solution to me? I tried to read some solutions in the discussion but I didn't quite get them.
Problem copy:
Consider an array, A, of n integers (A=a0,a1,...,a0). We take all consecutive subsequences of integers from the array that satisfy the following:
{ai,ai+1,...,aj-1,aj}, where 0≤i≤j≤nFor each subsequence, we apply the bitwise XOR (⊕) operation on all the integers and record the resultant value.
Given array A, find the XOR sum of every subsequence of A and determine the frequency at which each number occurs. Then print the number and its respective frequency as two space-separated values on a single line.
Output Format
Print 2 space-separated integers on a single line. The first integer should be the number having the highest frequency, and the second integer should be the number's frequency (i.e., the number of times it appeared). If there are multiple numbers having maximal frequency, choose the smallest one.
Constraints
• 1≤n≤105
• 1≤ai<216
