Step 18 Tries — Theory
Bit PreRequisites for TRIE Problems
Before tackling maximum-XOR problems with a trie, you need the bit-level groundwork this lesson assembles: how numbers decompose into bits, why XOR behaves like addition without carry, and how a binary trie — a trie whose alphabet is just {0, 1} — stores numbers bit by bit from the most significant bit down. With those pieces, the greedy 'prefer the opposite bit' walk that maximises XOR stops being a trick and becomes obvious.
The XOR facts you will actually use
XOR compares numbers bit by bit, independently per position — there is no carry. Three identities drive everything: x ^ x = 0 (a number cancels itself), x ^ 0 = x, and XOR is commutative and associative, so a ^ b ^ a = b. A fourth observation matters for maximisation: a 1 in a high bit outweighs 1s in all lower bits combined (2^k > 2^k - 1 = sum of all lower bits), so when building an answer bit by bit, greedy choices at high positions are always safe.
Also useful: the XOR of a range or set can be maintained incrementally — inserting or removing a value is just XOR-ing it in, since x ^ x = 0 removes it again.
From character tries to binary tries
A regular trie stores strings: each node has children indexed by character, and a root-to-leaf path spells a prefix. Replace the alphabet with bits: each node has exactly two children, child[0] and child[1]. Inserting a number means walking from the most significant bit to the least, creating nodes as needed. Every number of the same bit-width follows a path of identical length (say 32), so all leaves sit at the same depth.
Fix the bit width in advance — commonly bit 31 down to bit 0 for non-negative values up to about 2^31, so numbers align by magnitude: their highest bits are all compared at the same trie levels, which is what makes the greedy walk below valid. Nodes commonly store a count of how many inserted numbers pass through them; that count is what later problems use for 'how many numbers give XOR less than K' style queries.
class BitTrieNode:
def __init__(self):
self.child = [None, None] # child[0], child[1]
self.count = 0 # numbers passing through
MAX_BIT = 31
def insert(root, num):
node = root
for b in range(MAX_BIT, -1, -1):
bit = (num >> b) & 1
if node.child[bit] is None:
node.child[bit] = BitTrieNode()
node = node.child[bit]
node.count += 1The maximum-XOR query walk
Given x, find the inserted number y maximising x ^ y. Walk the trie alongside x's bits from high to low. At bit b, your result gets a 1 at position b exactly when y has the opposite bit to x there. So greedily prefer the child labelled 1 - (x's bit); take it if it exists. If it does not, you are forced into the same-bit child and that answer bit is 0. Because high bits dominate (the fact from section 1), never sacrificing a high 1 for any combination of lower bits is provably optimal.
Worked example: inserted numbers include 9 (01001) and 5 (00101), query x = 12 (01100), using 5 bits. Bit 4: x has 0, prefer child 1 — none exist (all numbers start 0), take 0. Bit 3: x has 1, prefer 0 — 5's path qualifies, follow it. Remaining bits follow 5's path: answer bits so far 1 at bit 3; bits 2..0 of the walk against 5 (00101) vs x (01100) give XOR bits 0,0,1... computing fully: 12 ^ 5 = 9, while 12 ^ 9 = 5, so the walk correctly selects y = 5 with XOR 9. Insert and query each cost O(bits) = O(32) — effectively constant.
def max_xor_with(root, x):
node = root
best = 0
for b in range(MAX_BIT, -1, -1):
bit = (x >> b) & 1
want = 1 - bit
if node.child[want] is not None:
best |= (1 << b) # this answer bit becomes 1
node = node.child[want]
else:
node = node.child[bit]
return bestCommon mistakes
(1) Inserting bits from least significant upward — the trie then groups numbers by their low bits, magnitude alignment is destroyed, and the greedy walk is invalid. Always MSB first. (2) Inconsistent bit width between insert and query: if one number was inserted over 31 bits and queried over 20, the paths do not line up. (3) Forgetting the count field until a problem asks for counting queries (XOR less than K, pairs with XOR in a range) and having to rebuild the structure. (4) Signed values: for possibly negative numbers in fixed-width languages, two's complement makes the sign bit behave like any other bit if you consistently use the full width (e., 32 bits) — problems in this module use non-negative values, so 31..0 is safe.
Key points
- XOR is per-bit with no carry: x ^ x = 0, x ^ 0 = x, order irrelevant — and a high 1 beats all lower bits combined.
- A binary trie stores numbers MSB-first; each node has children for bit 0 and bit 1 plus a pass-through count.
- Max-XOR query: at each bit prefer the child opposite to x's bit; fall back to the same bit only when forced.
- Insert and query are O(number of bits) — treat 32-bit widths as constant time.
- Keep insert and query bit-widths identical, and include node counts from the start for counting queries.