#905
Easy Algorithms Sort array by parity
Array Two Pointers Sorting
76.5% acceptance
Feb 25, 2026
5675
156
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.
Solution
Rust
Time O(n)
Space O(1)
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 && nums[r] % 2 == 0 { nums.swap(l, r); }
if nums[l] % 2 == 0 { l += 1; }
if nums[r] % 2 != 0 { if r == 0 { break; } r -= 1; }
}
nums
}
}