Skip to content

1803. Count Pairs With XOR in a Range 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  int count = 0;
  TrieNode() : children(2) {}
};

class Solution {
 public:
  int countPairs(vector<int>& nums, int low, int high) {
    int ans = 0;

    for (const int num : nums) {
      ans += getCount(num, high + 1) - getCount(num, low);
      insert(num);
    }

    return ans;
  }

 private:
  static constexpr int kHeight = 14;
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  void insert(int num) {
    shared_ptr<TrieNode> node = root;
    for (int i = kHeight; i >= 0; --i) {
      const int bit = num >> i & 1;
      if (node->children[bit] == nullptr)
        node->children[bit] = make_shared<TrieNode>();
      node = node->children[bit];
      ++node->count;
    }
  }

  // Returns the number of numbers < limit.
  int getCount(int num, int limit) {
    int count = 0;
    shared_ptr<TrieNode> node = root;
    for (int i = kHeight; i >= 0; --i) {
      const int bit = num >> i & 1;
      const int bitLimit = limit >> i & 1;
      if (bitLimit == 1) {
        if (node->children[bit] != nullptr)
          count += node->children[bit]->count;
        node = node->children[bit ^ 1];
      } else {
        node = node->children[bit];
      }
      if (node == nullptr)
        break;
    }
    return count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class TrieNode {
  public TrieNode[] children = new TrieNode[2];
  public int count = 0;
}

class Solution {
  public int countPairs(int[] nums, int low, int high) {
    int ans = 0;

    for (final int num : nums) {
      ans += getCount(num, high + 1) - getCount(num, low);
      insert(num);
    }

    return ans;
  }

  private final int kHeight = 14;
  private TrieNode root = new TrieNode();

  private void insert(int num) {
    TrieNode node = root;
    for (int i = kHeight; i >= 0; --i) {
      final int bit = num >> i & 1;
      if (node.children[bit] == null)
        node.children[bit] = new TrieNode();
      node = node.children[bit];
      ++node.count;
    }
  }

  // Returns the number of numbers < limit.
  private int getCount(int num, int limit) {
    int count = 0;
    TrieNode node = root;
    for (int i = kHeight; i >= 0; --i) {
      final int bit = num >> i & 1;
      final int bitLimit = ((limit >> i) & 1);
      if (bitLimit == 1) {
        if (node.children[bit] != null)
          count += node.children[bit].count;
        node = node.children[bit ^ 1];
      } else {
        node = node.children[bit];
      }
      if (node == null)
        break;
    }
    return count;
  }
}