Taro Logo

Longest Subsequence With Non-Zero Bitwise XOR

#195 Most AskedMedium
0 views
Topics:
ArraysGreedy AlgorithmsBit Manipulation

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 <= 105
  • 0 <= nums[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in the input array, and can they contain negative numbers or zeros?
  2. What should be returned if the entire array has a bitwise XOR sum of zero and no valid non-zero subsequence can be formed?
  3. Are duplicate values allowed in the input array, and if so, can we pick multiple identical elements from different indices?
  4. Does the order of elements in the original array matter, or are we strictly looking for the maximum length of any subsequence?
  5. If multiple subsequences achieve the maximum possible length with a non-zero XOR sum, does it matter which one we base our length calculation on?

Brute Force Solution

Approach

This solution finds the length of the longest subsequence whose cumulative bitwise XOR sum is non-zero. If every element in the array is zero, no subsequence can have a non-zero bitwise XOR. When the XOR sum of the entire array is already non-zero, the entire array is the longest valid subsequence, and otherwise removing any non-zero element results in a valid subsequence of length n minus one.

Here's how the algorithm would work step-by-step:

  1. Check whether the input array contains at least one non-zero number.
  2. Return 0 immediately if all numbers in the array are 0.
  3. Compute the bitwise XOR sum across all elements in the array.
  4. Return the full length of the array if the overall XOR sum is not zero.
  5. Return the array length minus one if the overall XOR sum is zero, as excluding one non-zero element flips the XOR sum to non-zero.

Code Implementation

def longest_subsequence(nums):
    # Check if there is any non-zero element in the array
    has_non_zero = False
    for value in nums:
        if value != 0:
            has_non_zero = True
            break
    if not has_non_zero:
        return 0
    # Calculate the XOR sum of all elements in nums
    total_xor = 0
    for value in nums:
        total_xor ^= value
    # If the total XOR sum is non-zero, the entire array is valid
    if total_xor != 0:
        return len(nums)
    # Otherwise, removing any non-zero element yields a non-zero XOR sum
    return len(nums) - 1

Big(O) Analysis

Time Complexity
O(n) – The solution iterates through the array of length n a constant number of times to check for non-zero elements and compute the total XOR sum.
Space Complexity
O(1) – Only a few auxiliary variables are used to store the running XOR sum and flags, requiring constant extra memory.

Optimal Solution

Approach

Instead of checking every single combination of items, we can use a clever mathematical shortcut. If combining everything together gives a non-zero result, we can just keep everything. If it gives a zero result, we only ever need to remove at most one single item to make the result non-zero.

Here's how the algorithm would work step-by-step:

  1. Look at the entire collection of items all together and combine them using the special bitwise merging rule.
  2. Check if the final combined result is something other than zero.
  3. If the combined result is indeed different from zero, realize that keeping every single item gives you the longest possible winning collection, so you are already finished.
  4. If the combined result happens to be zero, it means the entire group cancels itself out.
  5. To fix a total cancellation of zero, you only need to look at any single item that is different from the others and remove it.
  6. Once you remove that single conflicting item, the remaining group is guaranteed to have a combined result that is not zero.
  7. Count the size of this slightly smaller group, knowing it is the absolute maximum number of items you can possibly keep.

Code Implementation

def longest_subsequence(item_collection):
    total_xor_result = 0
    for current_item in item_collection:
        total_xor_result ^= current_item

    # If the total XOR is non-zero, keeping all items yields the maximum possible length.
    if total_xor_result != 0:
        return len(item_collection)

    # If total XOR is zero, we must find an item to remove that breaks the zero-sum cancellation.
    for current_item in item_collection:
        if current_item != 0:
            # Removing any single non-zero item breaks the cancellation and guarantees a non-zero result.
            return len(item_collection) - 1

    return 0

Big(O) Analysis

Time Complexity
O(n) – To find the total bitwise XOR of the collection, we must iterate through all n elements of the array once. If the total is zero, we perform a constant time scan to find any non-zero element to remove. The cost is driven entirely by this single pass over the input size n. This results in approximately n operations, which simplifies directly to O(n).
Space Complexity
O(1) – The algorithm only requires a few constant-size primitive variables to keep track of the total bitwise XOR result and loop indices. No extra data structures, arrays, or recursive call stacks are created during the process. Therefore, the auxiliary space remains entirely constant regardless of the input size N, making it O(1) space complexity.

Edge Cases

Array where the XOR sum of all elements is already non-zero
How to Handle:
The greedy approach immediately takes the entire array as the maximum length subsequence.
Array where the XOR sum of all elements is zero
How to Handle:
Removing any single element will break the zero sum, so the solution returns the array length minus one.
Array containing only zeros
How to Handle:
Since the XOR sum of any combination of zeros is always zero, no valid subsequence exists and the function returns zero.
Array with a single non-zero element
How to Handle:
The single element itself forms a valid subsequence with a non-zero XOR sum, returning a length of one.
Array with a single zero element
How to Handle:
No non-zero subsequence can be formed, so the solution returns a length of zero.
Array containing negative numbers
How to Handle:
Bitwise operations in languages like Java and C++ treat integers as two's complement, correctly processing negative values.
Maximum sized inputs with up to 10^5 elements
How to Handle:
The O(n) linear time complexity allows the algorithm to comfortably execute well within standard time limits.
All elements in the array are identical and non-zero
How to Handle:
An even count yields a zero XOR sum requiring the removal of one element, while an odd count allows taking all of them.
0/257 completed