Sort Array by Parity

(#905), Easy

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 = 0` and `right = nums.length - 1`.
  • While `left < right`:
  • - If `nums[left]` is odd and `nums[right]` is even, swap them.
  • - If `nums[left]` is even, increment `left`.
  • - If `nums[right]` is odd, decrement `right`.
  • This ensures all even numbers move to the beginning of the array.
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.

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources