Sort Array By Parity
Given an integer array nums, move all the even integers to the beginning of the array, followed by all the odd integers . Any order within each group is acceptable, so any valid answer will be accepted. Use two pointers starting at the left and right ends, swapping an odd value found on the left with an even value found on the right as they converge toward the middle.
Constraints
- 1 ≤ nums.length ≤ 5000
- 0 ≤ numsi ≤ 5000
Example
nums = [3, 1, 2, 4][4, 2, 1, 3]Explanation Any arrangement with the evens before the odds is accepted; this two-pointer trace produces [4, 2, 1, 3].
Swap an odd from the left with an even from the right
left=0 (3) is odd, right=3 (4) is even — both are on the wrong side, about to swap.
What happens in this step
left = 0 (value 3, odd), right = 3 (value 4, even) Neither pointer can advance on its own (left isn't even, right isn't odd), so this is a genuine mismatch pair — about to swap.
Steps to visualize
- Place one pointer at the start and one at the end of the array.
- Move the left pointer right while it sits on an even value.
- Move the right pointer left while it sits on an odd value.
- Swap the odd value at the left with the even value at the right.
- Repeat until the pointers meet or cross.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
left=0 (3) is odd, right=3 (4) is even — both are on the wrong side, about to swap.
What happens in this step
left = 0 (value 3, odd), right = 3 (value 4, even) Neither pointer can advance on its own (left isn't even, right isn't odd), so this is a genuine mismatch pair — about to swap.
Solution
function sortArrayByParity(nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 === 0) {
left++;
} else if (nums[right] % 2 !== 0) {
right--;
} else {
const temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
return nums;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [3, 1, 2, 4] | [4, 2, 1, 3] | example from the docstring |
nums = [2, 4, 6] | [2, 4, 6] | every value is already even |
nums = [1, 3, 5] | [1, 3, 5] | every value is odd |
nums = [2, 4, 1, 3] | [2, 4, 1, 3] | already sorted by parity, no swaps needed |
nums = [1] | [1] | smallest valid input, a single element |
nums = [1, 2] | [2, 1] | boundary case, exactly two elements requiring one swap |
nums = [3, 1, 2, 4, 6, 5] | [6, 4, 2, 1, 3, 5] | several swaps required across a longer array |