leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit a3fc419862fc9771da68d2c4f1696496c2c0ac59
parent a3293e7b8ec4cb65724351b4ccba5dfeeaf5f46c
Author: Jack Sangdahl <jack@pngu.org>
Date:   Sat, 11 Apr 2026 17:01:05 -0600

3702. longest subsequence with non-zero bitwise xor

Diffstat:
Alongest_subseq_nz_xor.c | 28++++++++++++++++++++++++++++
Alongest_subseq_nz_xor.py | 26++++++++++++++++++++++++++
2 files changed, 54 insertions(+), 0 deletions(-)

diff --git a/longest_subseq_nz_xor.c b/longest_subseq_nz_xor.c @@ -0,0 +1,28 @@ +// 3702. Longest Subsequence With Non-Zero Bitwise XOR +#include "leetcode.h" + +/* + * 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. + */ + +int longestSubsequence(int *nums, int numsSize) { + int sum = 0; + bool pos = false; + for (int i = 0; i < numsSize; i++) { + pos |= (bool)nums[i]; + sum ^= nums[i]; + } + return pos ? numsSize - !sum : 0; +} + +int main() { + int n1[] = {1, 2, 3}, n2[] = {2, 3, 4}; + int r1 = longestSubsequence(n1, ARRAY_SIZE(n1)); + int r2 = longestSubsequence(n2, ARRAY_SIZE(n2)); + printf("%d\n", r1); + assert(r1 == 2); + printf("%d\n", r2); + assert(r2 == 3); +} diff --git a/longest_subseq_nz_xor.py b/longest_subseq_nz_xor.py @@ -0,0 +1,26 @@ +# 3702. Longest Subsequence With Non-Zero Bitwise XOR +from functools import reduce +from operator import xor +from typing import List + +""" +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. +""" + + +class Solution: + def longestSubsequence(self, nums: List[int]) -> int: + n = len(nums) + if max(nums) == 0: + return 0 + if reduce(xor, nums) == 0: + return n - 1 + return n + + +if __name__ == "__main__": + obj = Solution() + print(obj.longestSubsequence(nums=[1, 2, 3])) + print(obj.longestSubsequence(nums=[2, 3, 4]))