Ctrl K

Longest Stretch with the Top AND

Medium
You are given an array of positive integers values. For any non-empty segment (a run of consecutive elements) you can take the bitwise AND of all its numbers. Let k be the largest bitwise AND that any segment of the array reaches. Among the segments whose AND is exactly k, find the longest one and return its length.
Example 1
values=[5, 7, 7, 3, 7] → 2

The largest AND any segment can reach is 7, since an AND never exceeds any of its numbers. The segment [7, 7] gives 7 and has length 2; the lone 7 at the end is shorter.

Example 2
values=[6, 4, 2] → 1

The best value is 6, and only the one-element segment reaches it: 6 AND 4 = 4.

Example 3
values=[9, 9, 9] → 3

The whole array is nines, its AND is 9, which is the maximum.

Constraints
  • 1 ≤ values.length ≤ 10⁵
  • 1 ≤ values[i] ≤ 2³¹ − 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTake From Any Pile MediumXOR of Every Cross Pair MediumOR of All Subset Sums MediumSmallest Unreachable OR MediumXOR Tile Duel Hard
loading Python…
Input
values=[5, 7, 7, 3, 7]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 45 tests on the server, hidden ones included.