Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND Problem
Description
LeetCode Problem 3825.
You are given an integer array nums.
Return the length of the longest strictly increasing subsequence in nums whose bitwise AND is non-zero. If no such subsequence exists, return 0.
Example 1:
Input: nums = [5,4,7]
Output: 2
Explanation:
One longest strictly increasing subsequence is [5, 7]. The bitwise AND is 5 AND 7 = 5, which is non-zero.
Example 2:
Input: nums = [2,3,6]
Output: 3
Explanation:
The longest strictly increasing subsequence is [2, 3, 6]. The bitwise AND is 2 AND 3 AND 6 = 2, which is non-zero.
Example 3:
Input: nums = [0,1]
Output: 1
Explanation:
One longest strictly increasing subsequence is [1]. The bitwise AND is 1, which is non-zero.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Enumeration + Longest Increasing Subsequence
The AND of a subsequence is non-zero exactly when all of its numbers share at least one set bit. So try every bit position b: keep only the numbers that have bit b set, compute the length of their longest strictly increasing subsequence with the usual patience-sorting method (binary search on the tails array), and take the best length over all bits. If no number has any bit set, the answer is 0.
Complexity: O(n log n log M) time and O(n) space, where n is the length of nums and M is its maximum value (log M is the number of bits).
from bisect import bisect_left
class Solution:
def longestSubsequence(self, nums: List[int]) -> int:
def lis(arr: List[int]) -> int:
g = []
for x in arr:
j = bisect_left(g, x)
if j == len(g):
g.append(x)
else:
g[j] = x
return len(g)
ans = 0
m = max(nums).bit_length()
for i in range(m):
arr = [x for x in nums if x >> i & 1]
ans = max(ans, lis(arr))
return ans