Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum XOR of Two Numbers in an Array
Next article icon

Maximum XOR of Two Numbers in an Array | Set 2

Last Updated : 20 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR from all the possible pairs in the given array.

Examples:

Input: arr[] = {25, 10, 2, 8, 5, 3}
Output: 28
Explanation:
The maximum result is 5^25 = 28.

Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: 7
Explanation:
The maximum result is 1^6 = 7.

Naive Approach: Refer to the article Maximum XOR of Two Numbers in an Array for the simplest approach to solve the problem by generating all pairs of the given array and computing XOR of each pair to find the maximum among them.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Bitmasking Approach:  Refer to the article Maximum XOR of Two Numbers in an Array to solve the problem using Bitmasking.

Time Complexity: O(N*log M), where M is the maximum number present in the array 
Auxiliary Space: O(N)

Efficient Approach: The above approach can be solved by using Trie by inserting the binary representation of the numbers in the array arr[]. Now iterate the binary representation of all the elements in the array arr[] and if the current bit is 0 then find the path with value 1 or vice-versa in the Trie to get the maximum value of Bitwise XOR. Update the maximum value for each number. Below are the steps:

  1. Initialize maximumXOR as 0.
  2. Insert the binary representation of all the numbers in the given array arr[] in the Tree. While inserting in the trie if the current bit 0 then create a node in the left else create a node in the right of the current head node.
  3. Now, traverse the given array and for each element do the following:
    • Initialize the currentXOR value as 0.
    • Traverse the binary representation of the current number.
    • If ith bit is 1 and node->left exists then update currentXOR as currentXOR + pow(2, i) and update node as node->left. Else update node = node->right.
    • If ith bit is 0, and node->right exists then update currentXOR as currentXOR + pow(2, i) and update node as node->right. Else update node = node->left.
  4. For each array element in the above step, update the maximumXOR value if maximumXOR is greater than currentXOR.
  5. Print the value of maximumXOR after the above steps.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of Trie
class node {
public:
    node* left;
    node* right;
};
 
// Function to insert binary
// representation of element x
// in the Trie
void insert(int x, node* head)
{
    // Store the head
    node* curr = head;
 
    for (int i = 30; i >= 0; i--) {
 
        // Find the i-th bit
        int val = (x >> i) & 1;
 
        if (val == 0) {
 
            // If curr->left is NULL
            if (!curr->left)
                curr->left = new node();
 
            // Update curr to curr->left
            curr = curr->left;
        }
        else {
 
            // If curr->right is NULL
            if (!curr->right)
                curr->right = new node();
 
            // Update curr to curr->right
            curr = curr->right;
        }
    }
}
 
// Function that finds the maximum
// Bitwise XOR value for all such pairs
int findMaximumXOR(int arr[], int n)
{
    // head Node of Trie
    node* head = new node();
 
    // Insert each element in trie
    for (int i = 0; i < n; i++) {
        insert(arr[i], head);
    }
 
    // Stores the maximum XOR value
    int ans = 0;
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Stores the XOR with current
        // value arr[i]
        int curr_xor = 0;
 
        int M = pow(2, 30);
 
        node* curr = head;
 
        for (int j = 30; j >= 0; j--) {
 
            // Finding ith bit
            int val = (arr[i] >> j) & 1;
 
            // Check if the bit is 0
            if (val == 0) {
 
                // If right node exists
                if (curr->right) {
 
                    // Update the currentXOR
                    curr_xor += M;
                    curr = curr->right;
                }
 
                else {
                    curr = curr->left;
                }
            }
 
            else {
 
                // Check if left node exists
                if (curr->left) {
 
                    // Update the currentXOR
                    curr_xor += M;
                    curr = curr->left;
                }
                else {
                    curr = curr->right;
                }
            }
 
            // Update M to M/2 for next set bit
            M /= 2;
        }
 
        // Update the maximum XOR
        ans = max(ans, curr_xor);
    }
 
    // Return the maximum XOR found
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << findMaximumXOR(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Structure of Trie
static class node
{
    node left;
    node right;
};
 
// Function to insert binary
// representation of element x
// in the Trie
static void insert(int x, node head)
{
     
    // Store the head
    node curr = head;
 
    for(int i = 30; i >= 0; i--)
    {
         
        // Find the i-th bit
        int val = (x >> i) & 1;
 
        if (val == 0)
        {
             
            // If curr.left is null
            if (curr.left == null)
                curr.left = new node();
 
            // Update curr to curr.left
            curr = curr.left;
        }
        else
        {
             
            // If curr.right is null
            if (curr.right == null)
                curr.right = new node();
 
            // Update curr to curr.right
            curr = curr.right;
        }
    }
}
 
// Function that finds the maximum
// Bitwise XOR value for all such pairs
static int findMaximumXOR(int arr[], int n)
{
     
    // head Node of Trie
    node head = new node();
 
    // Insert each element in trie
    for(int i = 0; i < n; i++)
    {
        insert(arr[i], head);
    }
 
    // Stores the maximum XOR value
    int ans = 0;
 
    // Traverse the given array
    for(int i = 0; i < n; i++)
    {
         
        // Stores the XOR with current
        // value arr[i]
        int curr_xor = 0;
 
        int M = (int)Math.pow(2, 30);
 
        node curr = head;
 
        for(int j = 30; j >= 0; j--)
        {
             
            // Finding ith bit
            int val = (arr[i] >> j) & 1;
 
            // Check if the bit is 0
            if (val == 0)
            {
 
                // If right node exists
                if (curr.right != null)
                {
                     
                    // Update the currentXOR
                    curr_xor += M;
                    curr = curr.right;
                }
                else
                {
                    curr = curr.left;
                }
            }
 
            else
            {
                 
                // Check if left node exists
                if (curr.left != null)
                {
                     
                    // Update the currentXOR
                    curr_xor += M;
                    curr = curr.left;
                }
                else
                {
                    curr = curr.right;
                }
            }
 
            // Update M to M/2 for next set bit
            M /= 2;
        }
 
        // Update the maximum XOR
        ans = Math.max(ans, curr_xor);
    }
 
    // Return the maximum XOR found
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4 };
 
    int N = arr.length;
 
    // Function call
    System.out.print(findMaximumXOR(arr, N));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python program for the above approach
 
# Structure of Trie
class node:
    def __init__(self):
        self.left = None
        self.right = None
 
# Function to insert binary
# representation of element x
# in the Trie
def insert(x,  head):
 
    # Store the head
    curr = head
 
    for i in range(30, -1, -1):
 
        # Find the i-th bit
        val = (x >> i) & 1
 
        if (val == 0):
 
            # If curr.left is null
            if (curr.left == None):
                curr.left = node()
 
            # Update curr to curr.left
            curr = curr.left
        else:
 
            # If curr.right is null
            if (curr.right == None):
                curr.right = node()
 
            # Update curr to curr.right
            curr = curr.right
 
 
# Function that finds the maximum
# Bitwise XOR value for all such pairs
def findMaximumXOR(arr, n):
 
    # head Node of Trie
    head = node()
 
    # Insert each element in trie
    for i in range(n):
        insert(arr[i], head)
 
    # Stores the maximum XOR value
    ans = 0
 
    # Traverse the given array
    for i in range(n):
 
        # Stores the XOR with current
        # value arr[i]
        curr_xor = 0
 
        M = 2 ** 30
 
        curr = head
 
        for j in range(30, -1, -1):
 
            # Finding ith bit
            val = (arr[i] >> j) & 1
 
            # Check if the bit is 0
            if (val == 0):
 
                # If right node exists
                if (curr.right != None):
 
                    # Update the currentXOR
                    curr_xor += M
                    curr = curr.right
                else:
                    curr = curr.left
 
            else:
 
                # Check if left node exists
                if (curr.left != None):
 
                    # Update the currentXOR
                    curr_xor += M
                    curr = curr.left
                else:
                    curr = curr.right
 
            # Update M to M/2 for next set bit
            M = M//2
 
        # Update the maximum XOR
        ans = max(ans, curr_xor)
 
    # Return the maximum XOR found
    return ans
 
# Driver Code
 
# Given array arr
arr = [1, 2, 3, 4]
 
N = len(arr)
 
# Function call
print(findMaximumXOR(arr, N))
 
# This code is contributed by Saurbah Jaiswal
 
 

C#




// C# program for
// the above approach
using System;
class GFG{
 
// Structure of Tree
public class node
{
  public node left;
  public node right;
};
 
// Function to insert binary
// representation of element
// x in the Tree
static void insert(int x,
                   node head)
{
  // Store the head
  node curr = head;
 
  for(int i = 30; i >= 0; i--)
  {
    // Find the i-th bit
    int val = (x >> i) & 1;
 
    if (val == 0)
    {
      // If curr.left is null
      if (curr.left == null)
        curr.left = new node();
 
      // Update curr to curr.left
      curr = curr.left;
    }
    else
    {
      // If curr.right is null
      if (curr.right == null)
        curr.right = new node();
 
      // Update curr to curr.right
      curr = curr.right;
    }
  }
}
 
// Function that finds the maximum
// Bitwise XOR value for all
// such pairs
static int findMaximumXOR(int []arr,
                          int n)
{   
  // Head Node of Tree
  node head = new node();
 
  // Insert each element in tree
  for(int i = 0; i < n; i++)
  {
    insert(arr[i], head);
  }
 
  // Stores the maximum XOR value
  int ans = 0;
 
  // Traverse the given array
  for(int i = 0; i < n; i++)
  {
    // Stores the XOR with
    // current value arr[i]
    int curr_xor = 0;
 
    int M = (int)Math.Pow(2, 30);
    node curr = head;
 
    for(int j = 30; j >= 0; j--)
    {
      // Finding ith bit
      int val = (arr[i] >> j) & 1;
 
      // Check if the bit is 0
      if (val == 0)
      {
        // If right node exists
        if (curr.right != null)
        {
          // Update the currentXOR
          curr_xor += M;
          curr = curr.right;
        }
        else
        {
          curr = curr.left;
        }
      }
 
      else
      {
        // Check if left node exists
        if (curr.left != null)
        {
          // Update the currentXOR
          curr_xor += M;
          curr = curr.left;
        }
        else
        {
          curr = curr.right;
        }
      }
 
      // Update M to M/2
      // for next set bit
      M /= 2;
    }
 
    // Update the maximum XOR
    ans = Math.Max(ans, curr_xor);
  }
 
  // Return the maximum
  // XOR found
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{   
  // Given array []arr
  int []arr = {1, 2, 3, 4};
 
  int N = arr.Length;
 
  // Function call
  Console.Write(findMaximumXOR(arr, N));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
// javascript program for the above approach
 
    // Structure of Trie
     class node {
         constructor() {
                 
                this.left = null;
                this.right = null;
            }
     }
    // Function to insert binary
    // representation of element x
    // in the Trie
    function insert(x,  head) {
 
        // Store the head
        var curr = head;
 
        for (i = 30; i >= 0; i--) {
 
            // Find the i-th bit
            var val = (x >> i) & 1;
 
            if (val == 0) {
 
                // If curr.left is null
                if (curr.left == null)
                    curr.left = new node();
 
                // Update curr to curr.left
                curr = curr.left;
            } else {
 
                // If curr.right is null
                if (curr.right == null)
                    curr.right = new node();
 
                // Update curr to curr.right
                curr = curr.right;
            }
        }
    }
 
    // Function that finds the maximum
    // Bitwise XOR value for all such pairs
    function findMaximumXOR(arr , n) {
 
        // head Node of Trie
        var head = new node();
 
        // Insert each element in trie
        for (var i = 0; i < n; i++) {
            insert(arr[i], head);
        }
 
        // Stores the maximum XOR value
        var ans = 0;
 
        // Traverse the given array
        for (i = 0; i < n; i++) {
 
            // Stores the XOR with current
            // value arr[i]
            var curr_xor = 0;
 
            var M = parseInt( Math.pow(2, 30));
 
            var curr = head;
 
            for (j = 30; j >= 0; j--) {
 
                // Finding ith bit
                var val = (arr[i] >> j) & 1;
 
                // Check if the bit is 0
                if (val == 0) {
 
                    // If right node exists
                    if (curr.right != null) {
 
                        // Update the currentXOR
                        curr_xor += M;
                        curr = curr.right;
                    } else {
                        curr = curr.left;
                    }
                }
 
                else {
 
                    // Check if left node exists
                    if (curr.left != null) {
 
                        // Update the currentXOR
                        curr_xor += M;
                        curr = curr.left;
                    } else {
                        curr = curr.right;
                    }
                }
 
                // Update M to M/2 for next set bit
                M = parseInt(M/2);
            }
 
            // Update the maximum XOR
            ans = Math.max(ans, curr_xor);
        }
 
        // Return the maximum XOR found
        return ans;
    }
 
    // Driver Code
     
 
        // Given array arr
        var arr = [ 1, 2, 3, 4 ];
 
        var N = arr.length;
 
        // Function call
        document.write(findMaximumXOR(arr, N));
 
// This code is contributed by umadevi9616
</script>
 
 
Output: 
7

 

Time Complexity: O(32*N)
Auxiliary Space: O(32*N)



Next Article
Maximum XOR of Two Numbers in an Array

S

single__loop
Improve
Article Tags :
  • Advanced Data Structure
  • Arrays
  • Bit Magic
  • DSA
  • Mathematical
  • Searching
  • Bitwise-XOR
  • Trie
Practice Tags :
  • Advanced Data Structure
  • Arrays
  • Bit Magic
  • Mathematical
  • Searching
  • Trie

Similar Reads

  • Maximum XOR of Two Numbers in an Array
    Given an array arr[] of non-negative integers. The task is to find the maximum possible XOR of any two elements of the array. Example: Input: arr[] = [26, 100, 25, 13, 4, 14]Output: 126 Explanation: XOR of 26 ^ 100 = 126, which is the maximum possible XOR. Input: arr[] = [1, 2, 3, 4, 5, 6, 7]Output:
    15 min read
  • Maximum OR of Two Numbers in an Array
    Given an array Arr of non-negative integers of size N, the task is to find the maximum possible OR between two numbers present in the array. Example: Input: Arr = {25, 10, 2, 8, 5, 3}Output: 29 Input: Arr = {1, 2, 3, 4, 5, 6, 7}Output: 7 Naive Approach: A Simple Solution is to generate all pairs of
    4 min read
  • Maximum XOR of Two Binary Numbers after shuffling their bits.
    Given two n-bit integers a and b, find the maximum possible value of (a' xor b') where a' is a shuffle-a, b' is a shuffle-b and xor is the bitwise xor operator. Note: Consider a n-bit integer a. We call an integer a' as shuffle-a if a' can be obtained by shuffling the bits of a in its binary represe
    8 min read
  • Maximum sum of minimums of pairs in an array
    Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1,
    4 min read
  • Minimize product of maximum numbers in two Array using swaps | Set 2
    Given two arrays arr1[] and arr2[] of N size each. Select any index i and swap the element arr1[i] and arr2[i]. By applying this operation any number of times(possibly none) find the minimum possible product of maximum elements from array arr1[] and arr2[]. Examples: Input: N = 6arr1[] = {1, 2, 6, 5
    6 min read
  • Maximum OR value of a pair in an array
    Given an array arr[] of N positive elements. The task is to find the maximum bitwise OR value of a pair from the given array.Examples: Input: arr[] = {4, 8, 12, 16} Output: 28 (12, 16) is the pair with the maximum bitwise OR. 12 | 16 = 28 Input: arr[] = {4, 8, 16, 2} Output: 24 Approach: Iterate ove
    4 min read
  • Maximize Bitwise XOR of K with two numbers from Array
    Given an integer K and an array arr[] of size N, the task is to choose two elements from the array in such a way that the Bitwise XOR of those two with K (i.e. K ⊕ First chosen element ⊕ Second chosen element) is the maximum. Note: Any array element can be chosen as many times as possible Examples:
    15+ min read
  • Maximum Sum of Array with given MEX
    Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions: Size of the array = NMEX of the array = KAll array elements should be at most XAmong all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no
    7 min read
  • Maximize sum of selected numbers from Array to empty it | Set 2
    Given an array arr[] of N integers, the task is to maximize the sum of selected numbers over all the operations such that in each operation, choose a number Ai, delete one occurrence of it and delete all occurrences of Ai - 1 and Ai + 1 (if they exist) in the array until the array gets empty. Exampl
    7 min read
  • Maximum XOR Queries With an Element From Array
    Given an array arr[] of size n containing non-negative integers and also given a list of q queries in a 2D array queries[][], where each query is of the form [xi, mi]. For each query, you need to find the maximum value of (xi XOR arr[j]) such that arr[j] is less than or equal to mi. In simple terms,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences