Show problems as
Classic problem #905EasyArrayTwo PointersSorting

Sort Array By Parity

Real-world version: Evens to the Front
Tracked in this browser only
Read Sort Array By Parity on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A list of whole numbers reads values.

Return the list rearranged so that every even value comes before every odd one, with the even values keeping the order they had among themselves and the odd values likewise keeping theirs.

Examples

Example 1

Input
values = [1, 2, 3, 4]
Output
[2, 4, 1, 3]

The evens are 2 and 4 in that order, and the odds are 1 and 3 in that order, so the evens go first with each group's order untouched.

Example 2

Input
values = [7, 7, 2]
Output
[2, 7, 7]

The only even value moves to the front and the two odd sevens follow in the order they were in.

Example 3

Input
values = [5]
Output
[5]

A single odd value has nothing to move ahead of it.

Constraints

  • 1 <= values.length <= 5000
  • 0 <= values[i] <= 5000

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def sort_array_by_parity(values: list[int]) -> list[int]:
Java
public int[] sortArrayByParity(int[] values)