Program to count pairs with XOR in a range in Python


Suppose we have an array nums and have two values l and r, we have to find the number of nice pairs. Here a nice pair is a pair (i, j) where 0 <= i < j < size of nums and l <= (nums[i] XOR nums[j]) <= r.

So, if the input is like nums = [4,1,7,2] l = 2 r = 6, then the output will be 6 because the nice pairs are (1,0): 1 XOR 4 = 5, (1,2): 1 XOR 7 = 6, (1,3): 1 XOR 2 = 3, (0,3): 4 XOR 2 = 6, (0,2): 4 XOR 7 = 3, (2,3): 7 XOR 2 = 5.

To solve this, we will follow these steps −

  • Define a function test() . This will take nums, x

  • count := a map containing frequency of elements in nums

  • res := 0

  • while x is non-zero, do

    • if x is odd, then

      • res := res + sum of all elements of (count[a] * count[(x - 1) XOR a) for all a in count

    • count := map with key a/2 and value (count[a] + count[a XOR 1] for all a in count

    • x = quotient of x/2

  • return quotient of res / 2

  • From the main method return test(nums, r + 1) - test(nums, l)

Example

Let us see the following implementation to get better understanding

from collections import Counter
def solve(nums, l, r):
   def test(nums, x):
      count = Counter(nums)
      res = 0
      while x:
         if x & 1:
            res += sum(count[a] * count[(x - 1) ^ a] for a in count)
         count = Counter({a >> 1: count[a] + count[a ^ 1] for a in count})
         x >>= 1
      return res // 2

   return test(nums, r + 1) - test(nums, l)

nums = [4,1,7,2]
l = 2
r = 6
print(solve(nums, l, r))

Input

[4,1,7,2], 2, 6

Output

6

Updated on: 08-Oct-2021

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements