Skip to content

Get the Maximum XOR of Two Numbers in an Array in Java

The challenge

Given a non-empty array of numbers, a, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ ij < n.

Could you do this in O(n) runtime?


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

The solution in Java

We can very quickly resolve this challenge by performing a double loop and comparing our resultant:

class Solution { public int findMaximumXOR(int[] nums) { // store our maximum int max = ; // loop through all numbers for (int i=; i<nums.length; i++) { // loop through all our numbers again for (int j=; j<nums.length; j++) { // keep a temp of the XOR int tmp = nums[i] ^ nums[j]; // check if it's bigger if (tmp>max) max = tmp; } } // return our maximum return max; } }
Code language: Java (java)

While this solution does come to a correct answer, it is not in the O(n) of time due to our second loop, and our space complexity could be made better by not using an additional variable.

See also  Calculate the Surface Area and Volume of a Box with Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x