LeetCode #3681 — HARD

Maximum XOR of Subsequences

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums of length n where each element is a non-negative integer.

Select two subsequences of nums (they may be empty and are allowed to overlap), each preserving the original order of elements, and let:

  • X be the bitwise XOR of all elements in the first subsequence.
  • Y be the bitwise XOR of all elements in the second subsequence.

Return the maximum possible value of X XOR Y.

Note: The XOR of an empty subsequence is 0.

Example 1:

Input: nums = [1,2,3]

Output: 3

Explanation:

Choose subsequences:

  • First subsequence [2], whose XOR is 2.
  • Second subsequence [2,3], whose XOR is 1.

Then, XOR of both subsequences = 2 XOR 1 = 3.

This is the maximum XOR value achievable from any two subsequences.

Example 2:

Input: nums = [5,2]

Output: 7

Explanation:

Choose subsequences:

  • First subsequence [5], whose XOR is 5.
  • Second subsequence [2], whose XOR is 2.

Then, XOR of both subsequences = 5 XOR 2 = 7.

This is the maximum XOR value achievable from any two subsequences.

Constraints:

  • 2 <= nums.length <= 105
  • 0 <= nums[i] <= 109
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums of length n where each element is a non-negative integer. Select two subsequences of nums (they may be empty and are allowed to overlap), each preserving the original order of elements, and let: X be the bitwise XOR of all elements in the first subsequence. Y be the bitwise XOR of all elements in the second subsequence. Return the maximum possible value of X XOR Y. Note: The XOR of an empty subsequence is 0.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Greedy · Bit Manipulation

Example 1

[1,2,3]

Example 2

[5,2]
Step 02

Core Insight

What unlocks the optimal approach

  • Build a linear XOR basis from all numbers and take the maximum XOR achievable from it.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3681: Maximum XOR of Subsequences
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3681: Maximum XOR of Subsequences
// package main
// 
// import (
// 	"math/bits"
// 	"slices"
// )
// 
// // https://space.bilibili.com/206214
// type xorBasis []int
// 
// // n 为值域最大值 U 的二进制长度,例如 U=1e9 时 n=30
// func newXorBasis(n int) xorBasis {
// 	return make(xorBasis, n)
// }
// 
// func (b xorBasis) insert(x int) {
// 	// 从高到低遍历,保证计算 maxXor 的时候,参与 XOR 的基的最高位(或者说二进制长度)是互不相同的
// 	for i := len(b) - 1; i >= 0; i-- {
// 		if x>>i == 0 { // 由于大于 i 的位都被我们异或成了 0,所以 x>>i 的结果只能是 0 或 1
// 			continue
// 		}
// 		if b[i] == 0 { // x 和之前的基是线性无关的
// 			b[i] = x // 新增一个基,最高位为 i
// 			return
// 		}
// 		x ^= b[i] // 保证每个基的二进制长度互不相同
// 	}
// 	// 正常循环结束,此时 x=0,说明一开始的 x 可以被已有基表出,不是一个线性无关基
// }
// 
// func (b xorBasis) maxXor() (res int) {
// 	// 从高到低贪心:越高的位,越必须是 1
// 	// 由于每个位的基至多一个,所以每个位只需考虑异或一个基,若能变大,则异或之
// 	for i := len(b) - 1; i >= 0; i-- {
// 		res = max(res, res^b[i])
// 	}
// 	return
// }
// 
// func maxXorSubsequences(nums []int) int {
// 	u := slices.Max(nums)
// 	m := bits.Len(uint(u))
// 	b := newXorBasis(m)
// 	for _, x := range nums {
// 		b.insert(x)
// 	}
// 	return b.maxXor()
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

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

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.