905. Sort Array By Parity
Problem Description
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 <= 50000 <= nums[i] <= 5000
Solution
Python Solution
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums) - 1
while left < right:
if nums[left] % 2 == 1 and nums[right] % 2 == 0:
nums[left], nums[right] = nums[right], nums[left]
if nums[left] % 2 == 0:
left += 1
if nums[right] % 2 == 1:
right -= 1
return nums
Time Complexity: O(n)
We need to traverse the array once.
Space Complexity: O(1)
We modify the array in-place.
Java Solution
class Solution {
public int[] sortArrayByParity(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 == 1 && nums[right] % 2 == 0) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
if (nums[left] % 2 == 0) {
left++;
}
if (nums[right] % 2 == 1) {
right--;
}
}
return nums;
}
}
Time Complexity: O(n)
We need to traverse the array once.
Space Complexity: O(1)
We modify the array in-place.
C++ Solution
class Solution {
public:
vector sortArrayByParity(vector& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
if (nums[left] % 2 == 1 && nums[right] % 2 == 0) {
swap(nums[left], nums[right]);
}
if (nums[left] % 2 == 0) {
left++;
}
if (nums[right] % 2 == 1) {
right--;
}
}
return nums;
}
};
Time Complexity: O(n)
We need to traverse the array once.
Space Complexity: O(1)
We modify the array in-place.
JavaScript Solution
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortArrayByParity = function(nums) {
let left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 === 1 && nums[right] % 2 === 0) {
[nums[left], nums[right]] = [nums[right], nums[left]];
}
if (nums[left] % 2 === 0) {
left++;
}
if (nums[right] % 2 === 1) {
right--;
}
}
return nums;
};
Time Complexity: O(n)
We need to traverse the array once.
Space Complexity: O(1)
We modify the array in-place.
C# Solution
public class Solution {
public int[] SortArrayByParity(int[] nums) {
int left = 0, right = nums.Length - 1;
while (left < right) {
if (nums[left] % 2 == 1 && nums[right] % 2 == 0) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
if (nums[left] % 2 == 0) {
left++;
}
if (nums[right] % 2 == 1) {
right--;
}
}
return nums;
}
}
Time Complexity: O(n)
We need to traverse the array once.
Space Complexity: O(1)
We modify the array in-place.