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

Approaches

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

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…