Leetcode #2760: Longest Even Odd Subarray With Threshold
In this guide, we solve Leetcode #2760 Longest Even Odd Subarray With Threshold 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.

Problem Statement
You are given a 0-indexed integer array nums and an integer threshold. Find the length of the longest subarray of nums starting at index l and ending at index r (0 <= l <= r < nums.length) that satisfies the following conditions: nums[l] % 2 == 0 For all indices i in the range [l, r - 1], nums[i] % 2 != nums[i + 1] % 2 For all indices i in the range [l, r], nums[i] <= threshold Return an integer denoting the length of the longest such subarray.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: nums = [3,2,5,4], threshold = 5
Output: 3
Explanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions.
Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.
Python Solution
class Solution:
def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int:
ans, n = 0, len(nums)
for l in range(n):
if nums[l] % 2 == 0 and nums[l] <= threshold:
r = l + 1
while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold:
r += 1
ans = max(ans, r - l)
return ans
Complexity
The time complexity is , where is the length of the array . The space complexity is .
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.