Skip to main content
Back to problems
Leetcode
Medium
Arrays
Bit Manipulation
Greedy
Longest Subarray With Maximum Bitwise And

Find the longest contiguous segment whose bitwise AND is as large as possible.

Acceptance 100%
Problem Statement

Given an integer array, consider the bitwise AND of every contiguous subarray. Your task is to find the maximum possible bitwise AND value among all subarrays, then return the length of the longest contiguous subarray that achieves that maximum value.

A key observation is that the bitwise AND of any subarray cannot exceed the largest element in the array, and the best possible value is determined by the maximum element itself. The problem reduces to locating the longest consecutive run of that maximum value.

Input Format

  • An integer array nums of length n.
  • Each element is a non-negative integer.

Output Format

  • Return the length of the longest contiguous subarray whose bitwise AND is maximum among all contiguous subarrays.

Constraints

  • 1 <= n <= $10^{5}$
  • 0 <= nums[i] <= $10^{9}$
  • The answer always fits in a 32-bit signed integer.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3,3,2,2]

Output

2

Explanation

The maximum possible bitwise AND over any contiguous subarray is 3, achieved by subarrays containing only 3. The longest such contiguous subarray is [3, 3], so the answer is 2.

Example 2

Input

nums = [5,5,5]

Output

3

Explanation

The maximum bitwise AND is 5, and the entire array already has that value.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.