#3702

Longest Subsequence With Non-Zero Bitwise XOR

Medium
ArrayBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

If the XOR of the entire array is non-zero, the answer is the length of the array. If it's zero, removing one element may yield a non-zero XOR.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the XOR of the entire array.
  2. 2Step 2: If the XOR is non-zero, return the length of the array.
  3. 3Step 3: If the XOR is zero, return the length of the array minus one.
solution.py5 lines
1def longest_non_zero_xor(nums):
2    total_xor = 0
3    for num in nums:
4        total_xor ^= num
5    return len(nums) if total_xor != 0 else len(nums) - 1

Complexity note: Only one pass through the array is needed to compute the XOR, hence O(n).

  • 1The XOR of the entire array determines the possibility of a non-zero result.
  • 2Removing one element can change the XOR from zero to non-zero.

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