Similar Problems

Similar Problems not available

Bitwise Xor Of All Pairings - Leetcode Solution

Companies:

LeetCode:  Bitwise Xor Of All Pairings Leetcode Solution

Difficulty: Medium

Topics: bit-manipulation array  

Problem Description: You are given an array nums of even length n. All possible pairings of the array elements are given as edges of a graph where the vertices are the elements of nums.

A pairing is good if for an edge (a, b), nums[a] XOR nums[b] equals k.

Return the number of good pairings.

Solution: This problem can be solved using a brute force approach, which involves checking every pair of integers in the array. However, this would result in a time complexity of O(n^2), which would be too slow for large inputs.

A more efficient solution involves using a hash map to keep track of the number of times each integer occurs in the array. We can then iterate over the array and for each integer i, we can compute the number of pairs that XOR to k by checking the number of occurrences of k XOR i in the hash map.

Here is the code implementation of this approach:

def countPairs(nums, k): # initialize hashmap to keep track of number of occurrences of each integer hashmap = {} for num in nums: if num in hashmap: hashmap[num] += 1 else: hashmap[num] = 1

# iterate over array and compute number of pairs that XOR to k
count = 0
for num in nums:
    xor = num ^ k
    if xor in hashmap:
        count += hashmap[xor]
        if xor == num:
            count -= 1

return count // 2

In this solution, we first initialize a hash map to keep track of the number of occurrences of each integer in the array. We then iterate over the array and for each integer i, we compute the XOR with the target value k, and check whether the result is in the hash map.

If the XOR is in the hash map, we add the number of occurrences of the XOR to the count. We also subtract 1 from the count if the XOR is equal to the current integer, to avoid counting pairs of an integer with itself.

Finally, we return the count divided by 2, since we have counted each pair twice. This gives us the total number of good pairings.

Time Complexity: The time complexity of this solution is O(n), since we iterate over the array only once, and hash map lookups can be done in constant time. The space complexity is also O(n), since we store all the elements of the array in the hash map.

Bitwise Xor Of All Pairings Solution Code

1