#3755

Find Maximum Balanced XOR Subarray Length

Medium
ArrayHash TableBit ManipulationPrefix SumHash MapArray
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 prefix XOR and a hash map to track the first occurrence of each (pxor, diff) state, allowing for efficient length calculation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hash map to store the first occurrence of (pxor, diff) and set initial values.
  2. 2Step 2: Iterate through the array, updating the prefix XOR and the difference between even and odd counts.
  3. 3Step 3: Check if the current (pxor, diff) exists in the map; if it does, calculate the length and update max length.
solution.py13 lines
1def maxBalancedXOR(nums):
2    prefix_map = {(0, 0): -1}
3    pxor, evens, odds, max_len = 0, 0, 0, 0
4    for i, num in enumerate(nums):
5        pxor ^= num
6        if num % 2 == 0: evens += 1
7        else: odds += 1
8        diff = evens - odds
9        if (pxor, diff) in prefix_map:
10            max_len = max(max_len, i - prefix_map[(pxor, diff)])
11        else:
12            prefix_map[(pxor, diff)] = i
13    return max_len

Complexity note: Single pass through the array with a hash map for state tracking leads to linear time complexity.

  • 1Prefix XOR helps track cumulative XOR efficiently.
  • 2Using a hash map allows for quick lookups of previously seen states.

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