Sort Array by Parity(#905)
Category: Array, Sorting, Two Pointer
๐งฉ Problem Statement
You're given an array of integers nums, and your task is to move all even numbers to the front of the array, followed by all the odd numbers. You can return any valid arrangement that satisfies this condition.
๐ Examples
Input: [3, 1, 2, 4]
Output: [4, 2, 1, 3] or [2, 4, 1, 3]
Input: [0]
Output: [0]
Input: [1, 2, 3, 4]
Output: [2, 4, 3, 1]
๐ง Approach
### Two-Pointer Approach
โข Initialize two pointers:
โข `left` at the start (0)
โข `right` at the end (`nums.length - 1`)
โข While `left < right`:
โข If `nums[left]` is odd and `nums[right]` is even โ swap them.
โข If `nums[left]` is even โ move `left` forward.
โข If `nums[right]` is odd โ move `right` backward.
This approach modifies the array in-place and ensures all even numbers come before odd numbers. No need to preserve relative order.
๐ป Code
var sortArrayByParity = function (nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 > nums[right] % 2) {
[nums[left], nums[right]] = [nums[right], nums[left]];
}
if (nums[left] % 2 === 0) left++;
if (nums[right] % 2 === 1) right--;
}
return nums;
};
๐ Complexity
Time: O(n) โ Each element is checked at most once.
Space: O(1) โ In-place swapping, no extra space used.