[LeetCode] Longest Subsequence With Non-Zero Bitwise XOR

3702. Longest Subsequence With Non-Zero Bitwise XOR

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int longestSubsequence(vector<int>& nums) {
int bit = 0, notZero = 0;
for(auto& n : nums) {
if(n) {
notZero++;
bit ^= n;
}
}
return bit ? nums.size() : notZero ? nums.size() - 1 : 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/12/PS/LeetCode/longest-subsequence-with-non-zero-bitwise-xor/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.