Given an array of integers nums
, half of the integers in nums
are odd, and the other half are even. The requirement is to sort the array so that whenever nums[i]
is odd, i
is odd, and whenever nums[i]
is even, i
is even.
Example:
Input: nums = [4, 2, 5, 7]
Output: [4, 5, 2, 7]
Explanation: [4, 7, 2, 5], [2, 5, 4, 7], and [2, 7, 4, 5] would also be correct.
We can use a two-pointer approach:
even_idx
) will focus on even indices and will seek the next odd number located at an even index.odd_idx
) will focus on odd indices and will seek the next even number located at an odd index.We will then swap these misplaced numbers to ensure they are in the correct positions.
def sortArrayByParityII(nums):
n = len(nums)
even_idx, odd_idx = 0, 1
while even_idx < n and odd_idx < n:
if nums[even_idx] % 2 == 0:
even_idx += 2
elif nums[odd_idx] % 2 == 1:
odd_idx += 2
else:
# Swap the misplaced values
nums[even_idx], nums[odd_idx] = nums[odd_idx], nums[even_idx]
even_idx += 2
odd_idx += 2
return nums
# Example usage
print(sortArrayByParityII([4, 2, 5, 7])) # Output could be [4, 5, 2, 7] or any other valid configuration
O(n)
, where n
is the number of elements in the array. Each element is processed at most twice.O(1)
, as we are performing the sorting in-place using only a constant amount of extra space.This solution effectively rearranges the array by ensuring that all even indices contain even numbers and all odd indices contain odd numbers through a series of swaps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?