Longest Even Odd Subarray With Threshold - Problem

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 (first element must be even)
  • For all indices i in the range [l, r - 1], nums[i] % 2 != nums[i + 1] % 2 (alternating even/odd)
  • For all indices i in the range [l, r], nums[i] <= threshold (all elements within threshold)

Return an integer denoting the length of the longest such subarray.

Note: A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Alternating Pattern
$ Input: nums = [3,2,5,4], threshold = 5
Output: 3
💡 Note: Starting at index 1: [2,5,4] has length 3. Element 2 is even, alternates (2→5→4 = even→odd→even), and all ≤ 5.
Example 2 — Threshold Violation
$ Input: nums = [1,2], threshold = 2
Output: 1
💡 Note: Starting at index 1: [2] has length 1. Element 2 is even and ≤ 2. Cannot extend to element 1 since we need even start.
Example 3 — No Valid Subarray
$ Input: nums = [2,3,4,5], threshold = 4
Output: 3
💡 Note: Starting at index 0: [2,3,4] has length 3. Stops at element 5 because 5 > 4 (threshold violation).

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ threshold ≤ 106

Visualization

Tap to expand
Longest Even-Odd Subarray With ThresholdInput:nums = [3,2,5,4], threshold = 532540123oddevenoddevenValid Subarray: [2,5,4]✓ Starts with even (2)✓ Alternating pattern: 2→5→4 (even→odd→even)✓ All elements ≤ 5 (threshold)Output: 3 (length of longest valid subarray)
Understanding the Visualization
1
Input Analysis
Array with threshold constraint and pattern requirements
2
Pattern Matching
Find subarrays: even start + alternating + threshold
3
Maximum Length
Return length of longest valid subarray
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently track valid subarrays with three conditions: even start, alternating parity, and threshold constraint
Asked in
Amazon 15 Microsoft 12 Google 8
12.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen