DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

Maximum XOR of Two Numbers in an Array

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

Example 1:

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

Example 2:

Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127

Constraints:

  • 1 <= nums.length <= 2 * 105
  • 0 <= nums[i] <= 231 - 1

SOLUTION:

class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        n = len(nums)
        maxx = 0
        mask = 0
        se = set()
        for i in range(30, -1, -1):
            mask |= (1 << i)
            newMaxx = maxx | (1 << i)
            for i in range(n):
                se.add(nums[i] & mask)
            for prefix in se:
                if (newMaxx ^ prefix) in se:
                    maxx = newMaxx
                    break
            se.clear()
        return maxx
Enter fullscreen mode Exit fullscreen mode

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay