Sort Array By Parity

Given an array of integers, rearrange it so all even numbers come before all odd numbers. Any order within each group is acceptable.

EasyOptionalTwo PointersPartitioning
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array of integers, rearrange it so all even numbers come before all odd numbers. Any order within each group is acceptable.

Why solve this?

A direct variation on the Segregate 0s and 1s partition, swapping the two-value condition for a parity check — good practice recognizing the same shape under a different rule.

Pattern Recognition

Whenever elements need to be grouped in place by a two-way yes/no condition (even vs. odd, matches vs. doesn't), and the order within each group doesn't matter, boundary pointers closing in from both ends solve it in one pass.

Prerequisites

  • Comfort with in-place two-way partitioning (see Segregate 0s and 1s).

Hints

  1. This is the same shape as segregating 0s and 1s — just swap the condition from 'is it 0' to 'is it even'.
  2. Advance the left pointer past values that are already even; advance the right pointer past values that are already odd.
  3. Stability (preserving each group's original relative order) is not required here, which is exactly what makes the two-pointer swap approach valid.

Approach

Keep a left pointer starting at index 0 and a right pointer starting at the last index. Advance left forward past any value that's already even, and advance right backward past any value that's already odd. When left lands on an odd value and right lands on an even value, both are misplaced relative to each other, so swap them. Repeat until the pointers cross. Because stability isn't required, this in-place swap is sufficient — there's no need to preserve each group's original relative order, which is what would force a slower stable partition instead.

Code

Solution.java
class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            if (nums[left] % 2 == 0) {
                left++;
            } else if (nums[right] % 2 == 1) {
                right--;
            } else {
                int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp;
            }
        }
        return nums;
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays