Skip to main content
Back to problems
Leetcode
Medium
Arrays
Bit Manipulation
Sliding Window
Google
Longest Nice Subarray

Find the longest contiguous subarray where no two numbers share a set bit.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums, find the length of the longest contiguous subarray such that for every pair of distinct elements in that subarray, their bitwise AND is 0.

In other words, within the chosen subarray, no two numbers are allowed to have a 1 in the same bit position.

Return the maximum possible length of such a subarray.

Intuition

You are looking for the longest window that remains "compatible" under bitwise constraints: as soon as two numbers overlap in any set bit, the current window is no longer valid.

Input Format

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

Output Format

  • Return a single integer: the maximum length of a contiguous subarray satisfying the condition.

Constraints

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

Example 1

Input

nums = [1, 3, 8, 48, 10]

Output

3

Explanation

The subarray [3, 8, 48] is nice because the numbers do not share any set bits pairwise. Its length is 3, which is maximal.

Example 2

Input

nums = [3, 1, 5, 11, 13]

Output

1

Explanation

Every pair of distinct elements shares at least one set bit, so any valid subarray can contain only one number.

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.