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]

Explanation:

Input: [0]

Output: [0]

Explanation:

Input: [1, 2, 3, 4]

Output: [2, 4, 3, 1]

Explanation:

๐Ÿง  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.

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources