Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Move even numbers before odd numbers in-place

Partition an integer list in-place so that all even numbers appear before odd numbers using a two-pointer approach.

Python practice15 minTwo Pointers & Sliding WindowIntermediateLast updated March 26, 2026

Problem statement

Given a list of integers nums, reorder the elements in-place so that all even numbers come before all odd numbers. The relative order among even numbers or among odd numbers does not need to be preserved. Return the same list object after partitioning. You must perform the operation in-place using O(1) additional memory and in linear time.

Task

Use two pointers to rearrange an array in-place so that every even number is positioned before any odd number. Achieve O(n) time and O(1) extra space.

Examples

Basic partition

Input

nums = [3, 1, 2, 4, 7, 6]

Output

[6, 4, 2, 1, 7, 3]

A two-pointer partition swaps odd numbers on the left with even numbers on the right. Evens (6,4,2) appear before odds (1,7,3).

Input format

A single function call move_even_before_odd(nums) where nums is a list of integers.

Output format

Return the same list object after reordering so that all even integers appear before all odd integers.

Constraints

0 <= len(nums) <= 10^5; integers can be negative, zero, or positive. In-place (O(1) extra space) and O(n) time required.

Samples

Sample 1

Input

[2, 4, 6]

Output

[2, 4, 6]

All elements are even; the list remains the same.