Skip to content

Commit e5e0a83

Browse files
authored
Added task 3755
1 parent 804e829 commit e5e0a83

3 files changed

Lines changed: 90 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package g3701_3800.s3755_find_maximum_balanced_xor_subarray_length;
2+
3+
// #Medium #Array #Hash_Table #Bit_Manipulation #Prefix_Sum #Senior #Weekly_Contest_477
4+
// #2026_04_25_Time_91_ms_(98.50%)_Space_256.08_MB_(93.23%)
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
public class Solution {
10+
public int maxBalancedSubarray(int[] nums) {
11+
int n = nums.length;
12+
int ans = 0;
13+
int xor = 0;
14+
int diff = n;
15+
Map<Long, Integer> pos = new HashMap<>(n + 1, 1);
16+
pos.put((long) xor << 20 | diff, -1);
17+
for (int i = 0; i < n; i++) {
18+
xor ^= nums[i];
19+
diff += nums[i] % 2 != 0 ? 1 : -1;
20+
long key = (long) xor << 20 | diff;
21+
Integer j = pos.get(key);
22+
if (j != null) {
23+
ans = Math.max(ans, i - j);
24+
} else {
25+
pos.put(key, i);
26+
}
27+
}
28+
return ans;
29+
}
30+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
3755\. Find Maximum Balanced XOR Subarray Length
2+
3+
Medium
4+
5+
Given an integer array `nums`, return the **length** of the **longest **non-empty subarrays**** that has a bitwise XOR of zero and contains an **equal** number of **even** and **odd** numbers. If no such subarray exists, return 0.
6+
7+
**Example 1:**
8+
9+
**Input:** nums = [3,1,3,2,0]
10+
11+
**Output:** 4
12+
13+
**Explanation:**
14+
15+
The subarray `[1, 3, 2, 0]` has bitwise XOR `1 XOR 3 XOR 2 XOR 0 = 0` and contains 2 even and 2 odd numbers.
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [3,2,8,5,4,14,9,15]
20+
21+
**Output:** 8
22+
23+
**Explanation:**
24+
25+
The whole array has bitwise XOR `0` and contains 4 even and 4 odd numbers.
26+
27+
**Example 3:**
28+
29+
**Input:** nums = [0]
30+
31+
**Output:** 0
32+
33+
**Explanation:**
34+
35+
No non-empty subarray satisfies both conditions.
36+
37+
**Constraints:**
38+
39+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
40+
* <code>0 <= nums[i] <= 10<sup>9</sup></code>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package g3701_3800.s3755_find_maximum_balanced_xor_subarray_length;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void maxBalancedSubarray() {
11+
assertThat(new Solution().maxBalancedSubarray(new int[] {3, 1, 3, 2, 0}), equalTo(4));
12+
}
13+
14+
@Test
15+
void maxBalancedSubarray2() {
16+
assertThat(
17+
new Solution().maxBalancedSubarray(new int[] {3, 2, 8, 5, 4, 14, 9, 15}),
18+
equalTo(8));
19+
}
20+
}

0 commit comments

Comments
 (0)