Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Home/Questions/Q 3527
Next
In Process

RTSALL Latest Articles

aarav0
aarav0
Asked: September 11, 20262026-09-11T09:52:32-05:00 2026-09-11T09:52:32-05:00In: Data Structures & Algorithms, Tries & Prefix Search Engines

How does a 32-bit Binary Trie find the Maximum XOR of Two Numbers in O(N) time?

Given an integer array, we need to find two numbers whose bitwise XOR (A ^ B) is maximized.

The brute force approach tests all pairs in O(N^2), which is way too slow when N = 100,000. People recommend building a Binary Trie (prefix tree of bits 0 and 1) to solve this in O(32 * N) = O(N) time. How does walking down a binary tree yield the maximum possible XOR?

  • 0
  • 2 2 Answers
  • 0 Followers
  • 0
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

Leave an answer
Cancel reply

You must login to add an answer.


Forgot Password?

Need An Account, Sign Up Here

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Abhishek
    Abhishek Begginer
    2026-09-11T21:26:57-05:00Added an answer on September 11, 2026 at 9:26 pm

    Here is the C++20 Binary Trie implementation. To avoid dynamic heap allocations during tree insertion, we use a flat contiguous node pool.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    class BinaryTrie {
        struct Node {
            int next[2] = {-1, -1};
        };
        std::vector<Node> tree;
    
    public:
        BinaryTrie() {
            tree.emplace_back(); // Root node at index 0
        }
    
        void insert(int num) {
            int curr = 0;
            for (int i = 30; i >= 0; --i) {
                int bit = (num >> i) & 1;
                if (tree[curr].next[bit] == -1) {
                    tree[curr].next[bit] = tree.size();
                    tree.emplace_back();
                }
                curr = tree[curr].next[bit];
            }
        }
    
        int queryMaxXOR(int num) const {
            int curr = 0;
            int max_xor = 0;
            for (int i = 30; i >= 0; --i) {
                int bit = (num >> i) & 1;
                int opposite = 1 - bit;
                if (tree[curr].next[opposite] != -1) {
                    max_xor |= (1 << i);
                    curr = tree[curr].next[opposite];
                } else {
                    curr = tree[curr].next[bit];
                }
            }
            return max_xor;
        }
    };
    
    int findMaximumXOR(const std::vector<int>& nums) {
        BinaryTrie trie;
        for (int x : nums) trie.insert(x);
    
        int ans = 0;
        for (int x : nums) {
            ans = std::max(ans, trie.queryMaxXOR(x));
        }
        return ans;
    }
    
    int main() {
        std::vector<int> nums = {3, 10, 5, 25, 2, 8};
        std::cout << "Maximum XOR Pair: " << findMaximumXOR(nums) << "n"; // Expected: 28 (5 ^ 25)
        return 0;
    }
    

    Complexity: Strictly O(31 * N) = O(N) time with flat memory pooling.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Abhay Tiwari
    Abhay Tiwari Begginer
    2026-09-11T09:52:35-05:00Added an answer on September 11, 2026 at 9:52 am

    The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature.

    1. The Greedy Bit Principle

    In binary numbers, the Most Significant Bit (MSB) has more numerical value than all lower bits combined! For example, bit 30 ($2^{30} pprox 1.07 imes 10^9$) is strictly greater than the sum of all bits from 0 to 29 combined ($2^{30} – 1$).

    Therefore, to maximize an XOR sum, you must be greedy from left to right (MSB down to LSB):

    • If the current bit of number num is 1, you desperately want to pair it with a number whose corresponding bit is 0 (because 1 ^ 0 = 1).
    • If the current bit of num is 0, you want to pair it with a number whose corresponding bit is 1 (because 0 ^ 1 = 1).

    2. Why a Binary Trie?

    A Binary Trie is just a tree where every node has at most two children: 0 (left) and 1 (right).

    1. Insert: You insert each number into the Trie as a 31-bit or 32-bit string of binary digits, from bit 31 down to bit 0.
    2. Query: For each number x, you walk down the Trie. At each bit b, you ask: ‘Does the opposite branch (1 - b) exist?’
      • If YES: Take that branch! That bit in your XOR result becomes 1.
      • If NO: You’re forced to take the same branch (b), so that bit in your XOR result becomes 0.

    Because you made the best possible choice at every single bit position starting from the highest power of 2, the final accumulated number is mathematically guaranteed to be the global maximum XOR!


    Clean Python 3.12 Implementation

    class TrieNode:
        __slots__ = ('children',)
        def __init__(self):
            self.children: list[TrieNode | None] = [None, None]
    
    class Solution:
        def find_maximum_xor(self, nums: list[int]) -> int:
            root = TrieNode()
    
            # Step 1: Insert all numbers into the 31-bit binary trie
            for num in nums:
                curr = root
                for i in range(30, -1, -1):
                    bit = (num >> i) & 1
                    if not curr.children[bit]:
                        curr.children[bit] = TrieNode()
                    curr = curr.children[bit]
    
            # Step 2: Query each number against the trie
            max_xor = 0
            for num in nums:
                curr = root
                current_xor = 0
                for i in range(30, -1, -1):
                    bit = (num >> i) & 1
                    opposite_bit = 1 - bit
                    
                    # Greedily check if the complementary bit exists
                    if curr.children[opposite_bit]:
                        current_xor |= (1 << i)
                        curr = curr.children[opposite_bit]
                    else:
                        curr = curr.children[bit]
                        
                max_xor = max(max_xor, current_xor)
    
            return max_xor
    

    Complexity Breakdown

    • Time Complexity: O(31 * N) = O(N). Inserting N numbers takes 31 * N operations. Querying N numbers takes 31 * N operations. Total time is strictly linear in the number of elements.
    • Space Complexity: O(31 * N) worst-case node allocations. In practice, prefix branches overlap heavily, keeping memory around a few megabytes.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Related Questions

  • pgvector: HNSW index build fails with out-of-memory or high swap: ...

    • 1 Answer
  • Why does std::views::filter on temporary containers trigger undefined behavior and ...

    • 1 Answer
  • PyTorch RuntimeError: CUDA out of memory: Why torch.cuda.empty_cache() fails & ...

    • 1 Answer
  • Next.js 15: Error: Route used "params" without awaiting it (Asynchronous ...

    • 1 Answer
  • Task Scheduler with Cooldowns: Closed-form mathematical formula vs Priority Queue ...

    • 2 Answers

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.