Easy JAVA Solution that beats 99.70%|| Two Pointer Approach.||Beginner Friendly
IntuitionThe problem requires alternating even and odd numbers in the array. Since there are equal counts of even and odd numbers (as guaranteed by the problem)
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires alternating even and odd numbers in the array. Since there are equal counts of even and odd numbers (as guaranteed by the problem), we can:

- Separate the even and odd numbers.

- Rebuild the array by placing even numbers at even indices and odd numbers at odd indices.

# Approach
<!-- Describe your approach to solving the problem. -->
1. Separate Even and Odd Numbers:

- Traverse the array once, collecting even numbers in one array and odd numbers in another.
2. Rebuild the Original Array:

 - Use two separate indices, one for even numbers and one for odd numbers.

- Place the numbers alternately in the original array based on their 
 respective parity positions (even or odd).


# Complexity
- Time complexity:  O(n).
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(n).
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        int n = nums.length;
        int[] even = new int[n / 2];
        int[] odd = new int[n / 2];

        // Fill even and odd arrays
        int evenIndex = 0, oddIndex = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] % 2 == 0) {
                even[evenIndex++] = nums[i];
            } else {
                odd[oddIndex++] = nums[i];
            }
        }

        // Rebuild nums array with alternating even and odd numbers
        evenIndex = 0;
        oddIndex = 0;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                nums[i] = even[evenIndex++];
            } else {
                nums[i] = odd[oddIndex++];
            }
        }
        return nums;
    }
}
```
![upvote.webp](https://assets.leetcode.com/users/images/44bf3602-566e-475a-ae22-d86371707f52_1734762019.1468117.webp)

['Two Pointers', 'Java']