Storing numbers bit by bit in a trie

Video lessonComing soon

1 The pair with the largest XOR

We have an array of non-negative numbers, and we want the largest a ^ b over any two of them. This is the problem Maximum XOR of Two Numbers in an Array. Our example through the whole lesson is:

130517214344
nums. The best pair is 5 and 14: 5 ^ 14 = 11

Checking all 10 pairs finds 5 ^ 14 = 11. Size is no shortcut, because the largest and the smallest, 14 and 4, give only 10.

But n numbers make about n²/2 pairs. At n = 10⁵ that is around 5 × 10⁹ pairs. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).

We need each number's best partner without trying every other number.

2 The top bit decides

Compare 8 and 7 in four bits:

18040201
8: the top bit alone
08141211
7: every bit below it

One top bit beats all the bits below it put together. Bit k is worth 2ᵏ, and all the bits below it add up to 2ᵏ − 1. So when we read two numbers from the top, the first place where they differ decides which one is bigger.

XOR has a 1 wherever its two numbers differ. For x = 5, which is 0101, any partner that starts with 1 gives an XOR of at least 8. Any partner that starts with 0 gives at most 7. So the partners that start with 0 are out, whatever their lower bits are.

So we choose the partner one bit at a time, from the top. At each bit, we want the opposite bit to x's, because it puts a 1 in the XOR. We take it whenever some number still in the running has it, and we never give it back for lower bits.

At each bit, we ask: does some number start with the bits chosen so far, then the bit we want? A trie answers that prefix question in one step per bit.

3 A trie over bits

The last lesson's trie stored words, one letter per level. Here each number is a word of 0s and 1s, written from the top bit down, so a node has at most two children. In the drawings, 0 goes left and 1 goes right. Our numbers fit in 4 bits, so each one is a path of 4 steps.

Inserting walks the bits from the top. It follows the child for each bit, and makes the child first if it is missing. A new number makes nodes only below the point where it leaves every earlier path.

Inserting 13, 5, 7, 14 and 4
130517214344i
nums
1101"1101"
13 = 1101 makes a new path of 4 nodes

Every number gets the same number of bits, with leading 0s, so each level stands for the same bit in every number. Without leading 0s, 2 is 10 and 12 is 1100:

10"10"100"1100"
No leading 0s: 2 and 12 share a step
0010"0010"1100"1100"
4 bits each: they part at the root

On the left, 2 and 12 seem to agree on their top bit. But 2's first 1 is worth 2, and 12's is worth 8. On the right, they part at the root, where they really differ.

Real inputs go up to 2³¹ − 1, so the code gives every number 31 bits, from bit 30 down to bit 0.

4 Walking down for the best partner

To find the best partner for x, we start at the root and go down one level per bit, from the top. At each level, x has some bit, and we want want = 1 - bit:

  • The child for want exists. We go there. Some number differs from x at this bit, so this bit of the XOR is 1.
  • It is missing. We go to the child for bit. Every number left matches x at this bit, so this bit of the XOR is 0.

One of the two children always exists. Every number has all its bits, so every path runs down to the last level, and no node above it is empty.

Here is the walk for x = 5:

The best partner for 5 = 0101
08140211bit 3
x = 5
0100"0100"1"0101"11"0111"1101"1101"10"1110"
Bit 3: want 1, found. XOR 1000

The same walk as a table:

ibit of 5wantchild for want?go toXOR so far
301yes11000
210no11000
101yes11010
010yes01011

The walk ends on 14, which is 1110, and the XOR is 1011 = 11. We lost bit 2, because no number starts with 10. The 8 we kept at bit 3 still outweighs everything we could lose below it.

We run the same walk for every number:

xbest partnerx ^ partner
13710
51411
71310
14511
41410

The answer is the largest result, 11. The best pair shows up when we walk for either of its numbers, so nothing is missed.

5 The code and its cost

We insert every number first, then walk for each one. The trie holds x itself while we walk for x. That does no harm: x ^ x is 0, so it never beats a real pair. With a single number, the answer is 0.

Every tab gives 11 for our example, and the table's result for each number. The code uses 31 bits, not 4. In our example, bits 30 to 4 are 0 in every number, so they form one shared path, and the walk adds nothing there.

Each insert and each walk takes 31 steps, one per bit. For n = 10⁵ numbers, that is around 6 × 10⁶ steps in all, well inside the time limit. With B bits, the time is O(n · B).

Each number adds at most 31 nodes, so the trie holds at most about 3 × 10⁶ nodes: O(n · B) space. That is tens of megabytes, so memory is the cost to watch.

6 Mistakes and edge cases

  • Bits without leading 0s. The % 2 loop from the lesson on bit operators gives the bits lowest first, with no leading 0s. The trie then lines up 2 and 12 wrongly, as in the drawing above. Read bit i with (num >> i) & 1, from the top bit down.
  • Moving to a missing child. The opposite child is often missing, as at bit 2 for x = 5. Moving there without the check gets a Runtime Error.
  • A loop that stops at bit 1. The test must be i >= 0. With i > 0, bit 0 never goes into the trie, and our example gives 10 instead of 11.
  • The wrong top bit. The constraints decide it: values up to 2³¹ − 1 need bit 30, and values up to 10⁹ need bit 29. Starting too low ignores the bits above. Starting at bit 31 only adds a level of 0s, but a mask for bit 31 needs care.

C++

1 << 31 overflows an int. It gives −2147483648. When values can reach bit 31, use long long for the result and 1LL << i for the mask.

1 << 31 is −2147483648. It lands on the sign bit. When values can reach bit 31, use long for the result and 1L << i for the mask.

Nothing to watch. Integers have no width, so 1 << 31 is 2147483648. HIGH_BIT alone sets how many bits the trie uses.

Bit operators use 32 signed bits. 1 << 31 is −2147483648, and | cuts any value past 2³¹ − 1. Values up to 2³¹ − 1 are safe, as in this problem.

int is 64 bits, so 1 << 31 is a positive 2147483648. The trap is back if the values are stored as int32.

1 << 31 on an i32 is −2147483648. It lands on the sign bit. When values can reach bit 31, use i64 for the result and the mask.

1 << 31 is −2147483648. It lands on the sign bit. When values can reach bit 31, use long for the result and 1L << i for the mask.

7 When to use a bit trie

The sign is the largest XOR between one number and a group of others, where trying every pair is too slow. The trie and the walk stay the same from problem to problem. What changes is which numbers are in the trie, or what each node keeps:

  • The largest XOR of any pair. Insert every number, then walk for each one, as above.
  • Each query has a limit. In Maximum XOR With an Element From Array, each query gives x and a limit m, and the partner must be at most m. Sort the numbers and the queries by m. Before each query, insert every number up to its m, so the trie holds exactly the allowed partners, and an empty trie means −1. Answering in our own order and writing each answer back at its index is answering offline.
  • The largest XOR of a subarray. XOR undoes itself, so a running XOR works like a prefix sum: the XOR of nums[l..r] is prefix[r + 1] ^ prefix[l]. The best subarray is the best pair of prefix values, the leading 0 included.
  • Pairs with XOR below k. Each node keeps the prefix count from the last lesson. Walk down x's bits and k's bits together. Where k has a 1, every number on x's own side puts a 0 in the XOR there, so all of them are below k: add that child's count, then go down the other side. Where k has a 0, go down x's own side.

The walk takes the best bit at each level and never goes back. The next topic, greedy algorithms, is about when a choice like that is safe.

Before writing the walk, write two or three numbers in fixed-width binary, one under the other, and find their largest XOR by hand from the top bit down.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.