905. Sort Array By Parity(Solution || Leetcode easy || Java)

Palakkgoyal
2 min readNov 14, 2022

--

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Example 1:

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

Example 2:

Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

SOLUTION:

class Solution {
public int[] sortArrayByParity(int[] nums) {
//initialise an array to return
int[] ans = new int[nums.length];

//initialise variable to add even elements at starting indexes
int i = 0;

//initialise variable to add odd elements at end indexes
int j = nums.length — 1;

//start loop to iterate over each element
for(int k = 0; k < nums.length; k++){
//if element is even, add that element in the starting of our ans array
if(nums[k]%2 == 0){
ans[i] = nums[k];
i++;
}
//if element is odd, add that element in the end of ans array
else{
ans[j] = nums[k];
j — ;
}
}

return ans;
}
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Sort Array By Parity.

Memory Usage: 48.3 MB, less than 54.07% of Java online submissions for Sort Array By Parity.

Thank you for reading. If you have any queries then, please let me know me in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet