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){
                int tmp = A[even];
                A[even] = A[odd];
                A[odd] = tmp;
                odd += 2;
                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.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

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

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala