Sort Array By Parity

Given an array nums, return an array where all even numbers come first, followed by all odd numbers. The relative order within each group does not matter.

Example 1
Input: [3,1,2,4] → Output: [2,4,3,1]
Example 2
Input: [0] → Output: [0]

Solution Approach

Two pointers: lo starts at 0, hi at end. When lo is odd and hi is even, swap them.

  • lo=0, hi=n-1.
  • While lo
  • If lo
Java
class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int lo = 0, hi = nums.length - 1;
        while (lo < hi) {
            while (lo < hi && nums[lo] % 2 == 0) lo++;
            while (lo < hi && nums[hi] % 2 == 1) hi--;
            if (lo < hi) {
                int tmp = nums[lo]; nums[lo] = nums[hi]; nums[hi] = tmp;
                lo++; hi--;
            }
        }
        return nums;
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(1)