Partition in place with pointers from both ends, swapping an odd left value with an even right value.
Complexity
O(n) time and O(1) extra space.
Reorder an array so all even values appear before all odd values.
Partition in place with pointers from both ends, swapping an odd left value with an even right value.
O(n) time and O(1) extra space.
package main
func sortArrayByParity(nums []int) []int {
left, right := 0, len(nums)-1
for left < right {
for left < right && nums[left]%2 == 0 {
left++
}
for left < right && nums[right]%2 != 0 {
right--
}
nums[left], nums[right] = nums[right], nums[left]
}
return nums
}
class Solution:
def sortArrayByParity(self, nums: list[int]) -> list[int]:
left, right = 0, len(nums) - 1
while left < right:
while left < right and nums[left] % 2 == 0: left += 1
while left < right and nums[right] % 2: right -= 1
nums[left], nums[right] = nums[right], nums[left]
return nums
function sortArrayByParity(nums: number[]): number[] {
let left = 0;
let right = nums.length - 1;
while (left < right) { while (left < right && nums[left] % 2 === 0) left += 1; while (left < right && nums[right] % 2 !== 0) right -= 1; [nums[left], nums[right]] = [nums[right], nums[left]]; }
return nums;
}