#922
Easy Algorithms Sort array by parity ii
Array Two Pointers Sorting
71.2% acceptance
Feb 25, 2026
2809
104
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn sort_array_by_parity_ii(mut nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut j = 1usize;
for i in (0..n).step_by(2) {
if nums[i] % 2 != 0 {
while nums[j] % 2 != 0 { j += 2; }
nums.swap(i, j);
}
}
nums
}
}