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:
Here are the steps I took to come to my first solution:
A
as an argument.even
numbers and another one to store the odd
numbers.A
.A
is even or odd by performing modulus operations (A[i] % 2 === 0
).A
to its corresponding array: even elements into the even array and odd elements into the odd array.Let’s have a better understanding by looking at the following implementation in JavaScript:
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