Rearrange an array so that even values appear at even indices and odd values appear at odd indices.
Given an integer array nums with an equal number of even and odd values, rearrange the array so that:
nums[i]is even wheniis evennums[i]is odd wheniis odd
Return any valid rearrangement. You may modify the array in place or return a new array, depending on your implementation choice.
The input is guaranteed to contain the same number of even and odd elements, so a valid arrangement always exists.
Input Format
- An integer array
nums numscontains an equal count of even and odd integers
Output Format
- Return an array rearranged so parity matches index parity at every position
Constraints
2 <= nums.length <= 2 * $10^{4}$nums.lengthis evennumscontains an equal number of even and odd integers- All values fit in standard 32-bit signed integers
Example 1
Input
nums = [4,2,5,7]
Output
[4,5,2,7]
Explanation
Index 0 and 2 contain even numbers, while index 1 and 3 contain odd numbers.
Example 2
Input
nums = [2,3]
Output
[2,3]
Explanation
The array already satisfies the required parity arrangement.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.