548. Sort Array By Parity
You are given an integer array nums. Rearrange it so that every even number comes before every odd number, and return the rearranged array.
So that the answer is unique, keep each group in its original order: the evens must appear in the same relative order they had in nums, followed by the odds in the same relative order they had in nums.
Remember that 0 counts as even. Can you do it in one pass?
Example 1:
Input: nums = [3, 1, 2, 4]
Output: [2, 4, 3, 1]
Explanation: The evens are 2 and 4 (in that order in nums); the odds are 3 and 1. Evens first gives [2, 4, 3, 1].
Example 2:
Input: nums = [0]
Output: [0]
Explanation: 0 is even, and a single-element array is already arranged.
Constraints:
- 1 ≤ nums.length ≤ 5000
- 0 ≤ nums[i] ≤ 5000
Hints:
You never need to compare two numbers with each other — each element only has to answer one yes/no question: is it even?
Sweep the array once with two collectors: append evens to one list and odds to another, then glue them together. Appending in scan order automatically preserves each group's relative order.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [3, 1, 2, 4]
Expected output: [2, 4, 3, 1]