Community Problem

Sort Array By Parity

Difficulty: Easy

Rearrange the array so that every even integer appears before every odd integer; any valid arrangement is accepted.

Sort Array By Parity

Rearrange the array so that every even integer appears before every odd integer; any valid arrangement is accepted.

EASY
Free
arrays
two-pointers
fundamentals
riverbanda

By @riverbanda

December 20, 2025

·

Updated May 18, 2026

180 views

2

4.0 (9)

I keep coming back to this one whenever a candidate tells me they are comfortable with two pointers but only ever practice on Two Sum. The trick is the partition shape: there is no relative-order requirement, just a "all evens left of all odds" invariant, which makes the in-place swap version a clean stress test for whether the two-pointer mental model has actually clicked.

Sort Array By Parity

Given an integer array nums, move every even integer to the front and every odd integer to the back. Return any array that satisfies this property. The relative order among the even values does not need to be preserved, and the relative order among the odd values does not need to be preserved either.

Examples

Example 1:

  • Input: nums = [3, 1, 2, 4]
  • Output: [2, 4, 3, 1]
  • Explanation: [2, 4, 1, 3], [4, 2, 1, 3], and [4, 2, 3, 1] are also accepted; any output with both evens at the front is valid.

Example 2:

  • Input: nums = [0]
  • Output: [0]
  • Explanation: A single element is trivially sorted by parity.

Example 3:

  • Input: nums = [1, 3, 5]
  • Output: [1, 3, 5]
  • Explanation: All odd, no rearrangement is required.

Example 4:

  • Input: nums = [2, 4, 6]
  • Output: [2, 4, 6]
  • Explanation: All even, no rearrangement is required.

Constraints

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

Follow-up

Can you solve this in O(n) time and O(1) extra space, without a second array? The expected solution uses two pointers walking from opposite ends and swaps misplaced pairs.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems