LeetCode Problem - Link


Problem

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

 

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.



Two Pointer Solution

I had tried this out myself without looking up solutions, I remembered some solutions where the while loop ran til the left_index is lesser than the right_index back in the day, I never solved it, but I was able to put that idea into practice and it was pretty easy to pull it out

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParity = function (nums) {
    let left_index = 0;
    let right_index = nums.length;


    let temp = null;


    while (left_index < right_index) {
        let is_left_num_odd = nums[left_index] % 2 !== 0
        let is_right_num_even = nums[right_index] % 2 == 0;


        if (!is_left_num_odd) {
            left_index += 1;
        }
        if (!is_right_num_even) {
            right_index -= 1;
        }


        if (is_left_num_odd && is_right_num_even) {
            temp = nums[left_index];
            nums[left_index] = nums[right_index]
            nums[right_index] = temp
        }


    }
    return nums


};