2 POINTERS › TWO POINTER ON ARRAYS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The requirement only distinguishes two groups: even values belong on the left, and odd values belong on the right. Because neither group has an order requirement, you do not need to sort the values or preserve their original positions. You only need to find values that are on the wrong side of the boundary and exchange them.
Use one pointer from the left and one from the right. The left pointer skips values that are already even, while the right pointer skips values that are already odd. When both pointers stop, the left side contains an odd value and the right side contains an even value, so swapping them fixes both positions at once. Once the pointers meet, no unexamined pair remains.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Each pointer moves only inward, and together they pass over at most n positions. A value is inspected a constant number of times, so no index can cause repeated scanning. |
| Space | O(1) | The algorithm stores only left, right, and temporary swap state besides the input array. This remains constant even for the worst arrangement of values; the returned array is the modified input and is excluded from the extra-space bound. |
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int left = 0;
int right = static_cast<int>(nums.size()) - 1;
while (left < right) {
if (nums[left] % 2 == 0) {
left++;
} else if (nums[right] % 2 == 1) {
right--;
} else {
swap(nums[left], nums[right]);
left++;
right--;
}
}
return nums;
}
};The order of the three branches is what makes the loop easy to trust. First discard a correct left value; otherwise discard a correct right value; only when both values are misplaced do you swap. After the swap, both positions are settled, so advancing both pointers is safe. The method changes nums directly, which gives constant extra space while still returning the required array.