Given an integer array nums, return an array consisting of all the even elements followed by all the odd elements. The order within each group does not matter. You should do this in-place if possible.
The two-pointer approach is efficient: use a left pointer starting at 0 and a right pointer starting at the end. If the left element is odd and the right element is even, swap them. Then move left forward when it points to an even, and right backward when it points to an odd.
This runs in O(n) time with O(1) space (in-place). A simpler approach using sort with a custom comparator also works: compare elements by parity (even before odd).
Edge cases include an empty array, all evens (return unchanged), all odds (return unchanged), and a single element.
The two-pointer approach for parity sorting is efficient because it uses the fact that even/odd is a binary property. The algorithm is a variant of the partition step in quicksort and demonstrates how sorting constraints can be satisfied in linear time without a full sort.
The two-pointer approach for parity sorting is efficient, using O(n) time and O(1) space by swapping elements in place without a full sorting pass.Example Input & Output
All even.
Evens 2,4 before odds 3,1.
Single odd.
Empty.
Single even.
Algorithm Flow

Solution Approach
Two pointers: swap odd-left with even-right. Move inward until pointers cross.
Time O(n), Space O(1).
Best Answers
class Solution {
public int[] solution(int[] nums) {
int lo=0,hi=nums.length-1;
while (lo<hi) {
if (nums[lo]%2==1&&nums[hi]%2==0) {
int t=nums[lo];nums[lo]=nums[hi];nums[hi]=t;
lo++;hi--;
} else {
if (nums[lo]%2==0) lo++;
if (nums[hi]%2==1) hi--;
}
}
return nums;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
