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
struct TrieNode {
  vector<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:
  constexpr static int kHeight = 14;
  TrieNode root;
  void insert(int num) {
    TrieNode* node = &root;
    for (int i = kHeight; i >= 0; --i) {
      const int bit = ((num >> i) & 1);
      if (!node->children[bit])
        node->children[bit] = new TrieNode();
      node = node->children[bit];
      ++node->count;
    }
  }

  // # of nums < limit
  int getCount(int num, int limit) {
    int count = 0;
    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])
          count += node->children[bit]->count;
        node = node->children[bit ^ 1];
      } else {
        node = node->children[bit];
      }
      if (!node)
        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;
    }
  }

  // # of nums < 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;
  }
}
Back to top