Skip to content

Commit d1ed34b

Browse files
Add Sliding_Window_XOR working solution
1 parent a71618f commit d1ed34b

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Author : Abhiraj Mandal
3+
Date : October 3, 2025
4+
5+
This is a pure Python implementation to calculate the cumulative XOR of all
6+
sliding windows of size k in an array generated via a linear recurrence.
7+
8+
The problem is :
9+
Given parameters n, k, x, multiplier, increment, modulo, generate an array:
10+
arr[0] = x
11+
arr[i] = (multiplier * arr[i-1] + increment) % modulo
12+
Compute the XOR of each window of size k, and cumulatively XOR all windows.
13+
"""
14+
15+
16+
class SlidingWindowXOR:
17+
"""
18+
Use:
19+
solver = SlidingWindowXOR()
20+
result = solver.compute(n, k, x, multiplier, increment, modulo)
21+
"""
22+
23+
def compute(self, n: int, k: int, x: int, multiplier: int,
24+
increment: int, modulo: int) -> int:
25+
"""
26+
Compute cumulative XOR of all sliding windows of size k.
27+
28+
>>> SlidingWindowXOR().compute(5, 2, 1, 1, 1, 100)
29+
0
30+
>>> SlidingWindowXOR().compute(2, 1, 2, 3, 4, 5)
31+
2
32+
"""
33+
# Generate the array using recurrence
34+
arr = [0] * n
35+
arr[0] = x
36+
for i in range(1, n):
37+
arr[i] = (multiplier * arr[i - 1] + increment) % modulo
38+
39+
x1 = 0 # XOR of current window
40+
x2 = 0 # cumulative XOR of all windows
41+
left = 0
42+
43+
for right in range(n):
44+
x1 ^= arr[right] # include current element
45+
if right - left + 1 > k:
46+
x1 ^= arr[left] # remove leftmost element
47+
left += 1
48+
if right - left + 1 == k:
49+
x2 ^= x1
50+
51+
return x2
52+
53+
54+
if __name__ == "__main__":
55+
solver = SlidingWindowXOR()
56+
57+
print("************ Testing Sliding Window XOR Algorithm ************\n")
58+
59+
# Example testcases
60+
test_cases = [
61+
(100, 20, 3, 7, 1, 997, 1019),
62+
(2, 1, 2, 3, 4, 5, 2),
63+
(5, 2, 1, 1, 1, 100, 4),
64+
(3, 5, 5, 2, 1, 100, 0),
65+
(4, 4, 3, 1, 0, 10, 0)
66+
]
67+
68+
for idx, (n, k, x, m, inc, mod, expected) in enumerate(test_cases, 1):
69+
result = solver.compute(n, k, x, m, inc, mod)
70+
print(f"Testcase {idx}: Expected={expected}, Got={result}")
71+
assert result == expected, f"Testcase {idx} failed!"
72+
73+
print("\nAll test cases successfully passed!")
74+
print("********** End of Testing Sliding Window XOR Algorithm **********")

0 commit comments

Comments
 (0)