ADVANCED DATA STRUCTURES PROGRAM • LEVEL 15 — DIGITAL SEARCH TREES

Find Maximum XOR with a Bitwise Trie

Learn how to find maximum xor with a bitwise trie using a clear C program.

AdvancedTrieDigital search

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Maximum XOR = 28

COMPLETE C PROGRAM

Complete C implementation

ads-bitwise-trie-maximum-xor.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { struct Node *child[2]; };
struct Node *new_node(void) { struct Node *node = calloc(1, sizeof *node); if (!node) exit(EXIT_FAILURE); return node; }
void insert_number(struct Node *root, int value) { for (int bit = 30; bit >= 0; bit--) { int digit = (value >> bit) & 1; if (!root->child[digit]) root->child[digit] = new_node(); root = root->child[digit]; } }
int maximum_xor(struct Node *root, int value) { int answer = 0; for (int bit = 30; bit >= 0; bit--) { int digit = (value >> bit) & 1, wanted = digit ^ 1; if (root->child[wanted]) { answer |= 1 << bit; root = root->child[wanted]; } else root = root->child[digit]; } return answer; }
void free_nodes(struct Node *root) { if (root) { free_nodes(root->child[0]); free_nodes(root->child[1]); free(root); } }

int main(void)
{
    int values[] = {3, 10, 5, 25, 2, 8}; struct Node *root = new_node(); int best = 0;
    for (int i = 0; i < 6; i++) insert_number(root, values[i]);
    for (int i = 0; i < 6; i++) { int current = maximum_xor(root, values[i]); if (current > best) best = current; }
    printf("Maximum XOR = %d\n", best); free_nodes(root); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Maximum XOR = 28
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. At each bit prefer the opposite branch because it contributes one to the XOR result.
  3. Display the computed result.

At each bit prefer the opposite branch because it contributes one to the XOR result.

EFFICIENCY

Time and space complexity

Time complexity

O(n * word bits)

Auxiliary space

O(n * word bits)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.