Sort Array by Parity

Easy~10 min

Given an integer array nums, rearrange it so that all even numbers come before all odd numbers.

Within the even numbers, preserve their original relative order from the input. Within the odd numbers, preserve their original relative order from the input.

Return the rearranged array.

Examples

Example 1
Input: nums = [3, 1, 2, 4]
Output: [2, 4, 3, 1]
Explanation: Even numbers [2, 4] come first (in their original order), then odd numbers [3, 1] (in their original order).
Example 2
Input: nums = [0, 1, 2]
Output: [0, 2, 1]
Explanation: Even numbers [0, 2] first, then odd numbers [1].
Example 3
Input: nums = [4, 2, 6]
Output: [4, 2, 6]
Explanation: All numbers are even, so the array is unchanged.

Constraints

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run