Leetcode 905. Sort Array By Parity
Given an array of integers 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.
Before we dive into the solution, let’s clarify the following questions:
nums
will always contain integers?
We can solve this problem efficiently using a two-pointer approach:
start
) at the beginning of the array and another (end
) at the end of the array.start
pointer if the current element is even.end
pointer if the current element is odd.start
points to an odd number and end
points to an even number, swap the elements.start
pointer is greater than or equal to the end
pointer.This approach ensures that all even numbers are moved to the front and odd numbers to the back with minimal swaps.
Here is the implementation in C++:
#include <vector>
std::vector<int> sortArrayByParity(std::vector<int>& nums) {
int start = 0;
int end = nums.size() - 1;
while (start < end) {
if (nums[start] % 2 == 0) {
++start;
} else if (nums[end] % 2 == 1) {
--end;
} else {
std::swap(nums[start], nums[end]);
++start;
--end;
}
}
return nums;
}
start
at the beginning (0
) and end
at the last element (nums.size()-1
).nums[start]
is even (nums[start] % 2 == 0
), move the start
pointer to the right.nums[end]
is odd (nums[end] % 2 == 1
), move the end
pointer to the left.nums[start]
is odd and nums[end]
is even, swap the two values and adjust both pointers (start
right, end
left).start
is no longer less than end
.This method is optimal in terms of both time and space, making it a suitable solution for the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?