Maximum Strong Pair XOR II - Problem

You are given a 0-indexed integer array nums. A pair of integers x and y is called a strong pair if it satisfies the condition:

|x - y| <= min(x, y)

You need to select two integers from nums such that they form a strong pair and their bitwise XOR is the maximum among all strong pairs in the array.

Return the maximum XOR value out of all possible strong pairs in the array nums.

Note: You can pick the same integer twice to form a pair.

Input & Output

Example 1 — Basic Strong Pairs
$ Input: nums = [1,6,2,3]
Output: 5
💡 Note: Strong pairs: (1,1) with XOR=0, (2,2) with XOR=0, (3,3) with XOR=0, (2,3) with XOR=1, (1,2) with XOR=3, (1,3) with XOR=2, (6,6) with XOR=0. However, we need |x-y| <= min(x,y). Checking: |1-6|=5 > min(1,6)=1 (not strong), |2-3|=1 <= min(2,3)=2 (strong), etc. The maximum XOR is 5 from a valid strong pair.
Example 2 — Same Elements
$ Input: nums = [5,5,5]
Output: 0
💡 Note: All elements are the same, so all pairs are (5,5) with |5-5|=0 <= min(5,5)=5, making them strong pairs. The XOR of any pair is 5^5=0.
Example 3 — No Valid Pairs
$ Input: nums = [1,10]
Output: 0
💡 Note: Check pair (1,10): |1-10|=9 > min(1,10)=1, so not a strong pair. Check pairs with same element: (1,1) and (10,10) both give XOR=0. Maximum XOR is 0.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 220

Visualization

Tap to expand
Maximum Strong Pair XOR II INPUT nums array: 1 6 2 3 [0] [1] [2] [3] Strong Pair Condition: |x - y| <= min(x, y) Valid Strong Pairs: (2,3): |2-3|=1 <= 2 OK (3,6): |3-6|=3 <= 3 OK (2,2): |2-2|=0 <= 2 OK Sorted for sliding window: [1, 2, 3, 6] ALGORITHM STEPS 1 Sort Array Enable sliding window 2 Build Trie Binary trie for XOR 3 Sliding Window Maintain valid pairs 4 Find Max XOR Query trie for max Binary Trie Structure: R 0 1 3 XOR 6 = 011 XOR 110 = 101 FINAL RESULT Maximum XOR Strong Pair: Pair: (3, 6) 3 XOR 6 = 5 Output: 5 Verification: |3 - 6| = 3 min(3, 6) = 3 3 <= 3 : OK Binary: 3 = 011 6 = 110 5 = 101 Key Insight: Sorting enables sliding window: for sorted array, if nums[i] and nums[j] form strong pair, all elements between them also form strong pairs. The Trie efficiently finds max XOR by greedily choosing opposite bits. Time: O(n log n + n * 20), Space: O(n * 20) for 20-bit integers. TutorialsPoint - Maximum Strong Pair XOR II | Trie + Sliding Window Approach
Asked in
Google 25 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~45 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen