Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND — binary search
Halve the sorted range until the target is found or the range collapses. Built for LeetCode 3825. Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND.
Because the slice is sorted, comparing nums[mid] to target tells you which half can be thrown away. That is the whole algorithm.
Algorithm
- While
lo <= hi, pickmid. - Equal → return
mid. Too small → search right. Too big → search left. - Empty range → not found (
-1).
- Time
- O(log n)
- Space
- O(1)
class Solution: def longestStrictlyIncreasingSubsequenceWithNonZeroBitwiseAnd(self, nums: list[int], target: int) -> int: lo, hi = 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1