Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Partition an array by parity

Reorder an array so that all even numbers appear before odd numbers using an in-place approach.

Python practice15 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given a list of integers, reorder the list in-place so that all even numbers appear before all odd numbers. The relative order within the even group or within the odd group does not need to be preserved. Return the modified list. The function should operate in O(n) time and O(1) extra space.

Task

Implement an in-place partition that groups even numbers before odd numbers (parity-based partition) using O(1) extra space and O(n) time.

Examples

Mix of even and odd

Input

partition_by_parity([3, 1, 2, 4])

Output

[4, 2, 1, 3]

One valid partition places even numbers 4 and 2 before odd numbers; order inside groups is not required to be preserved.

Input format

A single list of integers, e.g. [3, 1, 2, 4].

Output format

Return the same list object after partitioning, e.g. [4, 2, 1, 3].

Constraints

0 <= len(arr) <= 10^5; integers can be negative or positive. Must be in-place (O(1) extra space).

Samples

Sample 1

Input

[2, 4, 6, 1, 3]

Output

[2, 4, 6, 1, 3]

Already partitioned with evens first; function may leave it unchanged.