Leetcode 905. Sort Array By Parity
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.
nums = [3, 1, 2, 4]
[2, 4, 3, 1]
[4, 2, 3, 1]
, [2, 4, 1, 3]
, and [4, 2, 1, 3]
would also be accepted.Let’s proceed with writing the solution in Java.
We can use a two-pointer technique to rearrange the array in-place. The basic idea is to have one pointer start from the beginning (left = 0) and one from the end (right = nums.length - 1). We then swap elements if required as we traverse the array.
By the end, all even numbers will be at the beginning of the array and all odd numbers at the end.
public class SortArrayByParity {
public int[] sortArrayByParity(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 != 0 && nums[right] % 2 == 0) {
// Swap elements at left and right
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
if (nums[left] % 2 == 0) {
left++;
}
if (nums[right] % 2 != 0) {
right--;
}
}
return nums;
}
public static void main(String[] args) {
SortArrayByParity solution = new SortArrayByParity();
int[] input = {3, 1, 2, 4};
int[] result = solution.sortArrayByParity(input);
// Print the result array
for (int num : result) {
System.out.print(num + " ");
}
}
}
left
and right
). We are modifying the array in place and not using extra space proportional to the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?