712544. Maximum XOR With an Element From Array

Hard

Maximum XOR With an Element From Array

Summary

The problem involves finding the maximum possible XOR value that can be obtained by performing a bitwise XOR operation with each element in an array, given another target element. The goal is to maximize the sum of all these XOR values.

Detailed Explanation

We can solve this problem by iterating through each element in the array and calculating the XOR value with the target element. We keep track of the maximum XOR value seen so far. This approach has a time complexity of O(n), where n is the size of the array, since we need to iterate through all elements.

Here's a step-by-step breakdown:

  1. Initialize a variable max_xor to 0.
  2. Iterate through each element x in the array:
    • Calculate the XOR value xor_val between x and the target element.
    • Update max_xor if xor_val is greater than max_xor.
  3. Return max_xor.

Time complexity: O(n) Space complexity: O(1)

Here's an ASCII art diagram to illustrate this:

    +---------------+
    |  Array [a, b, c] |
    +---------------+
    |      Target    |
    |  element (t)   |
    +---------------+
    |  XOR (a, t) = a^t|
    |  XOR (b, t) = b^t|
    |  ...
    |  max_xor = max(a^t, b^t, ...)|
    +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int findMaximumXOR(int[] nums, int target) {
        int max_xor = 0;
        for (int num : nums) {
            int xor_val = num ^ target;
            if (xor_val > max_xor) {
                max_xor = xor_val;
            }
        }
        return max_xor;
    }

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.