Bitwise trie
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A bitwise trie stores numbers as strings of 0s and 1s, so each step has only two doors. It makes questions about number beginnings, such as address ranges or XOR comparisons, very quick, using at most as many steps as the number has bits.
Practical use cases
- Web app: IP allow-list for an admin panel. An admin login page must check whether a visitor IP falls into any of thousands of allowed or blocked ranges. Stored as a 0/1 trie, the check walks at most 32 doors and stops at the first matching range, so it adds no noticeable delay to every request. Pages stay quick even under heavy traffic, because each request does the same small fixed amount of work.
- Web app: Fast lookup of user ids in memory. A real-time dashboard keeps millions of active user ids as numbers and repeatedly needs "is this id present?" or "which id is closest?". A 0/1 trie answers in about 32 steps without sorting or hashing the whole set again.
- System: Routers and XOR puzzles. Network routers choose a route by the longest matching address beginning, and security or contest problems ask about XOR of numbers. Both are naturally answered by walking a two-door tree. Because numbers have a fixed number of bits, each walk has a small fixed length no matter how many numbers are stored.
The story: The Lockers with Two Doors
At Mira's school the lockers were numbered, and every locker had a funny rule: the corridor had only two doors at each turn, a left door marked 0 and a right door marked 1. To reach locker number 5 the caretaker had to remember its pattern: left, right, left, right (0101).
Mira noticed something. Lockers 5 and 3 both begin with a left door (0). Lockers 10 and 12 both begin with a right door (1). "The first turn splits the corridor in two halves!" The bigger the first bit, the farther the number. Inside each half the next bit splits it again.
She drew it on the wall: a tree where every box has at most two lanes, 0 and 1, and each number is a path of the same length. No letters at all, only bits. Looking for locker 10 was just following 1, 0, 1, 0.
This is the bitwise trie (binary trie): a trie over the binary form of numbers, starting from the most significant bit. Insert and lookup cost the number of bits, and best of all, the shape keeps numbers organised by their bits so we can ask clever questions like "which stored number is most different from this one?" (next lesson!).
How to spot this problem, and where you need it
You are working with large sets of whole numbers or addresses and need quick matching by their leading bits, or XOR based questions, and comparing against every number is too slow.
Signs you need it
- You deal with IP addresses, subnet ranges, or numbers where the beginning of the binary form matters.
- The problem mentions XOR, "bits", or asks for the number that is most like or most unlike another.
- A loop over every stored integer per query is the bottleneck.
- Numbers fit in a fixed number of bits, such as 32 or 64.
Where to use it in a project
- IP filtering, geo-IP lookups and rate limiting by network range.
- Features that compare large sets of integer ids, such as nearest or best-matching ids.
The solution
Write each number in binary with a fixed number of bits. Insert it into a trie where every node has only two children, 0 and 1, starting from the most important bit. To look up or compare a number, walk its bits from the top, choosing the matching door when you can. The walk length is just the number of bits.
Payoff: Before: checking an address against 50,000 ranges one by one. After: at most 32 steps, whatever the number of ranges.
Explain it like I am 8
Every number can be written with 0s and 1s, like a secret code. Make a road that splits into just two ways at each step, 0 or 1. Each number is a trip that follows its code. Numbers with the same start of code share the first part of the trip.
How it works, step by step
- Choose a fixed number of bits (for example 32 for ordinary integers, or 4 in our toy example).
- For each number, read its bits from the biggest to the smallest:
(x >> i) & 1for i from the top bit down to 0. - Each box has two child slots: 0 and 1. Follow the slot for the bit; create it if it is missing.
- After the last bit you are at a leaf; the path itself is the number.
- To check membership, follow the same bits; if a slot is missing, the number is not stored.
The code in four languages
PHP
<?php
const BITS = 4; // our toy numbers fit in 4 bits
class BNode {
public array $kid = [null, null]; // slot 0 and slot 1
}
class BitTrie {
private BNode $root;
public function __construct() { $this->root = new BNode(); }
public function insert(int $x): void {
$n = $this->root;
for ($i = BITS - 1; $i >= 0; $i--) { // biggest bit first
$b = ($x >> $i) & 1;
$n->kid[$b] ??= new BNode(); // create the lane if missing
$n = $n->kid[$b];
}
}
public function contains(int $x): bool {
$n = $this->root;
for ($i = BITS - 1; $i >= 0; $i--) {
$b = ($x >> $i) & 1;
if ($n->kid[$b] === null) { return false; }
$n = $n->kid[$b];
}
return true;
}
}
$t = new BitTrie();
foreach ([5, 3, 10, 12] as $x) {
$t->insert($x);
echo $x . ' = ' . str_pad(decbin($x), BITS, '0', STR_PAD_LEFT) . PHP_EOL;
}
foreach ([10, 7, 3] as $q) {
echo $q . ': ' . ($t->contains($q) ? 'stored' : 'not stored') . PHP_EOL;
}JavaScript
const BITS = 4; // our toy numbers fit in 4 bits
class BNode {
constructor() { this.kid = [null, null]; } // slot 0 and slot 1
}
class BitTrie {
constructor() { this.root = new BNode(); }
insert(x) {
let n = this.root;
for (let i = BITS - 1; i >= 0; i--) { // biggest bit first
const b = (x >> i) & 1;
if (n.kid[b] === null) n.kid[b] = new BNode(); // create the lane if missing
n = n.kid[b];
}
}
contains(x) {
let n = this.root;
for (let i = BITS - 1; i >= 0; i--) {
const b = (x >> i) & 1;
if (n.kid[b] === null) return false;
n = n.kid[b];
}
return true;
}
}
const t = new BitTrie();
for (const x of [5, 3, 10, 12]) {
t.insert(x);
console.log(x + ' = ' + x.toString(2).padStart(BITS, '0'));
}
for (const q of [10, 7, 3]) {
console.log(q + ': ' + (t.contains(q) ? 'stored' : 'not stored'));
}Java
public class Main {
static final int BITS = 4; // our toy numbers fit in 4 bits
static class BNode {
BNode[] kid = new BNode[2]; // slot 0 and slot 1
}
static class BitTrie {
private final BNode root = new BNode();
void insert(int x) {
BNode n = root;
for (int i = BITS - 1; i >= 0; i--) { // biggest bit first
int b = (x >> i) & 1;
if (n.kid[b] == null) n.kid[b] = new BNode(); // create the lane if missing
n = n.kid[b];
}
}
boolean contains(int x) {
BNode n = root;
for (int i = BITS - 1; i >= 0; i--) {
int b = (x >> i) & 1;
if (n.kid[b] == null) return false;
n = n.kid[b];
}
return true;
}
}
static String binary(int x) {
String s = Integer.toBinaryString(x);
return "0".repeat(BITS - s.length()) + s; // pad to BITS digits
}
public static void main(String[] args) {
BitTrie t = new BitTrie();
for (int x : new int[]{5, 3, 10, 12}) {
t.insert(x);
System.out.println(x + " = " + binary(x));
}
for (int q : new int[]{10, 7, 3}) {
System.out.println(q + ": " + (t.contains(q) ? "stored" : "not stored"));
}
}
}Go
package main
import "fmt"
const bits = 4 // our toy numbers fit in 4 bits
type bNode struct {
kid [2]*bNode // slot 0 and slot 1
}
type BitTrie struct {
root *bNode
}
func NewBitTrie() *BitTrie { return &BitTrie{root: &bNode{}} }
func (t *BitTrie) Insert(x int) {
n := t.root
for i := bits - 1; i >= 0; i-- { // biggest bit first
b := (x >> i) & 1
if n.kid[b] == nil {
n.kid[b] = &bNode{} // create the lane if missing
}
n = n.kid[b]
}
}
func (t *BitTrie) Contains(x int) bool {
n := t.root
for i := bits - 1; i >= 0; i-- {
b := (x >> i) & 1
if n.kid[b] == nil {
return false
}
n = n.kid[b]
}
return true
}
func main() {
t := NewBitTrie()
for _, x := range []int{5, 3, 10, 12} {
t.Insert(x)
fmt.Printf("%d = %0*b\n", x, bits, x)
}
for _, q := range []int{10, 7, 3} {
answer := "not stored"
if t.Contains(q) {
answer = "stored"
}
fmt.Printf("%d: %s\n", q, answer)
}
}Time: O(B) per operation · Extra space: O(n x B). B is the number of bits (like 32), so inserting or finding a number takes at most B steps however many numbers are stored.
Watch out for
- Reading bits from the smallest side first: the trie then loses the "biggest bit decides first" ordering that makes XOR tricks work.
- Mixing the bit lengths: every number must be padded to the same number of bits (5 is 0101, not 101).
- Using too few bits, so that a larger value silently loses its top bit.
Quick check
- How many children can a bitwise trie box have?
- 1
- 2
- 10
- In which order do we read the bits of a number?
- Smallest bit first
- Biggest (most significant) bit first
- Any order
- How many steps does inserting one number take with 32-bit integers?
- 32
- As many as numbers stored
- 2