Taro Logo

Longest Even Odd Subarray With Threshold

Easy
Asked by:
Infosys
0 views
Topics:
ArraysSliding Windows

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.

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

Example 1:

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.

Example 2:

Input: nums = [1,2], threshold = 2
Output: 1
Explanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 1 => [2]. 
It satisfies all the conditions and we can show that 1 is the maximum possible achievable length.

Example 3:

Input: nums = [2,3,4,5], threshold = 4
Output: 3
Explanation: In this example, we can select the subarray that starts at l = 0 and ends at r = 2 => [2,3,4]. 
It satisfies all the conditions.
Hence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= threshold <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected return value if no valid subarray can be found?
  2. Can the array contain negative integers or zeros, and how should zero be treated regarding parity?
  3. What are the constraints on the size of the input array `nums` and the value of `threshold`?
  4. If multiple valid subarrays of the maximum length exist, does it matter which one is used for the length calculation?
  5. Are all elements in the input array guaranteed to be standard integers?

Brute Force Solution

Approach

Imagine you have a long row of numbers and you need to find the longest group sitting next to each other where every number is below a certain limit, and the types of numbers alternate between one kind and another. The brute force approach simply tests every single possible group of numbers in the entire row to see if it follows all the rules.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first number in the row to see if it is smaller than the limit.
  2. If it is, consider it a valid group of size one, and remember that length.
  3. Next, check the first two numbers together to see if they follow the alternating pattern and both stay below the limit.
  4. If they do, remember this new length because it is longer.
  5. Keep extending your view to the right, adding one more number at a time, as long as the alternating pattern and the limit rule are both respected.
  6. Whenever a number breaks the rules, stop looking at that particular group and start over by picking a fresh starting point further down the line.
  7. Repeat this exhaustive checking process for every possible starting position in the entire row.
  8. After you have tested every single conceivable group, look back at all the valid lengths you found and pick the absolute largest one.

Code Implementation

def longest_even_odd_subarray(nums, threshold):
    max_length = 0

    # We test every possible starting position to ensure we do not miss any valid subarray
    for start_index in range(len(nums)):
        if nums[start_index] <= threshold and nums[start_index] % 2 == 0:
            current_length = 1
            max_length = max(max_length, current_length)

            for current_index in range(start_index + 1, len(nums)):
                # Check bounds and limit rule before verifying the alternating parity requirement
                if nums[current_index] <= threshold and (nums[current_index] % 2 != nums[current_index - 1] % 2):
                    current_length += 1
                    max_length = max(max_length, current_length)
                else:
                    break

    # Return the largest valid group length discovered across all checked starting points
    return max_length

Big(O) Analysis

Time Complexity
O(n²) – For each of the n possible starting positions in the array, the brute force approach scans ahead to test every subsequent number as part of the current group. In the worst-case scenario where all numbers satisfy the alternating pattern and threshold limit, the first starting position requires n checks, the second starting position requires n-1 checks, and so on. This nested checking process for every conceivable group results in approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The algorithm only maintains a few primitive integer variables to track the current starting position, the current length, and the maximum length found so far, without allocating any auxiliary data structures like temporary lists or hash maps. As the input size N grows, these few pointer and counter variables require a constant amount of extra memory regardless of the row length. Therefore, the auxiliary space complexity is strictly constant because no additional storage scales with the input size N.

Optimal Solution

Approach

Instead of checking every single possible grouping of numbers, the optimal strategy walks through the sequence and builds valid alternating patterns on the fly. Whenever a rule is broken, it instantly abandons the current attempt, remembers the longest successful stretch seen so far, and starts looking for a new pattern.

Here's how the algorithm would work step-by-step:

  1. Scan through the line of numbers one by one from left to right.
  2. Check if the current number is even and small enough to pass the size limit; if it does not meet these starting conditions, skip it and keep moving.
  3. If a valid starting number is found, begin a growing chain and look at the very next number.
  4. Verify that the next number breaks the alternating rule by being the opposite type (even instead of odd, or odd instead of even) and also stays within the size limit.
  5. Keep extending the chain as long as the numbers successfully alternate between even and odd, and every single number stays within the size limit.
  6. The moment a number breaks the alternating rule, exceeds the size limit, or the sequence ends, pause and measure the length of the chain just built.
  7. Compare this recent chain length against your all-time record, updating the record if the new chain is longer.
  8. Immediately start a fresh search for the next valid starting number right where the previous chain broke, and repeat the process until the end of the line is reached.

Code Implementation

class Solution:
    def longest_even_odd_subarray(self, nums: list[int], threshold: int) -> int:
        max_length_record = 0
        array_index = 0

        while array_index < len(nums):
            # A valid start requires an even number that does not exceed the threshold limit.
            if nums[array_index] % 2 == 0 and nums[array_index] <= threshold:
                current_chain_length = 1
                next_index = array_index + 1

                while next_index < len(nums):
                    # Elements must alternate parity and stay within threshold to grow the chain.
                    if nums[next_index] <= threshold and nums[next_index] % 2 != nums[next_index - 1] % 2:
                        current_chain_length += 1
                        next_index += 1
                    else:
                        break

                # Keep track of the longest valid alternating sequence found across attempts.
                if current_chain_length > max_length_record:
                    max_length_record = current_chain_length

                array_index = next_index
            else:
                array_index += 1

        return max_length_record

Big(O) Analysis

Time Complexity
O(n) – We perform a single left-to-right scan through the array of n numbers to find and extend valid alternating chains. Each element in the array is examined at most a constant number of times because the inner checks immediately resume scanning from where the previous chain broke without redundant backtracking. This linear traversal results in approximately n operations in the worst-case scenario. Therefore, the total operations scale directly with the input size, simplifying to O(n).
Space Complexity
O(1) – The algorithm only maintains a few primitive scalar variables, such as pointers for the current scan index, the length of the ongoing alternating chain, and a running maximum record. These variables track the state on the fly without allocating any auxiliary data structures like temporary lists or hash maps. Because no additional memory scales with the input size N, the extra space required remains constant.

Edge Cases

Empty or null input array
How to Handle:
Return zero immediately since no valid subarray can exist.
Single element array
How to Handle:
Check if the single element is even and less than or equal to the threshold, returning 1 if true and 0 if false.
Starting element is odd
How to Handle:
The algorithm must ignore odd starting elements because valid subarrays are explicitly required to start with an even number.
All elements exceed the threshold
How to Handle:
The validation check will fail for every element, resulting in a returned length of zero.
No alternating parity exists in the array
How to Handle:
The tracking loop resets whenever parity fails, ultimately returning a maximum length of zero if no valid subarray is found.
Negative numbers and zero included in the array
How to Handle:
Since zero is considered even, the algorithm correctly evaluates its parity and threshold condition just like positive numbers.
Maximum possible constraint limits with large inputs
How to Handle:
A single-pass linear scan approach ensures optimal efficiency and avoids performance bottlenecks.
Elements equal to the threshold boundary
How to Handle:
The less-than-or-equal-to condition correctly includes values that precisely match the threshold limit.