2Brute2Best
πŸ”₯0

Sort Array By Parity

EasyΒ·LeetCode #905Basic Anchor
LeetCode
30-Second Mental ModelTwo Pointers (Partition, two regions)
Complexity:O(N)β†’O(N)
Key Insight

Keep L at the left end and R at the right end. Everything left of L is a finished even, everything right of R is a finished odd, and the middle is unchecked. If nums[L] is even, it is already home, so move L right. If nums[R] is odd, it is already home, so move R left. Otherwise L is on an odd and R is on an even β€” swap them, and both are now home. Stop when the pointers meet.

Core Validity Invariant

At every moment, nums[0..L-1] are all even and nums[R+1..n-1] are all odd; only the middle nums[L..R] is still unknown. When the middle is empty, the whole array is arranged.

01

Problem

You are given an integer array nums.

Rearrange it so that all even numbers come first, followed by all odd numbers. Return the rearranged array.

The order inside the even group and inside the odd group does not matter. Any arrangement with every even before every odd is accepted.

Input

An integer array nums.

Output

An array with the same numbers, where every even number comes before every odd number.

Example 1
Input: nums = [3, 1, 2, 4]
Output: [2, 4, 3, 1]

2 and 4 are even, 3 and 1 are odd. [4, 2, 3, 1], [2, 4, 1, 3] and [4, 2, 1, 3] are also accepted.

Example 2
Input: nums = [0]
Output: [0]

One number is already arranged. (0 is even.)

Constraints
  • β€’ 1 ≀ nums.length ≀ 5000
  • β€’ 0 ≀ nums[i] ≀ 5000
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck β€” each hint is counted.

  1. 1.

    How many different kinds of numbers are there, as far as this problem cares?

  2. 2.

    Does the order inside the even group matter? What freedom does that give me?

  3. 3.

    If I build a brand-new array, how would I fill it?

  4. 4.

    Where does an even number belong β€” near the left end or the right end? And an odd one?

  5. 5.

    If I find a number that is on the wrong side, where could I find a partner to swap it with?

03

Brute force approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceTwo passes into a new array: first all evens, then all oddsO(N)O(N)
OptimalL looks for an odd, R looks for an even, swap them; O(1) extra spaceO(N)O(1)
09

Why does this belong to this pattern?

Clues in the problem statement
  • β€œall even numbers, then all odd numbers”Every number falls into one of a few fixed groups, and the groups have a fixed order β†’ partition.
  • β€œany order is accepted”We don't need to keep the original order inside a group, so swapping (which mixes up the order) is allowed.
  • β€œrearrange the array”We can do it in place: keep each finished group behind its own pointer.
Two fixed categories+order inside a group doesn't matter+rearrange in place→Two Pointers (Partition, two regions)

This is the anchor of the partition family. There is no sorting by value here β€” only which group a number is in. Learn the region idea: each finished group lives behind its own pointer, and the unchecked numbers sit in the middle. Sort Colors adds a third group (and a third pointer). Partition Array According to Given Pivot also has three groups, but there the order inside each group must be kept, which rules out swapping.

10

Don't make this mistake

Pattern confusion: sorting the array
βœ— sort(nums.begin(), nums.end());
βœ“ Partition by parity with two pointers (or two passes).

Sorting by value does not group by parity: [3, 1, 2, 4] sorted is [1, 2, 3, 4], which mixes evens and odds. And even a sort with a parity comparator costs O(N log N) for a job that needs one O(N) pass. This is a partition problem (put each number in its group), not a sorting problem.

Moving the pointers after the swap only sometimes
βœ— swap(nums[left], nums[right]); // forgot left++ / right--
βœ“ swap(nums[left], nums[right]); left++; right--;

Without moving, the loop still works but wastes steps re-checking the two numbers it just fixed. Worse, in versions where the checks are written as two separate while loops, forgetting to move can cause an infinite loop. After a swap, both cells are finished β€” move past them.

Missing the bounds check in inner loops
βœ— while (nums[left] % 2 == 0) left++;
βœ“ while (left < right && nums[left] % 2 == 0) left++;

If the array is all even, left runs past the end of the array. Always keep left < right inside every inner loop.

Checking odd with `x % 2 == 1` when negatives are possible

In C++, -3 % 2 is -1, not 1. The constraints here say nums[i] β‰₯ 0, so == 1 happens to work, but x % 2 != 0 is the habit that is always correct.

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.