algoadvance

Leetcode 905. Sort Array By Parity

Problem Statement

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:

Clarifying Questions

  1. Should the relative order of even and odd integers be maintained within their groups?
    • No, the relative order does not need to be maintained.
  2. Can the input array contain negative integers?
    • Typically, the emphasis will be on even and odd regardless of negative signs, but let’s assume input as non-negative unless specified otherwise.
  3. Is the input array mutable, i.e., can we modify it in place?
    • You can return a new array or modify it in place, as either approach results in valid output.

Let’s proceed with writing the solution in Java.

Strategy

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.

Code

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 + " ");
        }
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI