#3825
Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND
MediumArrayBinary SearchBit ManipulationEnumerationBinary SearchDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Utilize bit manipulation to filter elements based on their bits, then apply a modified LIS algorithm to find the longest increasing subsequence for each bit position.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through each bit position from 0 to 30.
- 2Step 2: Filter nums to keep only elements with the current bit set, maintaining their order.
- 3Step 3: Apply a dynamic programming approach to find the longest increasing subsequence for the filtered array.
solution.py13 lines
1def longestIncreasingSubseq(nums):
2 max_length = 0
3 for b in range(31):
4 filtered = [x for x in nums if x & (1 << b)]
5 lis = []
6 for num in filtered:
7 pos = bisect.bisect_left(lis, num)
8 if pos == len(lis):
9 lis.append(num)
10 else:
11 lis[pos] = num
12 max_length = max(max_length, len(lis))
13 return max_lengthℹ
Complexity note: The complexity is driven by filtering and applying binary search for LIS, making it efficient for large inputs.
- 1Bitwise operations can significantly reduce the problem size.
- 2Dynamic programming is effective for finding increasing subsequences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.