Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximum XOR of Two Numbers in an Array

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "421" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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

Explanation

Here's the breakdown of the solution:

  • Greedy Bit-by-Bit Construction: Start from the most significant bit (MSB) and greedily try to maximize the XOR result bit by bit. For each bit position, we aim to set it to 1 in the final result.

  • Prefix Set: Maintain a set of prefixes of the numbers encountered so far, considering only the bits from the MSB down to the current bit position.

  • Check for Existence: For each bit position, iterate through the prefix set. If there exist two prefixes a and b in the set such that a ^ b = candidate (where candidate is the current maximum XOR result we're trying to achieve), then we can achieve a '1' in that bit position, and we update the max_xor result.

  • Time & Space Complexity: O(N * 31), where N is the number of elements in nums. O(N) for the space used by the set.

Code

    def find_maximum_xor(nums):
    """
    Finds the maximum XOR result of two numbers in an array.

    Args:
        nums: A list of integers.

    Returns:
        The maximum XOR result.
    """

    max_xor = 0
    mask = 0
    for i in range(31, -1, -1):
        mask |= (1 << i)
        prefix_set = set()
        for num in nums:
            prefix_set.add(num & mask)

        temp_max_xor = max_xor | (1 << i)  # Try to set the i-th bit to 1
        for prefix in prefix_set:
            if (temp_max_xor ^ prefix) in prefix_set:
                max_xor = temp_max_xor
                break

    return max_xor

More from this blog

C

Chatmagic blog

2894 posts