Sort Array By Parity
Question
Given an array
A
of non-negative integers, return an array consisting of all the even elements ofA
, followed by all the odd elements ofA
.You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Solution
Approach 1: Sort
Since the array is already sorted, we can keep two pointers
When we encounter
1 | class Solution: |
- Runtime: 68 ms, faster than 83.75% of Python3 online submissions for Sort Array By Parity.
- Memory Usage: 13.8 MB, less than 5.69% of Python3 online submissions for Sort Array By Parity.
Use a custom comparator when sorting, to sort by parity.
1 | class Solution(object): |
- Time Complexity: O(NlogN), where
N is the length of
A
. - Space Complexity: O(N) for the sort, depending on
the built-in implementation of
sort
.
Approach 2: Two Pass
Write all the even elements first, then write all the odd elements.
1 | class Solution(object): |
- Time Complexity: O(N), where N is the
length of
A
. - Space Complexity: O(N) for the sort, depending on
the built-in implementation of
sort
.
Approach 3: In-Place
Intuition
If we want to do the sort in-place, we can use quicksort, a standard textbook algorithm.
Algorithm
We'll maintain two pointers i
and j
. The
loop invariant is everything below i
has parity
0
(ie. A[k] % 2 == 0
when
k < i
), and everything above j
has parity
1
.
Then, there are 4 cases for (A[i] % 2, A[j] % 2)
:
- If it is
(0, 1)
, then everything is correct:i++
andj--
. - If it is
(1, 0)
, we swap them so they are correct, then continue. - If it is
(0, 0)
, only thei
place is correct, so wei++
and continue. - If it is
(1, 1)
, only thej
place is correct, so wej--
and continue.
Throughout all 4 cases, the loop invariant is maintained, and
j-i
is getting smaller. So eventually we will be done with
the array sorted as desired.
1 | class Solution(object): |
- Time Complexity: O(N), where N is the
length of
A
. Each step of the while loop makesj-i
decrease by at least one. (Note that while quicksort is O(NlogN) normally, this is O(N)because we only need one pass to sort the elements.) - Space Complexity: O(1) in additional space complexity.