1547. Long AND Stretch
A factory logs one status code per machine along a conveyor line. A stretch is a run of consecutive machines, and its strength is the bitwise AND of all the codes inside it. Given the integer array nums and a threshold k, return the length of the longest stretch whose strength is at least k. If no stretch qualifies, return 0.
Hint of structure: dropping a machine from a stretch can never lower its AND, so if a stretch qualifies then every shorter stretch inside it does too. That makes a window that grows on the right and shrinks on the left work, provided you keep a counter per bit to know the current AND.
Required complexity: O(n log M) time where M is the largest value (30 bits), and O(1) extra space. The answer is a single integer.
Example 1
- Input:
- nums = [7,6,14,12,3], k = 4
- Output:
- 4
- Explanation:
The stretch 7,6,14,12 has AND 4, which is at least 4; adding 3 drops the AND to 0, so the answer is 4.
Example 2
- Input:
- nums = [1,2,1], k = 3
- Output:
- 0
- Explanation:
Every single code is below 3 and every longer stretch ANDs to 0, so no stretch qualifies and the answer is 0.
Constraints
1 ≤ n ≤ 105
0 ≤ nums[i], k ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log M)
- Space
- O(1)