Count Pairs With XOR in a Range — LeetCode 1803 Python Solution

HardBit ManipulationTrieArray
Problem
#1803
Pattern
Trie
Reading time
7 min

The 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 and low <= (nums[i] XOR nums[j]) <= high.

Example

Input
nums = [1,4,2,7], low = 2, high = 6
Output
6
Explanation
All nice pairs (i, j) are as follows:

Python solution

Python
class Trie:
    def __init__(self):
        self.children = [None] * 2
        self.cnt = 0

    def insert(self, x):
        node = self
        for i in range(15, -1, -1):
            v = x >> i & 1
            if node.children[v] is None:
                node.children[v] = Trie()
            node = node.children[v]
            node.cnt += 1

    def search(self, x, limit):
        node = self
        ans = 0
        for i in range(15, -1, -1):
            if node is None:
                return ans
            v = x >> i & 1
            if limit >> i & 1:
                if node.children[v]:
                    ans += node.children[v].cnt
                node = node.children[v ^ 1]
            else:
                node = node.children[v]
        return ans


class Solution:
    def countPairs(self, nums: List[int], low: int, high: int) -> int:
        ans = 0
        tree = Trie()
        for x in nums:
            ans += tree.search(x, high + 1) - tree.search(x, low)
            tree.insert(x)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(n \times \log M) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 1803. Count Pairs With XOR in a Range is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Trie.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1803. Count Pairs With XOR in a Range?
LeetCode 1803. Count Pairs With XOR in a Range is rated Hard on LeetCode.
What is the time complexity of LeetCode 1803. Count Pairs With XOR in a Range?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 1803. Count Pairs With XOR in a Range?
The Python solution on this page uses O(n \times \log M) auxiliary space.
What topics does LeetCode 1803. Count Pairs With XOR in a Range cover?
LeetCode 1803. Count Pairs With XOR in a Range is tagged Bit Manipulation, Trie and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview