#2932

Maximum Strong Pair XOR I

Easy
ArrayHash TableBit ManipulationTrieSliding WindowHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages the properties of XOR and the strong pair condition to reduce the number of pairs we need to check. By sorting the array and only checking adjacent elements, we can efficiently find the maximum XOR.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Initialize max_xor to 0.
  3. 3Step 3: Iterate through the sorted array and check adjacent pairs (nums[i], nums[i+1]).
  4. 4Step 4: For each adjacent pair, check if they satisfy the strong pair condition. If they do, calculate their XOR and update max_xor.
  5. 5Step 5: Return max_xor after checking all adjacent pairs.
solution.py14 lines
1# Full working Python code
2
3def max_strong_pair_xor_optimal(nums):
4    nums.sort()
5    max_xor = 0
6    n = len(nums)
7    for i in range(n - 1):
8        if abs(nums[i] - nums[i + 1]) <= min(nums[i], nums[i + 1]):
9            max_xor = max(max_xor, nums[i] ^ nums[i + 1])
10    return max_xor
11
12# Example usage
13print(max_strong_pair_xor_optimal([1, 2, 3, 4, 5]))  # Output: 7
14

Complexity note: The time complexity is O(n log n) due to sorting the array, while the space complexity is O(1) since we are not using any additional data structures that grow with input size.

  • 1Strong pairs are defined by the relationship between the two numbers, which can be leveraged to limit the pairs we check.
  • 2Sorting the array allows us to efficiently find valid pairs by only checking adjacent elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.