#3877

Minimum Removals to Achieve Target XOR

Medium
ArrayDynamic ProgrammingBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * 2^(n/2))
Space
O(1)
O(n)
💡

Intuition

Time O(n * 2^(n/2))Space O(n)

We can split the array into two halves, calculate all possible XORs for each half, and use a hash map to find pairs that achieve the target XOR.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split nums into two halves and calculate all possible XORs for each half.
  2. 2Step 2: Store the XORs of the first half in a hash map with their counts.
  3. 3Step 3: For each XOR from the second half, check if (target XOR current XOR) exists in the hash map and calculate the minimum removals.
solution.py29 lines
1from collections import defaultdict
2
3def min_removals(nums, target):
4    n = len(nums)
5    half = n // 2
6    first_half = nums[:half]
7    second_half = nums[half:]
8    xor_map = defaultdict(int)
9
10    def compute_xors(arr):
11        xors = []
12        for r in range(len(arr) + 1):
13            for subset in combinations(arr, r):
14                xors.append(reduce(lambda x, y: x ^ y, subset, 0))
15        return xors
16
17    xors1 = compute_xors(first_half)
18    xors2 = compute_xors(second_half)
19
20    for x in xors1:
21        xor_map[x] += 1
22
23    min_removals = float('inf')
24    for x in xors2:
25        required = target ^ x
26        if required in xor_map:
27            min_removals = min(min_removals, n - (xor_map[required] + len(xors2)))
28
29    return min_removals if min_removals != float('inf') else -1

Complexity note: We generate subsets for half the array, leading to O(2^(n/2)) combinations, and store them in a hash map, which takes O(n).

  • 1XOR of an empty array is 0.
  • 2Using hash maps can optimize subset sum problems.

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