All problems
1076EasyArrayTwo PointersSorting

Evens to the Front

Tracked in this browser only
Write code

Trains the technique from

LeetCode 905Sort Array By Parity

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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