#1835
Find XOR Sum of All Pairs Bitwise AND
HardArrayMathBit ManipulationBit ManipulationXOR Properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of calculating the AND for every pair, we can leverage the properties of XOR and AND operations. By recognizing that the XOR of AND results can be simplified, we can reduce the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to hold the XOR sum of all elements in arr2.
- 2Step 2: Calculate the XOR of all elements in arr2 and store it in a variable, say xor_arr2.
- 3Step 3: Initialize a variable to hold the final result as 0.
- 4Step 4: Iterate through each element in arr1, and for each element, compute the AND with xor_arr2, then XOR this result into the final result.
- 5Step 5: Return the final result.
solution.py10 lines
1# Full working Python code
2arr1 = [1, 2, 3]
3arr2 = [6, 5]
4xor_arr2 = 0
5for b in arr2:
6 xor_arr2 ^= b
7result = 0
8for a in arr1:
9 result ^= (a & xor_arr2)
10print(result)ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through arr2 to compute the XOR and then another pass through arr1. The space complexity is O(1) as we only use a few extra variables.
- 1Understanding bitwise operations can lead to significant optimizations.
- 2Recognizing patterns in how XOR and AND interact can simplify complex problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.