Given an array of integers, rearrange it so all even numbers come before all odd numbers. Any order within each group is acceptable.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array of integers, rearrange it so all even numbers come before all odd numbers. Any order within each group is acceptable.
A direct variation on the Segregate 0s and 1s partition, swapping the two-value condition for a parity check — good practice recognizing the same shape under a different rule.
Whenever elements need to be grouped in place by a two-way yes/no condition (even vs. odd, matches vs. doesn't), and the order within each group doesn't matter, boundary pointers closing in from both ends solve it in one pass.
Keep a left pointer starting at index 0 and a right pointer starting at the last index. Advance left forward past any value that's already even, and advance right backward past any value that's already odd. When left lands on an odd value and right lands on an even value, both are misplaced relative to each other, so swap them. Repeat until the pointers cross. Because stability isn't required, this in-place swap is sufficient — there's no need to preserve each group's original relative order, which is what would force a slower stable partition instead.
class Solution {
public int[] sortArrayByParity(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 == 0) {
left++;
} else if (nums[right] % 2 == 1) {
right--;
} else {
int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp;
}
}
return nums;
}
}