Minimum Removals to Achieve Target XOR Problem
Description
LeetCode Problem 3877.
You are given an integer array nums and an integer target.
You may remove any number of elements from nums (possibly zero).
Return the minimum number of removals required so that the bitwise XOR of the remaining elements equals target. If it is impossible to achieve target, return -1.
The bitwise XOR of an empty array is 0.
Example 1:
Input: nums = [1,2,3], target = 2
Output: 1
Explanation:
- Removing nums[1] = 2 leaves [nums[0], nums[2]] = [1, 3].
- The XOR of [1, 3] is 2, which equals target.
- It is not possible to achieve XOR = 2 in less than one removal, therefore the answer is 1.
Example 2:
Input: nums = [2,4], target = 1
Output: -1
Explanation:
It is impossible to remove elements to achieve target. Thus, the answer is -1.
Example 3:
Input: nums = [7], target = 7
Output: 0
Explanation:
The XOR of all elements is nums[0] = 7, which equals target. Thus, no removal is needed.
Constraints:
1 <= nums.length <= 400 <= nums[i] <= 10^40 <= target <= 10^4
Solution
Approach: Dynamic Programming
Removing the fewest elements means keeping the most. Let f[i][j] be the maximum number of elements we can keep from the first i elements so that their XOR is j. Start with f[0][0] = 0 and every other f[0][j] as negative infinity.
For nums[i - 1] there are two choices: skip it, giving f[i - 1][j], or keep it, giving f[i - 1][j ^ nums[i - 1]] + 1. Take the larger one.
Let m be the number of bits of the largest element. All XOR values stay below 2^m, so if target >= 2^m the answer is -1. Otherwise, if f[n][target] is negative the answer is -1, and if not it is n - f[n][target].
Complexity: time O(n * 2^m), space O(n * 2^m), where n is the length of the array and m is the number of bits of its largest element.
class Solution:
def minRemovals(self, nums: List[int], target: int) -> int:
m = max(nums).bit_length()
if (1 << m) <= target:
return -1
n = len(nums)
f = [[-10**9] * (1 << m) for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(1 << m):
f[i][j] = max(f[i - 1][j], f[i - 1][j ^ x] + 1)
if f[n][target] < 0:
return -1
return n - f[n][target]