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

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala