922. Sort Array By Parity II

Explanation

To solve this problem, we can use a two-pointer approach. We will maintain two pointers, one for even indices and one for odd indices. We iterate through the array and whenever we find an element at the wrong position (even number at an odd index or odd number at an even index), we swap it with the element at the correct position. This way, we can ensure that the array is sorted such that even numbers are at even indices and odd numbers are at odd indices.

  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(1) since we are performing the sorting in-place.
class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        int odd = 1, even = 0;
        while (even < nums.length && odd < nums.length) {
            while (even < nums.length && nums[even] % 2 == 0) {
                even += 2;
            }
            while (odd < nums.length && nums[odd] % 2 == 1) {
                odd += 2;
            }
            if (even < nums.length && odd < nums.length) {
                int temp = nums[even];
                nums[even] = nums[odd];
                nums[odd] = temp;
            }
        }
        return nums;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.