Sort Array By Parity (LeetCode 905): Solution and Explanation
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
- Count how many values in
numsare even and call itevens. - Create an output array of the same length. Set
even = 0andodd = evens. - For each value
xinnums: ifxis even, write it atresult[even]and increaseeven; otherwise write it atresult[odd]and increaseodd. - Return
result. The even pointer stops atevensand the odd pointer stops atn.
Step-by-step example
nums = [3,1,2,4]
- Counting pass: 3 is odd, 1 is odd, 2 is even, 4 is even, so
evens = 2. - The output has 4 slots. Slots 0 and 1 are the even block, slots 2 and 3 are the odd block. Set
even = 0andodd = 2. - 3 is odd, so it goes to slot 2 and
oddbecomes 3. 1 is odd, so it goes to slot 3 andoddbecomes 4. - 2 is even, so it goes to slot 0 and
evenbecomes 1. 4 is even, so it goes to slot 1 andevenbecomes 2. - 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 result1class Solution {
2 public int[] sortArrayByParity(int[] nums) {
3 int evens = 0;
4 for (int x : nums) if (x % 2 == 0) evens++;
5 int[] result = new int[nums.length];
6 int even = 0, odd = evens;
7 for (int x : nums) {
8 if (x % 2 == 0) {
9 result[even++] = x;
10 } else {
11 result[odd++] = x;
12 }
13 }
14 return result;
15 }
16}1class Solution {
2public:
3 vector<int> sortArrayByParity(vector<int>& nums) {
4 int evens = 0;
5 for (int x : nums) if (x % 2 == 0) evens++;
6 vector<int> result(nums.size());
7 int even = 0, odd = evens;
8 for (int x : nums) {
9 if (x % 2 == 0) {
10 result[even++] = x;
11 } else {
12 result[odd++] = x;
13 }
14 }
15 return result;
16 }
17};Time and space complexity
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.
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 - 1instead of at the even count. The odd block begins right after the last even slot. - Checking parity with
x % 2 == 1in languages where negative numbers give-1. The values here are non-negative, butx % 2 == 0is 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.