Sort Array By Parity II
Easy · Arrays & Hashing · Array · Two Pointers · Sorting
Problem
You are given an integer array nums of even length in which exactly half of the values are even and half are odd.
Rearrange it so that every even index holds an even value and every odd index holds an odd value, and return the result. Any arrangement that satisfies this is accepted.
Examples
Input: nums = [3,8,5,2] Output: [8,3,2,5]
Indices 0 and 2 now hold evens and indices 1 and 3 hold odds. [2,5,8,3] would also be accepted.
Input: nums = [1,0] Output: [0,1]
The even value moves to index 0.
Input: nums = [4,7,6,9,1,10] Output: [4,7,6,9,10,1]
Only the last two values need to swap.
Constraints
- 2 <= len(nums) <= 2 · 10^4
- len(nums) is even
- Half of the values in nums are even
- 0 <= nums[i] <= 1000
Approaches
- Fix each index with a forward search — time O(n²), space O(1)
Follow-up
Any valid arrangement is accepted, which is what lets the swaps reorder values freely. The first use case asks for the one arrangement that keeps the evens and the odds in their original order, and the second counts the fewest swaps instead of making them.
Related problems
Start free on Cariara · Coding problems · System design studio