Sort Array By Parity
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Examples
Example 1:
Input:
nums = [3,1,2,4]
Output:
[2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input:
nums = [0]
Output:
[0]
Solution
Method 1 - Two Pointer Partitioning
Intuition
We want to move all even numbers to the front and all odd numbers to the back. By using two pointers, we can swap misplaced elements in-place, efficiently partitioning the array.
Approach
- Initialize two pointers: one at the start (
l), one at the end (r). - Move
lforward if it points to an even number. - If
lpoints to an odd number, swap it with the element atrand moverbackward. - Continue until
lmeetsr. - Return the modified array.
Complexity
- ⏰ Time complexity:
O(n)— Each element is checked at most once. - 🧺 Space complexity:
O(1)— In-place swaps, no extra space.
Code
Java
class Solution {
public int[] sortArrayByParity(int[] nums) {
int l = 0, r = nums.length - 1;
while (l < r) {
if (nums[l] % 2 == 0) {
l++;
} else {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
r--;
}
}
return nums;
}
}
Python
class Solution:
def sortArrayByParity(self, nums):
l, r = 0, len(nums) - 1
while l < r:
if nums[l] % 2 == 0:
l += 1
else:
nums[l], nums[r] = nums[r], nums[l]
r -= 1
return nums
C++
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
if (nums[l] % 2 == 0) {
l++;
} else {
swap(nums[l], nums[r]);
r--;
}
}
return nums;
}
};
Go
func sortArrayByParity(nums []int) []int {
l, r := 0, len(nums)-1
for l < r {
if nums[l]%2 == 0 {
l++
} else {
nums[l], nums[r] = nums[r], nums[l]
r--
}
}
return nums
}
Kotlin
class Solution {
fun sortArrayByParity(nums: IntArray): IntArray {
var l = 0
var r = nums.size - 1
while (l < r) {
if (nums[l] % 2 == 0) {
l++
} else {
val tmp = nums[l]
nums[l] = nums[r]
nums[r] = tmp
r--
}
}
return nums
}
}
Rust
impl Solution {
pub fn sort_array_by_parity(mut nums: Vec<i32>) -> Vec<i32> {
let (mut l, mut r) = (0, nums.len() - 1);
while l < r {
if nums[l] % 2 == 0 {
l += 1;
} else {
nums.swap(l, r);
r -= 1;
}
}
nums
}
}
TypeScript
class Solution {
sortArrayByParity(nums: number[]): number[] {
let l = 0, r = nums.length - 1;
while (l < r) {
if (nums[l] % 2 === 0) {
l++;
} else {
[nums[l], nums[r]] = [nums[r], nums[l]];
r--;
}
}
return nums;
}
}