Problem 402054 · hard · Level 04 Non-Linear Data Structures

Walkie-Talkie Pairs That Crackle

binary trie · subtree counts · bit manipulation · counting pairs

Every walkie-talkie at a festival is tuned to a non-negative integer channel. Two radios crackle when the XOR of their channels lies between lo and hi inclusive. Given the list channels (one entry per radio; several radios may share a channel), return the number of index pairs (i, j) with i < j whose radios crackle.

Examples

Input:  channels = [3, 6, 5, 1], lo = 2, hi = 6
Output: 5
Explanation: 3^6 = 5, 3^5 = 6, 3^1 = 2, 6^5 = 3 and 5^1 = 4 are in range (both ends count);
6^1 = 7 is not.

Input:  channels = [3, 3, 3, 0], lo = 0, hi = 0
Output: 3
Explanation: a XOR of 0 means equal channels: the three radios on channel 3 form 3 pairs.

Constraints

  • 0 <= len(channels) <= 2 * 10**4
  • 0 <= channels[i] < 2**20, 0 <= lo <= hi < 2**20
  • Target: about O(n * 20); checking every pair is O(n**2) and too slow

Goals

  • Count the stored values whose XOR with x is below a bound in one walk down a binary trie
  • Add whole subtrees at once using counts kept on the nodes
  • Turn a range [lo, hi] into two 'below' questions
Starting Python…