Code Logo

Sort Array By Parity

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array nums, return an array consisting of all the even elements followed by all the odd elements. The order within each group does not matter. You should do this in-place if possible.

The two-pointer approach is efficient: use a left pointer starting at 0 and a right pointer starting at the end. If the left element is odd and the right element is even, swap them. Then move left forward when it points to an even, and right backward when it points to an odd.

This runs in O(n) time with O(1) space (in-place). A simpler approach using sort with a custom comparator also works: compare elements by parity (even before odd).

Edge cases include an empty array, all evens (return unchanged), all odds (return unchanged), and a single element.

The two-pointer approach for parity sorting is efficient because it uses the fact that even/odd is a binary property. The algorithm is a variant of the partition step in quicksort and demonstrates how sorting constraints can be satisfied in linear time without a full sort.

The two-pointer approach for parity sorting is efficient, using O(n) time and O(1) space by swapping elements in place without a full sorting pass.

Example Input & Output

Example 1
Input
[2,4,6]
Output
[2,4,6]
Explanation

All even.

Example 2
Input
[3,1,2,4]
Output
[2,4,3,1] or [4,2,1,3]
Explanation

Evens 2,4 before odds 3,1.

Example 3
Input
[1]
Output
[1]
Explanation

Single odd.

Example 4
Input
[]
Output
[]
Explanation

Empty.

Example 5
Input
[0]
Output
[0]
Explanation

Single even.

Algorithm Flow

Recommendation Algorithm Flow for Sort Array By Parity

Solution Approach

Sort the array by parity: all even integers come first followed by all odd integers. Return the resulting array.

function sortByParity(nums) {
  var r = [];
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] % 2 === 0) r.push(nums[i]);
  }
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] % 2 !== 0) r.push(nums[i]);
  }
  return r;
}

Use two passes: first collect all even numbers, then collect all odd numbers. This preserves the relative order within each group (stable partitioning). An alternative one-pass approach uses two pointers to swap out-of-place elements.

Time complexity is O(n), space complexity is O(n) for the result array.

Best Answers

java
class Solution {
    public int[] solution(int[] nums) {
        int lo=0,hi=nums.length-1;
        while (lo<hi) {
            if (nums[lo]%2==1&&nums[hi]%2==0) {
                int t=nums[lo];nums[lo]=nums[hi];nums[hi]=t;
                lo++;hi--;
            } else {
                if (nums[lo]%2==0) lo++;
                if (nums[hi]%2==1) hi--;
            }
        }
        return nums;
    }
}