Sort Array By Parity

Move the even numbers of an array to the front and the odd numbers to the back, in place.

Rearrange an array of integers nums so that every even number comes before every odd number, and return it. The order inside the even group and inside the odd group does not matter, so several answers can be correct.

Example 1
Input: nums = [3, 1, 2, 4]
Output: [4, 2, 1, 3]
Explanation: [2, 4, 3, 1], [4, 2, 3, 1] and [2, 4, 1, 3] are also accepted.
Example 2
Input: nums = [0]
Output: [0]
Solution

The Idea

Whether a number is even or odd is called its parity, so "sort by parity" means putting the numbers into two groups: evens on the left, odds on the right. Nothing else about their order counts. That is why Example 1 accepts four different answers.

The easy way is to take a second, empty array, copy the even numbers into it first and then the odd ones. That works, but it needs a whole second array as big as the first. Can the numbers be moved into their groups inside nums itself?

Look at [3, 1, 2, 4] from both ends. The leftmost number, 3, is odd, so it sits on the wrong side. The rightmost number, 4, is even, so it is on the wrong side too. Swapping the two fixes both places at once.

Swapping a wrong-side pair from the two ends is the whole idea. Put one marker, lo, at the left end and another, hi, at the right end, and let them walk toward each other. Look at the picture below.

The array 3, 1, 2, 4 with lo on 3 and hi on 4. 3 is odd and 4 is even, so they swap. After the first swap lo is on 1 and hi on 2, which swap too. After the second swap the array is 4, 2, 1, 3, and lo and hi have crossed.

In the row labelled "start", lo is on 3 and hi is on 4. 3 is odd and 4 is even, so they swap. In the row "after the first swap", 4 is now settled on the left and 3 on the right, and the markers have each moved one step inward. lo finds 1, which is odd, and hi finds 2, which is even, so they swap again.

In the last row, lo has moved past hi. Everything left of lo is even, everything right of hi is odd, and nothing is left in between. The array reads [4, 2, 1, 3], the answer from Example 1.

Walking two markers from opposite ends toward each other like this is called the two-pointer technique. Here each marker guards a zone: lo grows the even zone from the left, and hi grows the odd zone from the right.

Solution Approach

Turning that idea into code means settling three things: what each marker does at each step, when to stop, and how to test whether a number is odd.

Moving the markers

What if the number at lo is already even? Then it is in the right place, and lo simply moves one step right. In the same way, an odd number at hi is in the right place, and hi moves one step left.

Only when both are wrong, an odd number at lo and an even number at hi, do the two numbers swap. After the swap both are in the right place, so both markers move inward. Every step moves at least one marker, so the two markers always get closer to meeting.

When to stop

When can the walk stop? The numbers left of lo are known to be even and the numbers right of hi are known to be odd. Once lo is no longer left of hi, at most one number is unchecked, and a single number is in a correct place whatever its parity. So the loop runs while lo < hi.

Testing for odd numbers

How do we tell even from odd? The remainder after dividing by 2, written n % 2 in Java, is 0 for an even number. For an odd number it is not always 1: Java keeps the sign of the number, so -3 % 2 is -1. The safe test for odd is therefore n % 2 != 0, which covers both 1 and -1.

Java Solution

The method sortArrayByParity works in these steps:

  1. First, put the marker lo on the first position, 0, and the marker hi on the last position, nums.length - 1.
  2. Walk the markers toward each other with a while loop that runs as long as lo < hi.
  3. Inside the loop, if nums[lo] is even, move lo right. Otherwise, if nums[hi] is odd, move hi left.
  4. If neither holds, nums[lo] is odd and nums[hi] is even. Swap them through a temporary variable, tmp, and move both markers inward.
  5. When the loop ends, return nums, the same array that came in, now rearranged.

The main method runs both examples, an array with negative odd numbers, one with only odd numbers, a longer mixed array, and an empty array.

Java
import java.util.Arrays;

public class SortArrayByParity {

    public static int[] sortArrayByParity(int[] nums) {
        int lo = 0;                           // everything left of lo is even
        int hi = nums.length - 1;             // everything right of hi is odd
        while (lo < hi) {
            if (nums[lo] % 2 == 0) {
                lo++;                         // even on the left: already in place
            } else if (nums[hi] % 2 != 0) {
                hi--;                         // odd on the right: already in place
            } else {
                int tmp = nums[lo];           // odd on the left, even on the right: swap
                nums[lo] = nums[hi];
                nums[hi] = tmp;
                lo++;
                hi--;
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {3, 1, 2, 4})));
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {0})));
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {-3, 2, -5})));
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {5, 7, 9})));
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {1, 3, 6, 8, 5, 2})));
        System.out.println(Arrays.toString(sortArrayByParity(new int[] {})));
    }
}

Running it prints:

Output
[4, 2, 1, 3]
[0]
[2, -3, -5]
[5, 7, 9]
[2, 8, 6, 3, 5, 1]
[]

[4, 2, 1, 3] on the first line is exactly the last row of the picture. [0] comes back unchanged: with one number, lo and hi start on the same position and the loop never runs. 0 is even, so it is in the right group anyway.

Look at the third line, [2, -3, -5]. Both -3 and -5 ended up on the right, because the odd test is % 2 != 0. With nums[hi] % 2 == 1 instead, -5 does not count as odd, since its remainder is -1. It is swapped to the front, and the method returns [-5, 2, -3], with an odd number first.

[5, 7, 9] has no even number to move, so hi walks left until it meets lo and nothing is swapped. In [2, 8, 6, 3, 5, 1], the evens 2, 8 and 6 come first, though not in their original order, which the problem allows. The empty array starts with hi at -1, so the loop is skipped and [] comes back.

Complexity

The work is a single walk of lo and hi toward each other.

  • Time: O(n) for an array of n numbers, because every pass of the loop moves lo right, hi left, or both, and the two markers meet after at most n - 1 passes.
  • Space: O(1), because the numbers are swapped inside nums with one temporary variable, and the result is the input array itself, not a copy.

With three groups instead of two, the same idea becomes the Dutch National Flag algorithm.