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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
[2], whose XOR is 2.[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:
[5], whose XOR is 5.[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 <= 1050 <= nums[i] <= 109Problem 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Greedy · Bit Manipulation
[1,2,3]
[5,2]
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()
// }
// 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()
}
# Accepted solution for LeetCode #3681: Maximum XOR of Subsequences
# Time: O(nlogr), r = max(nums)
# Space: O(r)
# bitmasks, greedy
class Solution(object):
def maxXorSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def max_xor_subset(nums): # Time: O(nlogr)
base = [0]*l
for x in nums: # gaussian elimination over GF(2)
for b in base:
if x^b < x:
x ^= b
if x:
base.append(x)
max_xor = 0
for b in base: # greedy
if (max_xor^b) > max_xor:
max_xor ^= b
return max_xor
l = max(nums).bit_length()
return max_xor_subset(nums)
# Time: O(nlogr), r = max(nums)
# Space: O(r)
# bitmasks, greedy
class Solution2(object):
def maxXorSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def max_xor_subset(nums): # Time: O(nlogr)
base = [0]*l
for x in nums: # gaussian elimination over GF(2)
for i in reversed(xrange(len(base))):
if not x&(1<<i):
continue
if base[i] == 0:
base[i] = x
break
x ^= base[i]
max_xor = 0
for b in reversed(base): # greedy
if (max_xor^b) > max_xor:
max_xor ^= b
return max_xor
l = max(nums).bit_length()
return max_xor_subset(nums)
// Accepted solution for LeetCode #3681: Maximum XOR of Subsequences
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// 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()
// }
// Accepted solution for LeetCode #3681: Maximum XOR of Subsequences
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// 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()
// }
Use this to step through a reusable interview workflow for this problem.
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 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.
Review these before coding to avoid predictable interview regressions.
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.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
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.