[Java 98.84% Faster] Sort Array By Parity || One-pass & In-place Solution

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int low = 0;                                    // A var to point the left part of the array; Initially pointing at the first index
        int high = nums.length - 1;                     // A var to point the right part of the array; Initially pointing at the last index
        
        while(low <= high){                             // Run a loop till 'low' is less than or equal to 'high'
            if(nums[low]%2 == 1 && nums[high]%2 == 0){  // Check if the value at index 'low' is Odd and the value at index 'high' is Even or not
                nums[low] += nums[high];                // If Yes, then swap the values of indexes 'low' and 'high'
                nums[high] = nums[low]-nums[high];
                nums[low++] -= nums[high--];
            }
            else{                                       // Else
                if(nums[low]%2 == 0){                   // Check if the value at index 'low' is Even or not
                    low++;                              // If Yes, then leave it and move 'low' to the next index
                }
                if(nums[high]%2 == 1){                  // Also check if the value at index 'high' is Odd or not
                    high--;                             // If Yes, then leave it and move 'high' to the previous index
                }
            }
        }
        return nums;                                    // Finally, return the 'nums' array which has all the values sorted by parity in-place
    }
}

image

Comments (0)