#3845

Maximum Subarray XOR with Bounded Range

Hard
ArrayBit ManipulationTrieQueueSliding WindowPrefix SumMonotonic Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a sliding window to maintain valid subarrays and a Trie to efficiently compute maximum XOR values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a Trie and a sliding window with two pointers to track valid subarrays.
  2. 2Step 2: For each end index, add the prefix XOR to the Trie and check for maximum XOR with valid prefix XORs.
  3. 3Step 3: Adjust the start index to maintain the condition max - min <= k.
solution.py40 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.count = 0
5class Trie:
6    def __init__(self):
7        self.root = TrieNode()
8    def insert(self, num):
9        node = self.root
10        for i in range(15, -1, -1):
11            bit = (num >> i) & 1
12            if bit not in node.children:
13                node.children[bit] = TrieNode()
14            node = node.children[bit]
15            node.count += 1
16    def maxXOR(self, num):
17        node = self.root
18        max_xor = 0
19        for i in range(15, -1, -1):
20            bit = (num >> i) & 1
21            if 1 - bit in node.children:
22                max_xor |= (1 << i)
23                node = node.children[1 - bit]
24            else:
25                node = node.children[bit]
26        return max_xor
27
28def maxSubarrayXOR(nums, k):
29    trie = Trie()
30    max_xor = 0
31    prefix_xor = 0
32    start = 0
33    for end in range(len(nums)):
34        prefix_xor ^= nums[end]
35        trie.insert(prefix_xor)
36        while max(nums[start:end + 1]) - min(nums[start:end + 1]) > k:
37            prefix_xor ^= nums[start]
38            start += 1
39        max_xor = max(max_xor, trie.maxXOR(prefix_xor))
40    return max_xor

Complexity note: Linear complexity due to the single pass through the array and efficient Trie operations.

  • 1XOR operation properties can be leveraged for maximum values.
  • 2Maintaining a sliding window helps in efficiently checking conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.