Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2419: Longest Subarray With Maximum Bitwise AND

In this guide, we solve Leetcode #2419 Longest Subarray With Maximum Bitwise AND in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an integer array nums of size n. Consider a non-empty subarray from nums that has the maximum possible bitwise AND.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Bit Manipulation, Brainteaser, Array

Intuition

The problem structure lets us track state with bitwise operations.

Bit operations are constant time and avoid extra memory.

Approach

Apply XOR/AND/OR and shifts to maintain the required invariant.

Aggregate the result in a single pass.

Steps:

  • Identify a bitwise invariant.
  • Combine values with bit operations.
  • Return the aggregated result.

Example

Input: nums = [1,2,3,3,2,2] Output: 2 Explanation: The maximum possible bitwise AND of a subarray is 3. The longest subarray with that value is [3,3], so we return 2.

Python Solution

class Solution: def longestSubarray(self, nums: List[int]) -> int: mx = max(nums) ans = cnt = 0 for x in nums: if x == mx: cnt += 1 ans = max(ans, cnt) else: cnt = 0 return ans

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the array nums\textit{nums}nums. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy