Inplace solution using two pointers - Java
It is given that the array will have same count of even and odd numbers which means that the length of the array will always be even. \nIf we maintain two point
It is given that the array will have same count of even and odd numbers which means that the length of the array will always be even. \nIf we maintain two pointers `left` and `right` at opposite ends of the array, i.e.,\n\n```java\nleft = 0\nright = n - 1\n```\n\nThen we can safely say that `left` will be at even index and `right` will be at odd index. We will use this property and always make sure that the element at `left` will always be even and element at `right` will always be odd. We will move both pointers two steps ahead and behind respectively. It will result in the following three cases -\n\n1. If both the elements are violating the constraint, we will swap them and move both pointers\n2. If only a single element is violating the constraint, we will move that pointer only.\n3. If both the elements are not violating the constraint, we will just move both the pointers.\n\n```java\npublic class Problem28_SortArrayByParityII {\n\n    public int[] sortArrayByParityII(int[] nums) {\n        // Special case\n        if (nums == null || nums.length == 0) {\n            return nums;\n        }\n        // Length of the array\n        int n = nums.length;\n        // Left and right pointers\n        int left = 0;\n        int right = n - 1;\n        // Loop until the condition is met\n        while (left < n && right >= 0) {\n            // If both the numbers at wrong positions, we will swap them\n            if (nums[left] % 2 == 1 && nums[right] % 2 == 0) {\n                int temp = nums[left];\n                nums[left] = nums[right];\n                nums[right] = temp;\n                left += 2;\n                right -= 2;\n            }\n            // If the left number is at wrong position but right\n            // number is at correct position, we will move right\n            // pointer two steps before\n            else if (nums[left] % 2 == 1 && nums[right] % 2 == 1) {\n                right -= 2;\n            }\n            // If the right number is at wrong position but left\n            // number is at correct position, we will move left\n            // pointer two steps after\n            else if (nums[left] % 2 == 0 && nums[right] % 2 == 0) {\n                left += 2;\n            }\n            // If both the numbers are at correct position, we just move\n            // both the pointers\n            else {\n                left += 2;\n                right -= 2;\n            }\n        }\n        return nums;\n    }\n}\n```
['Two Pointers']