185. Evens to the Front

A mail clerk has a tray of parcels, and the array nums holds the house number written on each parcel. The delivery van visits all even-numbered houses first and the odd-numbered houses afterwards, so the parcels must be reordered before loading.

Return an array that contains exactly the same values as nums (the same numbers, with the same counts) arranged so that every even value comes before every odd value. The order inside the even group and inside the odd group does not matter, and any valid arrangement is accepted. Zero counts as even, and negative numbers follow the same rule: -4 is even and -3 is odd.

Example 1

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

The even values are 2 and 4 and the odd ones are 3 and 1. One valid answer is [2,4,3,1]; [4,2,1,3] would also be accepted.

Example 2

Input:
nums = [-3,0,-8,7]
Output:
[-8,0,-3,7]
Explanation:

The evens are 0 and -8, the odds are -3 and 7, so [0,-8,-3,7] works. Any arrangement with 0 and -8 first is accepted.

Constraints

1 ≤ nums.length ≤ 104

-105 ≤ nums[i] ≤ 105

How this problem is judged

Answers
Any valid answer is accepted. A checker tests yours against the problem's rules.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…