Sort Array By Parity
For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:
This problem is asking us to create a function that returns an array where the even numbers are at the beginning of the array and the odd numbers are at the end. For more clarification, example 1 does a great job in explaining the inputs and outputs. Our input array is [3,1,2,4]
and we can see that the output displays even numbers at the beginning and odd numbers at the end. Something else to keep in mind is that there’s no specific order, which is why the example states that outputs such as [4,2,31]
and [2,4,1,3]
can also be accepted as valid answers.
Now that we know what the question is asking us to do, now we need to pseudo code what the process should be to solve this problem. Here’s a screenshot of my pseudo code:
As stated in the picture above, the first step should be creating an empty array since the question is asking us to return an array of integers. The second step should be creating a loop to iterate over the nums
array. We can use a forEach
, for of
, etc., but for this problem, I’ll be using a for loop
statement. Here’s what the code looks like so far:
The next two steps will take place inside of the for loop
! For the third step, we need to create a conditional that will put the even numbers on the front of the array. Even numbers are divisible by 2, so the best way to approach the conditional logic is by using a modulo
or remainder operator(%)
. We also need to use .unshift()
to place the even numbers on the front. The fourth step would just be the opposite of step three, if the number is not even, then place that number at the end of the array. The method .push()
would be used to place the odd numbers at the end of the array. Here’s what the code looks like so far:
The last step will take place right outside of the for loop. All we need to do is return result
since we changed its value during the iteration. Here’s the full solution:
Here’s the test case results from lines 20 and 21 from the picture above:
Here are the results from LeetCode:
I hope I was able to explain this problem well! For more info on for loops
, modulo operators
, and built in methods such as push()
, and unshift()
checkout the resource section below!
Resources: