In this post, I will walk through how I solved the “Sort Array By Parity” problem on LeetCode.

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

You may return any answer array that satisfies this condition.

Example:

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.

There are multiple accepted solutions for this problem and I will share two of those with you:


My First Approach

Here are the steps I took to come to my first solution:

  1. Define a function, which accepts an array called A as an argument.
  2. Create two empty arrays; one to store the even numbers and another one to store the odd numbers.
  3. Iterate through the given array; A.
  4. Check if the current element of the A is even or odd by performing modulus operations (A[i] % 2 === 0).
  5. Push each element of the A to its corresponding array: even elements into the even array and odd elements into the odd array.
  6. Append the elements of the odd array to the array of even elements and return that.

Let’s have a better understanding by looking at the following implementation in JavaScript:

Image for post

The given array; A, is split into two separate arrays; even, which contains all the even numbers, and odd, which contains all the odd numbers. Then, these two arrays are combined in a way that even elements are followed by odd elements.

#algorithms #ruby #arrays #javascript #programming

Sort Array By Parity Problem
3.30 GEEK