1. All Pairs Nested Loops
Intuition
Two nested loops comparing all N*(N-1)/2 pairs. Compute nums[i] ^ nums[j] and maintain the maximum seen.
When to apply: Tiny inputs (N <= 1000).
Algorithm
- Step 1: Initialize
maxXor = 0. - Step 2: Loop
ifrom 0 to N-1. - Step 3: Loop
jfromito N-1. - Step 4: Update
maxXor = max(maxXor, nums[i] ^ nums[j]). - Step 5: Return
maxXor.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: int findMaximumXOR(vector<int>& nums) { int maxXor = 0; int n = nums.size(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { maxXor = max(maxXor, nums[i] ^ nums[j]); } } return maxXor; }}; int main() { Solution sol; vector<int> nums = {3, 10, 5, 25, 2, 8}; cout << "Max XOR: " << sol.findMaximumXOR(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Evaluates all N*(N-1)/2 pairs in O(1) arithmetic each. - Space complexity:
O(1)— Only scalar variables used.
Why Brute Force Doesn't Scale:
N = 2 * 105 pairs require 20 billion operations, exceeding the 1-second limit by 200x.
Binary Trie checks exactly 31 bits per number, executing 31 * 200,000 ~ 6.2 million operations in ~50ms.