Sort Array By Parity

easy two pointers array partition

Problem

Given an integer array nums, move every even integer in front of every odd integer and return the result. Any arrangement that satisfies this condition is accepted, so the relative order within each group does not matter.

Inputnums = [3, 1, 2, 4]
Output[4, 2, 1, 3]
Evens (4, 2) come before odds (1, 3). [2, 4, 3, 1] would also be a valid answer.

def sort_array_by_parity(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        if nums[left] % 2 == 0:
            left += 1
        elif nums[right] % 2 == 1:
            right -= 1
        else:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1
    return nums
function sortArrayByParity(nums) {
  let left = 0, right = nums.length - 1;
  while (left < right) {
    if (nums[left] % 2 === 0) {
      left++;
    } else if (nums[right] % 2 === 1) {
      right--;
    } else {
      [nums[left], nums[right]] = [nums[right], nums[left]];
      left++;
      right--;
    }
  }
  return nums;
}
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 tmp = nums[left];
                nums[left] = nums[right];
                nums[right] = tmp;
                left++;
                right--;
            }
        }
        return nums;
    }
}
vector<int> sortArrayByParity(vector<int>& nums) {
    int left = 0, right = (int)nums.size() - 1;
    while (left < right) {
        if (nums[left] % 2 == 0) {
            left++;
        } else if (nums[right] % 2 == 1) {
            right--;
        } else {
            swap(nums[left], nums[right]);
            left++;
            right--;
        }
    }
    return nums;
}
Time: O(n) Space: O(1)