Place Even Values at Even Indices and Odd Values at Odd Indices
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
### Problem
Exactly half the values in `nums` are even and half are odd. Rearrange the array so every index has a value of matching parity: even indices contain even values and odd indices contain odd values. Return any valid arrangement, preserving all occurrences.
```cpp
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums);
};
```
### Examples
**Example 1:**
```text
Input: nums = [3,2,1,4]
Output: [2,3,4,1]
Explanation: Indices0 and2 contain even values; indices1 and3 contain odd values.
```
**Example 2:**
```text
Input: nums = [1,0]
Output: [0,1]
Explanation: Swapping the two values gives the required index parities.
```
### Constraints
- `2 <= nums.length <= 2*10^4`, and length is even.
- Exactly half the values are even.
- `0 <= nums[i] <= 1000`.
### Contract considerations
The input length is even and parity counts are balanced, so a valid rearrangement always exists.
```hint Read the boundary condition
Pair an odd value at an even index with an even value at an odd index.
```
### What a Strong Answer Covers
The input length is even and parity counts are balanced, so a valid rearrangement always exists.
### Optional extensions
Original follow-up: perform the rearrangement in place. The reference uses only two indices and swaps.
### Follow-up Questions
Optional practice extension, separate from the original task: How would you handle an input with unequal counts of odd and even values?
Overview: Place Even Values at Even Indices and Odd Values at Odd Indices. Exactly half the values in nums are even and half are odd.
Place Even Values at Even Indices and Odd Values at Odd Indices
Amazon
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0
Problem
Exactly half the values in nums are even and half are odd. Rearrange the array so every index has a value of matching parity: even indices contain even values and odd indices contain odd values. Return any valid arrangement, preserving all occurrences.
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums);
};