Back to Month
MEDIUM 15 Aug 2026 View on LeetCode

3702. Longest Subsequence With Non-Zero Bitwise XOR

</> Solution

class Solution {
    public int longestSubsequence(int[] nums) {
        int totalXor = 0;
        boolean hasNonZero = false;

        for (int num : nums) {
            totalXor ^= num;
            if (num != 0) {
                hasNonZero = true;
            }
        }

        int n = nums.length;

        if (totalXor != 0) {
            return n;
        }

        return hasNonZero ? n - 1 : 0;
    }
}

TIME COMPLEXITY

O(n)

SPACE COMPLEXITY

O(1)

TOPICS

Array Bit Manipulation Greedy Math