LeetCode #3630 — HARD

Partition Array for Maximum XOR and AND

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.

Partition the array into three (possibly empty) subsequences A, B, and C such that every element of nums belongs to exactly one subsequence.

Your goal is to maximize the value of: XOR(A) + AND(B) + XOR(C)

where:

  • XOR(arr) denotes the bitwise XOR of all elements in arr. If arr is empty, its value is defined as 0.
  • AND(arr) denotes the bitwise AND of all elements in arr. If arr is empty, its value is defined as 0.

Return the maximum value achievable.

Note: If multiple partitions result in the same maximum sum, you can consider any one of them.

Example 1:

Input: nums = [2,3]

Output: 5

Explanation:

One optimal partition is:

  • A = [3], XOR(A) = 3
  • B = [2], AND(B) = 2
  • C = [], XOR(C) = 0

The maximum value of: XOR(A) + AND(B) + XOR(C) = 3 + 2 + 0 = 5. Thus, the answer is 5.

Example 2:

Input: nums = [1,3,2]

Output: 6

Explanation:

One optimal partition is:

  • A = [1], XOR(A) = 1
  • B = [2], AND(B) = 2
  • C = [3], XOR(C) = 3

The maximum value of: XOR(A) + AND(B) + XOR(C) = 1 + 2 + 3 = 6. Thus, the answer is 6.

Example 3:

Input: nums = [2,3,6,7]

Output: 15

Explanation:

One optimal partition is:

  • A = [7], XOR(A) = 7
  • B = [2,3], AND(B) = 2
  • C = [6], XOR(C) = 6

The maximum value of: XOR(A) + AND(B) + XOR(C) = 7 + 2 + 6 = 15. Thus, the answer is 15.

Constraints:

  • 1 <= nums.length <= 19
  • 1 <= 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. Partition the array into three (possibly empty) subsequences A, B, and C such that every element of nums belongs to exactly one subsequence. Your goal is to maximize the value of: XOR(A) + AND(B) + XOR(C) where: XOR(arr) denotes the bitwise XOR of all elements in arr. If arr is empty, its value is defined as 0. AND(arr) denotes the bitwise AND of all elements in arr. If arr is empty, its value is defined as 0. Return the maximum value achievable. Note: If multiple partitions result in the same maximum sum, you can consider any one of them.

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

[2,3]

Example 2

[1,3,2]

Example 3

[2,3,6,7]
Step 02

Core Insight

What unlocks the optimal approach

  • Brute-force all subsets for <code>B</code>.
  • Let <code>s</code> = XOR of all elements not in <code>B</code>.
  • We want to choose a value <code>x</code> (a subset‐XOR of the "remaining" elements) to maximize <code>x + (s XOR x)</code>.
  • Observe that <code>x + (s XOR x) = s + 2 * (x AND ~s)</code>.
  • To do this efficiently, build a linear XOR basis over the values <code>nums[j] & ~s</code> for each index <code>j</code> not in <code>B</code>.
  • Finally, greedily extract the maximum <code>x</code> from that basis.
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 #3630: Partition Array for Maximum XOR and AND
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3630: Partition Array for Maximum XOR and AND
// package main
// 
// import (
// 	"math/bits"
// 	"slices"
// )
// 
// // https://space.bilibili.com/206214
// // 线性基模板
// type xorBasis []int
// 
// func (b xorBasis) insert(x int) {
// 	for x > 0 {
// 		i := bits.Len(uint(x)) - 1 // x 的最高位
// 		if b[i] == 0 {             // x 和之前的基是线性无关的
// 			b[i] = x // 新增一个基,最高位为 i
// 			return
// 		}
// 		x ^= b[i] // 保证参与 maxXor 的基的最高位是互不相同的,方便我们贪心
// 	}
// 	// 正常循环结束,此时 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 maximizeXorAndXor(nums []int) int64 {
// 	n := len(nums)
// 	type pair struct{ and, xor, or int } // 多算一个子集 OR,用于剪枝
// 	subSum := make([]pair, 1<<n)
// 	subSum[0].and = -1
// 	for i, x := range nums {
// 		highBit := 1 << i
// 		for mask, p := range subSum[:highBit] {
// 			subSum[highBit|mask] = pair{p.and & x, p.xor ^ x, p.or | x}
// 		}
// 	}
// 	subSum[0].and = 0
// 
// 	sz := bits.Len(uint(slices.Max(nums)))
// 	b := make(xorBasis, sz)
// 	maxXor2 := func(sub uint) (res int) {
// 		clear(b)
// 		xor := subSum[sub].xor
// 		for ; sub > 0; sub &= sub - 1 {
// 			x := nums[bits.TrailingZeros(sub)]
// 			b.insert(x &^ xor) // 只考虑有偶数个 1 的比特位(xor 在这些比特位上是 0)
// 		}
// 		return xor + b.maxXor()*2
// 	}
// 
// 	ans := 0
// 	u := 1<<n - 1
// 	for i, p := range subSum {
// 		j := u ^ i
// 		if p.and+subSum[j].or*2-subSum[j].xor > ans { // 有机会让 ans 变得更大
// 			ans = max(ans, p.and+maxXor2(uint(j)))
// 		}
// 	}
// 	return int64(ans)
// }
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.