Skip to content

Commit 5db2a90

Browse files
authored
Create P06_SubarraysWithGivenXor.py
1 parent 3cfcdf2 commit 5db2a90

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Arrays/P06_SubarraysWithGivenXor.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def subarrays_with_given_XOR(arr, n, m):
2+
prefix_xor = 0
3+
4+
d = {0: 1} # initialise dictionary, d stores count 'xor values' in arr
5+
for i in range(n):
6+
prefix_xor ^= arr[i]
7+
if prefix_xor in d:
8+
d[prefix_xor] += 1
9+
else:
10+
d[prefix_xor] = 1
11+
12+
# Approach :
13+
# We know that, If A^B = C, then: A^C=B and B^C=A,
14+
15+
# In this problem :-
16+
17+
# val ^ givenXor = C
18+
# givenXor ^ c = a
19+
# val ^ c = givenXor
20+
# So, if val and val^givenXor=C is in d, then "givenXor" is in d.
21+
22+
23+
cnt = 0
24+
for val in d:
25+
if val^m in d:
26+
cnt += d[val] * d[val^m]
27+
d[e] = 0
28+
d[val^m] = 0
29+
return cnt
30+
31+
32+
arr = [4, 2, 2, 6, 4]
33+
xor = 6
34+
print(subarrays_with_given_XOR(arr, len(arr), xor))

0 commit comments

Comments
 (0)