algoadvance

Longest Alternating Subarray: Given an array nums consisting of positive integers, return the length of the longest subarray of nums where adjacent elements are alternately even and odd. A subarray is a contiguous part of an array.

Clarifying Questions

  1. Input Constraints:
    • What is the range of the length of the input array nums?
    • Are there any constraints on the values within nums?
  2. Edge Cases:
    • What should we return if the input array nums is empty?
    • How do we handle an array of length 1?

Strategy

To solve this problem, we can use a single pass through the array while maintaining the length of the current alternating subarray. We will keep track of the maximum length encountered during this pass. Here are the detailed steps:

  1. Initialization:
    • Initialize max_length to 0.
    • Initialize current_length to 1 (since any single element subarray is at least length 1).
  2. Iterate through the array:
    • For each element in the array starting from the second element, check if it alternates with the previous element.
    • If it does, increment current_length.
    • If it does not, compare and possibly update max_length.
    • Reset current_length to 1 since the new potential subarray starts.
  3. Final Check:
    • After the loop, ensure to compare max_length with current_length one last time in case the longest alternating subarray ends at the last element.

This method ensures we only pass through the array once, making it efficient.

Code

def longest_alternating_subarray(nums):
    if not nums:
        return 0
    
    max_length = 1
    current_length = 1
    
    for i in range(1, nums.length):
        if (nums[i] % 2 == 0 and nums[i-1] % 2 != 0) or (nums[i] % 2 != 0 and nums[i-1] % 2 == 0):
            current_length += 1
            max_length = max(max_length, current_length)
        else:
            current_length = 1
    
    return max_length

Time Complexity

This solution ensures that we efficiently find the longest alternating subarray with minimal overhead.

Try our interview co-pilot at AlgoAdvance.com