28.09.2023
905. Sort Array By Parity medium
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/353
Problem TLDR
Sort an array by even-odd
Intuition
There are built-in functions. However, in an interview manual partition is expected: maintain the sorted border l
and adjust it after swapping.
Approach
Let’s write them all.
Complexity
Time complexity:
O(n)Space complexity:
O(1)
Code
// 1
fun sortArrayByParity(nums: IntArray) = nums.also {
var l = 0
for (r in nums.indices) if (nums[r] % 2 == 0)
nums[r] = nums[l].also { nums[l++] = nums[r] }
}
// 2
fun sortArrayByParity(nums: IntArray) =
nums.partition { it % 2 == 0 }.toList().flatten()
// 3
fun sortArrayByParity(nums: IntArray) = nums.sortedBy { it % 2 }