The problem. Given an integer array nums, move all the even numbers to the front and all the odd numbers to the back. Any order within each group is fine. Return the array.
nums = [3, 1, 2, 4] -> [4, 2, 1, 3] (also accepted: [2, 4, 3, 1], [4, 2, 3, 1], ...)
nums = [0] -> [0]This isn't a full sort — values only need to land in the right group. That's exactly the partition step of quick sort, with "is it even?" in place of "is it below the pivot?". Keep two pointers: i moves right from the front past values that are already even, j moves left from the back past values that are already odd. When both stop, nums[i] is odd and nums[j] is even — each belongs on the other side — so swap them. When the pointers meet, every value is in its half.
function sortArrayByParity(nums) { const out = []; for (const x of nums) if (x % 2 === 0) out.push(x); // evens first for (const x of nums) if (x % 2 === 1) out.push(x); // then odds return out;}Time O(n), space O(n). Simple, and it keeps the original order within each group (it's stable).
i skips evens at the front, j skips odds at the back; when both are stuck, swap.
function sortArrayByParity(nums) { let i = 0, j = nums.length - 1; while (i < j) { if (nums[i] % 2 === 0) i++; // already an even at the front else if (nums[j] % 2 === 1) j--; // already an odd at the back else { [nums[i], nums[j]] = [nums[j], nums[i]]; // odd at the front, even at the back: swap i++; j--; } } return nums;}Time O(n), space O(1). Each step moves at least one pointer, so there are at most n steps. Unlike approach 1 it doesn't keep the original order inside the groups — the question doesn't ask it to.
-3 % 2 is -1: test oddness with x % 2 != 0.