Magicsheet logo

Number of Perfect Pairs

Medium
37.5%
Updated 8/1/2025

Number of Perfect Pairs

What is this problem about?

The Number of Perfect Pairs problem defines a "perfect pair" as two indices (i, j) where i < j and arr[i]^arr[j] == arr[i] + arr[j]. The XOR equals the sum only when there's no carry in binary addition — meaning no bit position has 1s in both numbers. This is equivalent to arr[i] & arr[j] == 0. Count all such pairs. This coding problem uses sorting with two pointers or hash map counting.

Why is this asked in interviews?

Goldman Sachs and Squarepoint Capital ask this because it requires recognizing the mathematical condition a XOR b == a + b ⟺ a AND b == 0. Once this insight is recognized, pair counting with a hash map or sorting is straightforward. The array, math, sorting, and two pointers interview pattern is applied.

Algorithmic pattern used

Hash map frequency counting. For each pair (a, b) where a & b == 0, count them as a perfect pair. For each element a, count elements b where (a & b) == 0. A simple O(n²) check works for small inputs. For larger inputs, iterate over all possible complements. Use frequency map to count pairs efficiently.

Example explanation

Array: [1,2,4,8]. Binary: 0001, 0010, 0100, 1000.

  • (1,2): 01&10=0 ✓. Perfect pair.
  • (1,4): 01&100=0 ✓. Perfect pair.
  • (1,8): ✓. (2,4): ✓. (2,8): ✓. (4,8): ✓. All 6 pairs are perfect since they all have no common bits. Answer = 6.

Array: [1,3,5]: 1&3=01&11=01≠0. 1&5=001&101=001≠0. 3&5=011&101=001≠0. Answer = 0.

Common mistakes candidates make

  • Not recognizing a XOR b == a + b implies a AND b == 0.
  • Naive O(n²) approach TLEs on large inputs.
  • Counting ordered pairs (i,j) and (j,i) separately when problem asks for i<j.
  • Off-by-one in pair enumeration.

Interview preparation tip

The identity a XOR b == a + b ⟺ a AND b == 0 is a key bit manipulation insight — XOR represents addition without carry, so no carry ⟺ no common bits. Memorize this equivalence. For counting pairs with a & b == 0, sort the array and use the "submask enumeration" technique for high-performance solutions on larger inputs. Practice converting XOR/sum conditions to AND conditions systematically.

Similar Questions