Magicsheet logo

Count Pairs With XOR in a Range

Hard
100%
Updated 6/1/2025

Asked by 2 Companies

Count Pairs With XOR in a Range

What is this problem about?

The "Count Pairs With XOR in a Range interview question" is a difficult bitwise problem. You are given an array of non-negative integers and a range [low, high]. You need to count the number of pairs (i,j)(i, j) with i<ji < j such that the bitwise XOR sum nums[i] ^ nums[j] falls within the given range. This problem requires efficient bitwise prefix searching.

Why is this asked in interviews?

Google asks the "Count Pairs With XOR in a Range coding problem" to test a candidate's mastery of the Trie data structure and its application to bitwise operations. It evaluates the ability to solve a "Range" problem by breaking it into two "Prefix" problems (counts for high and low-1) and using a Binary Trie to perform O(extbits)O( ext{bits}) prefix counts. It’s a classic "Hard" level bitwise challenge.

Algorithmic pattern used

This problem follows the Binary Trie and Prefix Search patterns.

  1. The Range Trick: count(low, high) = count(high) - count(low-1), where count(K) is the number of pairs with XOR sum K\leq K.
  2. Trie Construction: Build a Trie where each node stores the count of numbers that pass through it. Each bit of a number (from most significant to least) defines a path.
  3. Counting K\leq K: For each number x in the array:
    • Traverse the Trie bit by bit.
    • At each bit ii, if the ithi^{th} bit of KK is 1:
      • If we XOR x with the branch that matches x's bit, the XOR result at this bit is 0. Since 0<10 < 1, all numbers in this branch satisfy the condition. Add their pre-calculated count.
      • Move down the other branch (XOR result 1) to check further bits.
    • If the ithi^{th} bit of KK is 0:
      • You must move down the branch that matches x's bit (XOR result 0).
  4. Iterative Update: Add the number to the Trie after counting to ensure i<ji < j.

Example explanation

Numbers: [1, 4, 2, 7], K=3K = 3.

  • Insert 1 into Trie.
  • For 4: Find numbers y in Trie such that 4 ^ y <= 3.
    • 4 is 100, 1 is 001. 4 ^ 1 = 101 (5). 5>35 > 3. Count = 0.
  • Insert 4 into Trie.
  • For 2: 2 ^ 1 = 3. 333 \leq 3. OK. 2 ^ 4 = 6. 6>36 > 3. NO. Count = 1. Total pairs: 1.

Common mistakes candidates make

  • O(N2)O(N^2) Brute Force: Trying all pairs, which is too slow.
  • Trie Depth: Not processing enough bits (usually 15-16 bits for constraints up to 2imes1042 imes 10^4).
  • Logic Errors in Trie Traversal: Mismanaging the "less than" condition when a bit in KK is 1.

Interview preparation tip

Practice using Tries for bitwise problems. If a problem asks about "XOR" and "Count" or "Range," a Binary Trie is almost always the required "Trie interview pattern" solution.

Similar Questions