Sort Array By Parity II LeetCode Solution - The Coding Shala

Home >> LeetCode >> Sort Array By Parity 2

 In this post, we will learn how to solve LeetCode's Sort Array By Parity 2 Problem and will implement its solution in Java.

Sort Array By Parity 2 Problem

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Practice this Problem on LeetCode(Click Here).

Sort Array By Parity 2 Java Solution

Approach 1

This problem can be solved by using two pointers.

Java Program: 

class Solution {
    public int[] sortArrayByParityII(int[] A) {
        int even = 0, odd = 1;
        while(even < A.length && odd < A.length){
            if(A[even]%2==1){
                int tmp = A[even];
                A[even] = A[odd];
                A[odd] = tmp;
                odd += 2;
            }else{
                even += 2;
            }
        }
        return A;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

Spiral Order Matrix II - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

First Missing Positive Solution - The Coding Shala