LeetCode #3845 — HARD

Maximum Subarray XOR with Bounded Range

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 a non-negative integer array nums and an integer k.

You must select a subarray of nums such that the difference between its maximum and minimum elements is at most k. The value of this subarray is the bitwise XOR of all elements in the subarray.

Return an integer denoting the maximum possible value of the selected subarray.

Example 1:

Input: nums = [5,4,5,6], k = 2

Output: 7

Explanation:

  • Select the subarray [5, 4, 5, 6].
  • The difference between its maximum and minimum elements is 6 - 4 = 2 <= k.
  • The value is 4 XOR 5 XOR 6 = 7.

Example 2:

Input: nums = [5,4,5,6], k = 1

Output: 6

Explanation:

  • Select the subarray [5, 4, 5, 6].
  • The difference between its maximum and minimum elements is 6 - 6 = 0 <= k.
  • The value is 6.

Constraints:

  • 1 <= nums.length <= 4 * 104
  • 0 <= nums[i] < 215
  • 0 <= k < 215

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 a non-negative integer array nums and an integer k. You must select a subarray of nums such that the difference between its maximum and minimum elements is at most k. The value of this subarray is the bitwise XOR of all elements in the subarray. Return an integer denoting the maximum possible value of the selected subarray.

Baseline thinking

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

Pattern signal: General problem-solving

Example 1

[5,4,5,6]
2

Example 2

[5,4,5,6]
1
Step 02

Core Insight

What unlocks the optimal approach

  • Maintain an active window such that the difference between its maximum and minimum is at most <code>k</code>
  • For all valid subarray-start indices <code>i</code>, insert their prefix xors <code>pref[i]</code> into a trie (use <code>pref[0] = 0</code>, <code>pref[i + 1] = pref[i] ^ nums[i]</code>); keep counts per node to support deletions as <code>L</code> moves
  • For each right index <code>r</code>, query the trie with <code>pref[r + 1]</code> to get the maximum <code>pref[r + 1] ^ pref[l]</code> for <code>l in [L, r]</code>
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 #3845: Maximum Subarray XOR with Bounded Range
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3845: Maximum Subarray XOR with Bounded Range
// package main
// 
// import "math/bits"
// 
// // https://space.bilibili.com/206214
// const width = 15 // nums[i] 二进制长度的最大值
// 
// type node struct {
// 	son  [2]*node
// 	leaf int // 子树叶子个数
// }
// 
// type trie struct {
// 	root *node
// }
// 
// func newTrie() *trie {
// 	return &trie{&node{}}
// }
// 
// func (t *trie) put(val int) {
// 	cur := t.root
// 	for i := width - 1; i >= 0; i-- {
// 		bit := val >> i & 1
// 		if cur.son[bit] == nil {
// 			cur.son[bit] = &node{}
// 		}
// 		cur = cur.son[bit]
// 		cur.leaf++
// 	}
// }
// 
// func (t *trie) del(val int) {
// 	cur := t.root
// 	for i := width - 1; i >= 0; i-- {
// 		cur = cur.son[val>>i&1]
// 		cur.leaf-- // 如果减成 0 了,说明子树是空的,可以理解成 cur == nil
// 	}
// }
// 
// func (t *trie) maxXor(val int) (ans int) {
// 	cur := t.root
// 	for i := width - 1; i >= 0; i-- {
// 		bit := val >> i & 1
// 		if cur.son[bit^1] != nil && cur.son[bit^1].leaf > 0 {
// 			ans |= 1 << i
// 			bit ^= 1
// 		}
// 		cur = cur.son[bit]
// 	}
// 	return
// }
// 
// func maxXor1(nums []int, k int) (ans int) {
// 	sum := make([]int, len(nums)+1)
// 	for i, x := range nums {
// 		sum[i+1] = sum[i] ^ x
// 	}
// 
// 	t := newTrie()
// 	var minQ, maxQ []int
// 	left := 0
// 	for right, x := range nums {
// 		// 1. 入
// 		t.put(sum[right])
// 
// 		for len(minQ) > 0 && x <= nums[minQ[len(minQ)-1]] {
// 			minQ = minQ[:len(minQ)-1]
// 		}
// 		minQ = append(minQ, right)
// 
// 		for len(maxQ) > 0 && x >= nums[maxQ[len(maxQ)-1]] {
// 			maxQ = maxQ[:len(maxQ)-1]
// 		}
// 		maxQ = append(maxQ, right)
// 
// 		// 2. 出
// 		for nums[maxQ[0]]-nums[minQ[0]] > k {
// 			t.del(sum[left])
// 			left++
// 			if minQ[0] < left {
// 				minQ = minQ[1:]
// 			}
// 			if maxQ[0] < left {
// 				maxQ = maxQ[1:]
// 			}
// 		}
// 
// 		// 3. 更新答案
// 		ans = max(ans, t.maxXor(sum[right+1]))
// 	}
// 	return
// }
// 
// func maxXor(nums []int, k int) (ans int) {
// 	// 预处理:当窗口右端点在 right 时,窗口左端点在 lefts[right]
// 	// 顺带算出前缀异或和、nums 的最大值
// 	n := len(nums)
// 	lefts := make([]int, n)
// 	sum := make([]int, len(nums)+1)
// 	mx := 0
// 	var minQ, maxQ []int
// 	left := 0
// 	for right, x := range nums {
// 		sum[right+1] = sum[right] ^ x
// 		mx = max(mx, x)
// 
// 		// 1. 入
// 		for len(minQ) > 0 && x <= nums[minQ[len(minQ)-1]] {
// 			minQ = minQ[:len(minQ)-1]
// 		}
// 		minQ = append(minQ, right)
// 
// 		for len(maxQ) > 0 && x >= nums[maxQ[len(maxQ)-1]] {
// 			maxQ = maxQ[:len(maxQ)-1]
// 		}
// 		maxQ = append(maxQ, right)
// 
// 		// 2. 出
// 		for nums[maxQ[0]]-nums[minQ[0]] > k {
// 			left++
// 			if minQ[0] < left {
// 				minQ = minQ[1:]
// 			}
// 			if maxQ[0] < left {
// 				maxQ = maxQ[1:]
// 			}
// 		}
// 
// 		// 3. 记录此时的 left
// 		lefts[right] = left
// 	}
// 
// 	// 试填法
// 	width := bits.Len(uint(mx))
// 	last := make([]int, 1<<width)
// 	for i := width - 1; i >= 0; i-- {
// 		for j := range 1 << (width - i) {
// 			last[j] = -1
// 		}
// 		last[0] = 0 // sum[0] = 0 的位置是 0
// 		ans <<= 1
// 		newAns := ans | 1
// 		for right, l := range lefts {
// 			s := sum[right+1] >> i   // 去掉低位,只看高位
// 			if last[newAns^s] >= l { // newAns^s 存在,且在窗口内
// 				ans = newAns // 最终答案第 i 位填 1
// 				break
// 			}
// 			last[s] = right + 1
// 		}
// 	}
// 
// 	return
// }
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)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.

OPTIMIZED
O(n) time
O(1) space

Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.

Shortcut: If you are using nested loops on an array, there is almost always an O(n) solution. Look for the right auxiliary state.
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.