Skip to content

Two Pointers — Sort Array By Parity ​

↗ LeetCode: Sort Array By Parity · Easy · pattern chapter →

Asked atMetaAmazon

Rearrange so all even values come before all odd. Any valid partition accepted.

Example 1 — nums=[3,1,2,4] → [2,4,3,1] or [4,2,3,1] etc. Example 2 — nums=[0] → [0]Example 3 — nums=[1,3,5,2,4] → [2,4,5,3,1] or [4,2,3,5,1]

Constraints — 1 ≤ n ≤ 5000. Brute allocation + copy is O(n) time + O(n) space. Two-pointer in-place is O(n) time + O(1) space. Brute two-pass (write evens, then odds) is O(n) time + O(n) space. In-place two-pointer partition is O(n) = ~10⁶ ops with O(1) space — the Dutch-flag pattern.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Two-pass allocation ​

Intuition. Walk once collecting evens, then once collecting odds. Concatenate.

java
int[] sortArrayByParityBrute(int[] nums) {
    int[] res = new int[nums.length];
    int idx = 0;
    for (int x : nums) if (x % 2 == 0) res[idx++] = x;
    for (int x : nums) if (x % 2 == 1) res[idx++] = x;
    return res;
}

Complexity — Time O(n); Space O(n). Correct, but allocates a new array. In an interview say "in-place with two pointers → O(1) extra space."


Approach 2 — Opposing pointers + swap (canonical) ​

Insight. l from left seeks first odd; r from right seeks first even; swap; repeat until they meet. In-place, O(n), O(1) extra space.

java
int[] sortArrayByParity(int[] nums) {
    int l = 0, r = nums.length - 1;
    while (l < r) {
        if (nums[l] % 2 == 0) l++;
        else if (nums[r] % 2 == 1) r--;
        else { int t = nums[l]; nums[l++] = nums[r]; nums[r--] = t; }
    }
    return nums;
}
Execution Trace
Opposing pointers + swap (canonical)
i30112243phase = start
Step 1 / 3Initialize scan.

Complexity — Time O(n); Space O(1). Say aloud in an interview: "same in-place partition template as Dutch National Flag and Move Zeroes."

Trap — for stable ordering (preserving relative order), use slow/fast writer instead.


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceGrade
Two-pass allocationO(n)O(n)Fine baseline
Opposing 2p in-placeO(n)O(1)Canonical

When to use which ​

  • "Any valid partition" → opposing 2p.
  • "Stable ordering" → slow/fast writer + zero-fill (order-preserving).
  • Three-way partition → Dutch national flag.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help