All problems

Sort Array by Parity

Easy · two pointers

A cinema sells tickets with numbers, and the staff want to call out the even ticket numbers first and the odd ones afterwards.

Given a list of integers nums, return a new list that contains every even number first, then every odd number. Inside each group, the numbers must keep the same relative order they had in nums.

Zero counts as even. Equal values are all kept.

Examples

Example 1

Input: nums = [3, 1, 2, 4]

Output: [2, 4, 3, 1]

The evens 2 and 4 come first in their original order, then the odds 3 and 1 in their original order.

Example 2

Input: nums = [5, 8, 7, 6, 9, 2]

Output: [8, 6, 2, 5, 7, 9]

Example 3

Input: nums = [0]

Output: [0]

Constraints