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 a Range INPUT nums array: 1 i=0 4 i=1 2 i=2 7 i=3 Constraints: low = 1, high = 4 All XOR pairs: 1 XOR 4 = 5 1 XOR 2 = 3 1 XOR 7 = 6 4 XOR 2 = 6 4 XOR 7 = 3 2 XOR 7 = 5 Green = Valid (1 to 4) ALGORITHM STEPS 1 Build Trie Structure Store binary of each num 2 Count XOR less than K Helper function for range 3 Apply Range Formula count(high+1) - count(low) 4 Sum Valid Pairs Traverse trie for each num Binary Trie: R 0 1 Bits stored at each level FINAL RESULT Valid Pairs Found: Pair (0, 2): nums[0] XOR nums[2] 1 XOR 2 = 3 [OK] Pair (1, 3): nums[1] XOR nums[3] 4 XOR 7 = 3 [OK] Both satisfy: 1 <= XOR <= 4 OUTPUT 2 2 nice pairs found! Time: O(n * log(max)) Key Insight: Using a Trie (prefix tree) allows efficient counting of XOR values in a range. The trick is to use count(XOR < high+1) - count(XOR < low) to find pairs in [low, high]. Each number's binary representation is stored in the Trie, enabling O(log max_value) lookup per query instead of O(n). TutorialsPoint - Count Pairs With XOR in a Range | Optimal Trie-Based Solution O(n log M) Space: O(n)
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