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 Threshold INPUT nums array: 3 i=0 ODD 2 i=1 EVEN 5 i=2 ODD 4 i=3 EVEN threshold = 5 Constraints: 1. Start with EVEN number 2. Alternate even/odd 3. All nums <= threshold Find: Max subarray length ALGORITHM STEPS 1 Scan Array Find even nums as start 2 Check Threshold All elements <= 5 3 Extend Subarray While alternating parity 4 Track Maximum Update max length Processing: i=0: 3 is ODD - skip i=1: 2 EVEN, start here 2->5->4 (E-O-E) OK length = 3 max_length = 3 FINAL RESULT Longest valid subarray found: 2 EVEN 5 ODD 4 EVEN indices [1, 2, 3] OUTPUT 3 Verification: [OK] Starts with even (2) [OK] Alternates: E-O-E [OK] All <= 5 (2,5,4) Key Insight: Use a single pass O(n) approach: for each even number within threshold, greedily extend the subarray while alternating parity holds and all elements stay within threshold. Track the maximum length found. TutorialsPoint - Longest Even Odd Subarray With Threshold | Optimal Solution O(n)
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