Longest Subsequence With Non-Zero Bitwise XOR Problem
Description
LeetCode Problem 3702.
You are given an integer array nums.
Return the length of the longest subsequence in nums whose bitwise XOR is non-zero. If no such subsequence exists, return 0.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation:
One longest subsequence is [2, 3]. The bitwise XOR is computed as 2 XOR 3 = 1, which is non-zero.
Example 2:
Input: nums = [2,3,4]
Output: 3
Explanation:
The longest subsequence is [2, 3, 4]. The bitwise XOR is computed as 2 XOR 3 XOR 4 = 5, which is non-zero.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Brain Teaser
If the bitwise XOR of all elements in the array is non-zero, then the entire array is the desired longest subsequence, with length equal to the array length.
If all elements in the array are zero, then there is no subsequence with non-zero bitwise XOR, so we return 0.
Otherwise, we can remove one non-zero element from the array to make the bitwise XOR of the remaining elements non-zero. The length of the longest subsequence is the array length minus 1.
Complexity: The time complexity is O(n), and the space complexity is O(1), where n is the length of array nums.
class Solution:
def longestSubsequence(self, nums: List[int]) -> int:
n = len(nums)
xor = cnt0 = 0
for x in nums:
xor ^= x
cnt0 += int(x == 0)
if xor:
return n
if cnt0 == n:
return 0
return n - 1