#2935
Maximum Strong Pair XOR II
HardArrayHash TableBit ManipulationTrieSliding WindowHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array and leveraging the condition for strong pairs, we can significantly reduce the number of pairs we need to check. This allows us to focus on pairs that are likely to yield a high XOR.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array nums.
- 2Step 2: Initialize max_xor to 0.
- 3Step 3: Iterate through the sorted array and for each element, find valid pairs that satisfy the strong pair condition y <= 2 * x.
- 4Step 4: For each valid pair, calculate the XOR and update max_xor if this XOR is greater.
solution.py11 lines
1# Full working Python code
2
3def max_strong_pair_xor(nums):
4 nums.sort()
5 max_xor = 0
6 n = len(nums)
7 for i in range(n):
8 for j in range(i, n):
9 if nums[j] <= 2 * nums[i]:
10 max_xor = max(max_xor, nums[i] ^ nums[j])
11 return max_xorℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, and the nested loop runs in O(n) in the worst case, leading to an overall complexity of O(n log n). The space complexity is O(1) since we are not using additional data structures.
- 1Sorting the array helps in efficiently finding valid pairs that satisfy the strong pair condition.
- 2The condition for strong pairs can be simplified to y <= 2 * x, which reduces the number of pairs we need to check.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.