Sort Array By Parity (LeetCode 905): Solution and Explanation

Easy
Array
Two Pointers
Sorting

Rearrange nums so all even values come before all odd values. Any such arrangement is accepted; this walkthrough builds the stable one, with evens in their original order and odds in their original order.

Intuition

The output has two blocks: evens on the left and odds on the right. If you knew where the boundary between the blocks sits, you could drop each value straight into its block.

The boundary is just the number of even values. One quick pass counts them, and from then on the even block is slots 0 to evens - 1 and the odd block starts at slot evens.

Keep one write pointer per block. Walk nums from left to right and write each value at its block's pointer, then move that pointer one step right. Because both blocks are filled in the order values are read, each block keeps the input order, which is exactly the stable answer.

Approach: Count, then fill with two write pointers

  1. Count how many values in nums are even and call it evens.
  2. Create an output array of the same length. Set even = 0 and odd = evens.
  3. For each value x in nums: if x is even, write it at result[even] and increase even; otherwise write it at result[odd] and increase odd.
  4. Return result. The even pointer stops at evens and the odd pointer stops at n.

Step-by-step example

nums = [3,1,2,4]
  1. Counting pass: 3 is odd, 1 is odd, 2 is even, 4 is even, so evens = 2.
  2. The output has 4 slots. Slots 0 and 1 are the even block, slots 2 and 3 are the odd block. Set even = 0 and odd = 2.
  3. 3 is odd, so it goes to slot 2 and odd becomes 3. 1 is odd, so it goes to slot 3 and odd becomes 4.
  4. 2 is even, so it goes to slot 0 and even becomes 1. 4 is even, so it goes to slot 1 and even becomes 2.
  5. Return [2,4,3,1].

Code: Python, Java, C++

1class Solution:
2    def sortArrayByParity(self, nums: List[int]) -> List[int]:
3        evens = sum(1 for x in nums if x % 2 == 0)
4        result = [0] * len(nums)
5        even, odd = 0, evens
6        for x in nums:
7            if x % 2 == 0:
8                result[even] = x
9                even += 1
10            else:
11                result[odd] = x
12                odd += 1
13        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass counts the evens and a second pass writes every value once, so the work is linear in the length of nums.

Space

O(n)

The output array holds all n values. Apart from it, only the count and two pointers are stored.

Other approaches

In-place swap with two pointers (time O(n), space O(1))

Keep a left pointer looking for odds and a right pointer looking for evens, and swap when both stop. It uses O(1) extra space and is what LeetCode's editorial shows, and is accepted here too. Swapping moves odds out of their original order, which is fine because any even-first arrangement passes.

Two filtered lists (time O(n), space O(n))

Collect the evens into one list and the odds into another, then concatenate. It is stable and very readable, and has the same complexity as the counting approach, with an extra temporary list.

Common mistakes

  • Starting the odd pointer at 0 or at n - 1 instead of at the even count. The odd block begins right after the last even slot.
  • Checking parity with x % 2 == 1 in languages where negative numbers give -1. The values here are non-negative, but x % 2 == 0 is the safer test in general.

Frequently asked questions

Does my output have to keep the original order?

No. The judge accepts any arrangement where every even value comes before every odd value and the values are the same as the input. The stable version shown here is one valid answer; the in-place swap version is another.

Can I keep it stable without extra memory?

Not in linear time with a simple method. Stable in-place partitioning needs rotations or block merges, which costs O(n log n) time or more. The O(n) extra array is the practical choice.

Why count first instead of filling from both ends?

Filling odds from the right end would place them in reverse order. Counting first tells you where the odd block starts, so you can fill it left to right in input order.

Is this the same idea as counting sort?

Yes. With only two keys (even and odd), counting the first key gives the starting offset of the second, and the placement pass is the stable distribution step of counting sort.