We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sort Array By Parity II

Number: 958

Difficulty: Easy

Paid? No

Companies: Amazon


Problem Description

Given an array of integers nums where half the numbers are even and the other half are odd, rearrange the array so that whenever nums[i] is even, the index i is even, and whenever nums[i] is odd, the index i is odd. Return any valid rearranged array.


Key Insights

  • The array has an equal number of even and odd numbers.
  • Even-indexed positions must hold even numbers, and odd-indexed positions must hold odd numbers.
  • A two-pointer method can be employed to swap misplaced elements.
  • By iterating only over even and odd indices separately, we achieve an efficient in-place solution.

Space and Time Complexity

Time Complexity: O(n) – We scan through the array with two pointers. Space Complexity: O(1) – The sorting is performed in-place without using extra space.


Solution

We use two pointers:

  1. An evenIndex starting at 0 to track positions where an even number is expected.
  2. An oddIndex starting at 1 to track positions where an odd number is expected. Iterate through the array:
  • If the element at evenIndex is even, it’s in the correct position, so move to the next even index (evenIndex += 2).
  • Similarly, if the element at oddIndex is odd, move to the next odd index (oddIndex += 2).
  • If either position has an element of the wrong parity, swap the elements at evenIndex and oddIndex, and then move both pointers. This method ensures all elements are placed in the correct parity positions with a single pass through the array.

Code Solutions

# Python solution for Sort Array By Parity II

def sortArrayByParityII(nums):
    even_index = 0  # pointer for even indices
    odd_index = 1   # pointer for odd indices
    n = len(nums)
    
    # Process until either pointer exceeds the array length
    while even_index < n and odd_index < n:
        # If element at even_index is even, it's correctly placed
        if nums[even_index] % 2 == 0:
            even_index += 2
        # If element at odd_index is odd, it's correctly placed
        elif nums[odd_index] % 2 == 1:
            odd_index += 2
        else:
            # Swap misplaced elements
            nums[even_index], nums[odd_index] = nums[odd_index], nums[even_index]
            even_index += 2
            odd_index += 2
            
    return nums

# Example usage:
print(sortArrayByParityII([4,2,5,7]))
← Back to All Questions