Sort Array by Parity

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Sort Array by Parity

Approach

Use two pointers from both ends. If left points to even, advance left. If right points to odd, retreat right. If left is odd and right is even, swap them. This is a simplified partition (like QuickSort) around the condition "is even".

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Partition

Why It Works

The two-pointer partition ensures all even numbers migrate to the left portion and all odd numbers to the right. Each element is visited at most once from each side, giving O(n) time. This is the same partition logic used in QuickSort, simplified to a boolean condition.

Updated Feb 2026