<p>Given a <strong>(0-indexed)</strong> integer array <code>nums</code> and two integers <code>low</code> and <code>high</code>, return <em>the number of <strong>nice pairs</strong></em>.</p>

<p>A <strong>nice pair</strong> is a pair <code>(i, j)</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>low &lt;= (nums[i] XOR nums[j]) &lt;= high</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,4,2,7], low = 2, high = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> All nice pairs (i, j) are as follows:
    - (0, 1): nums[0] XOR nums[1] = 5 
    - (0, 2): nums[0] XOR nums[2] = 3
    - (0, 3): nums[0] XOR nums[3] = 6
    - (1, 2): nums[1] XOR nums[2] = 6
    - (1, 3): nums[1] XOR nums[3] = 3
    - (2, 3): nums[2] XOR nums[3] = 5
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [9,8,4,2,1], low = 5, high = 14
<strong>Output:</strong> 8
<strong>Explanation:</strong> All nice pairs (i, j) are as follows:
​​​​​    - (0, 2): nums[0] XOR nums[2] = 13
&nbsp;   - (0, 3): nums[0] XOR nums[3] = 11
&nbsp;   - (0, 4): nums[0] XOR nums[4] = 8
&nbsp;   - (1, 2): nums[1] XOR nums[2] = 12
&nbsp;   - (1, 3): nums[1] XOR nums[3] = 10
&nbsp;   - (1, 4): nums[1] XOR nums[4] = 9
&nbsp;   - (2, 3): nums[2] XOR nums[3] = 6
&nbsp;   - (2, 4): nums[2] XOR nums[4] = 5</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= low &lt;= high &lt;= 2 * 10<sup>4</sup></code></li>
</ul>
class TrieNode:
	def __init__(self, bit_index: int = 20):
		self.freq = 0 
		self.child = [None, None]
		self.bit_index = bit_index

	def add_num(self, num: int):
		self.freq += 1

		if self.bit_index == -1:
			return
		current_bit = (num >> self.bit_index) & 1
		
		if self.child[current_bit] is None:
			self.child[current_bit] = TrieNode(self.bit_index - 1)
		
		self.child[current_bit].add_num(num)

	def find_nums_with_smaller_xor(self, num: int, k: int):
		if self.bit_index == -1:
			return self.freq
		
		num_bit = (num >> self.bit_index) & 1
		k_bit = (k >> self.bit_index) & 1
		
		if k_bit == 0:
			if self.child[num_bit] is None:
				return 0
			return self.child[num_bit].find_nums_with_smaller_xor(num, k)
		else:
			total_nums = 0
			
			if self.child[num_bit] is not None:
				total_nums += self.child[num_bit].freq
			
			if self.child[num_bit ^ 1] is not None:
				total_nums += self.child[num_bit ^ 1].find_nums_with_smaller_xor(num, k)		
			return total_nums
class Solution:
	def countPairs(self, nums: List[int], low: int, high: int):
		root = TrieNode()

		ans = 0
		for num in nums:
			ans += root.find_nums_with_smaller_xor(num, high)

			if low != 0:
				ans -= root.find_nums_with_smaller_xor(num, low - 1)

			root.add_num(num)
		return ans	
25400