Maximum XOR After Operations — LeetCode 2317 Python Solution

MediumBit ManipulationArrayMath
Problem
#2317
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).

Example

Input
nums = [3,2,4,6]
Output
7
Explanation
Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.

Python solution

Python
class Solution:
    def maximumXOR(self, nums: List[int]) -> int:
        return reduce(or_, nums)

Complexity

MeasureComplexity
TimeO(n), where n is the length of \textit{nums}
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2317. Maximum XOR After Operations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2317. Maximum XOR After Operations?
LeetCode 2317. Maximum XOR After Operations is rated Medium on LeetCode.
What is the time complexity of LeetCode 2317. Maximum XOR After Operations?
The Python solution on this page runs in O(n), where n is the length of \textit{nums}.
What is the space complexity of LeetCode 2317. Maximum XOR After Operations?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2317. Maximum XOR After Operations cover?
LeetCode 2317. Maximum XOR After Operations is tagged Bit Manipulation, Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview