Count Pairs With XOR in a Range - Problem

Given a 0-indexed integer array nums and two integers low and high, return the number of nice pairs.

A nice pair is a pair (i, j) where:

  • 0 <= i < j < nums.length
  • low <= (nums[i] XOR nums[j]) <= high

The XOR operation computes the bitwise exclusive OR of two numbers.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,2,7], low = 1, high = 4
Output: 2
💡 Note: Nice pairs are (0,2): 1^2=3 ∈ [1,4] and (1,3): 4^7=3 ∈ [1,4]. Total count is 2.
Example 2 — Wider Range
$ Input: nums = [9,8,4,2,1], low = 5, high = 14
Output: 8
💡 Note: Multiple pairs have XOR values in [5,14]: (0,1): 9^8=1 ✗, (0,2): 9^4=13 ✓, (0,3): 9^2=11 ✓, etc. Count all valid pairs.
Example 3 — No Valid Pairs
$ Input: nums = [1,1,1], low = 5, high = 10
Output: 0
💡 Note: All pairs have XOR = 1^1 = 0, which is not in range [5,10]. No nice pairs exist.

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • 1 ≤ nums[i] ≤ 2 × 104
  • 1 ≤ low ≤ high ≤ 2 × 104

Visualization

Tap to expand
Count Pairs With XOR in Range [1,4]1427i=0i=1i=2i=3(0,1): 1^4=5(0,2): 1^2=3 ✓(0,3): 1^7=6(1,2): 4^2=6(1,3): 4^7=3 ✓(2,3): 2^7=5Count: 2
Understanding the Visualization
1
Input
Array nums=[1,4,2,7] and range [1,4]
2
Find Pairs
Check all pairs (i,j) where i<j for XOR in range
3
Count Valid
Count pairs with XOR ∈ [1,4]: result is 2
Key Takeaway
🎯 Key Insight: Use trie data structure to efficiently count XOR values in ranges without checking all pairs
Asked in
Google 35 Amazon 28 Microsoft 22
38.5K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen