Skip to main content

Sort Array By Parity in Java | Programming Tutorial | LeetCode Problem

Sort Array as Odd numbers followed by Even numbers in Java | Sort array as store All even numbers first and all Odd numbers last.

Sort array based on even and odd numbers in java

Given an array of non-negative integers, return an array consisting of all the even elements of array followed by all the odd elements of array.

You may return any answer array that satisfies this condition.

Example 1 :-

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

See description in Leetcode :-

So lets see solution of above problem.

Solution 1 : In place with For loop

class Solution {
    public int[] sortArrayByParity(int[] array) {
        if (array.length > 1) {
            int rightIndex = array.length - 1;

            for (int leftIndex = 0; leftIndex < array.length;) {
                
                if (array[leftIndex] % 2 != 0 && array[rightIndex] % 2 == 0) {
                    int temp = array[leftIndex];
                    array[leftIndex] = array[rightIndex];
                    array[rightIndex] = temp;
                }
                
                if (rightIndex <= (leftIndex+1)) {
                    break;
                }
                
                if (array[leftIndex] % 2 == 0) {
                    leftIndex++;
                }
                
                if (array[rightIndex] % 2 != 0) {
                    rightIndex--;
                }
                
            }
        }
        return array;
    }

Solution Explanation :-

  • In first condition check if array is greater than 1 or not. If it is greater than 1 then we are going inside.
  • Declare one variable rightIndex and initialize with last array index value.
  • Traverse array from left to right till array length.
  • Now we want all Even numbers at left side and all odd numbers at right side in array so In if condition, check first array value is odd and last array value is even or not. If both condition becomes true then we swap both values.
  • In second if condition, we are checking rightIndex is crossed by leftIndex or not. If it crossed that means our array is sorted and break the for loop.
  • In third if, check leftIndex value is even or not. if it is even then we move to next index (leftIndex++).
  • In fourth if, check rightIndex value is odd or not. if it is odd then move to previous index (Traverse array right to left).

Output Explanation :-

array = [3, 1, 2, 4]

  • array.length > 1 becomes true.
  • rightIndex = 3, leftIndex = 0
    • array[0] % 2 != 0 && array[3] % 2 == 0 becomes true.
      • First if | Swap both values. array = [4, 1, 2, 3]
      • Second if | 3 <= 0 becomes false
      • Third if | 4 % 2 == 0 becomes true. leftIndex = 1
      • Fourth if | 3 % 2 != 0 becomes true. rightIndex = 2

  • array = [4, 1, 2, 3], rightIndex = 2, leftIndex = 1
    •  array[1] % 2 != 0 && array[2] % 2 == 0 becomes true.
      • First if | Swap both values. array = [4, 2, 1, 3]
      • Second if | 2 <= 2 becomes true. and break the for loop.

  • array = [4, 2, 1, 3]

In above solution we are using for loop, in next solution let's try with while loop.

Solution 2 : In place with While loop

class Solution {
    
    public int[] sortArrayByParity(int[] array) {
        int leftIndex = 0, rightIndex = array.length - 1;
        while (leftIndex < rightIndex) {
            if (array[leftIndex] % 2 > array[rightIndex] % 2) {
                int temp = array[leftIndex];
                array[leftIndex] = array[rightIndex];
                array[rightIndex] = temp;
            }

            if (array[leftIndex] % 2 == 0) leftIndex++;
            if (array[rightIndex] % 2 == 1) rightIndex--;
        }

        return array;
    }
}

We can also solve this problem by using another empty array. So basically we can traverse through given array and check it is Even number or Odd number, based on that we can store values in newly array. 

So let's see how we can achieve that.

Solution 3 : Using extra array

class Solution {
    public int[] sortArrayByParity(int[] array) {
        int[] ans = new int[array.length];

        int leftIndex = 0;
        int rightIndex = array.length - 1;

        for (int i = 0; i < array.length; i++) {
            if (array[i] % 2 == 0) {
                ans[leftIndex++] = array[i];
            } else {
                ans[rightIndex--] = array[i];
            }
        }

        return ans;
    }
}

Explanation :-

  • In this solution, we are declare and creating new array same as old array length.
  • Take two variables, leftIndex assign with 0 and rightIndex assign with array's last index.
  • Traverse array from left to right.
  • In if condition, check number is Even. If it is even then assign that value to newly created array at leftIndex. otherwise it is Odd value and assign value based on rightIndex. 

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last