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 required result has three consecutive regions: values below pivot, values equal to pivot, and values above pivot. The important extra condition is that each region must keep the order its values had in nums. That means a value cannot simply be moved into the correct region by swapping, because the swap may make two values in the same region change places.
Scan nums from left to right and give every value to exactly one group. Appending to a group preserves the order automatically: the first less-than value reaches less before the second one, and the same is true for equal and greater. Once the scan ends, placing the three groups after one another satisfies both the value restrictions and the stability requirement.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The scan examines each input element once. The two insert operations copy the equal and greater groups once, while the less elements are already in the returned vector, so the total number of element operations is at most a constant multiple of n. |
| Space | O(n) | The three temporary groups together hold every input element, so their total capacity is linear. The returned array is required output and is excluded; in the worst shape, all n values can belong to one group, which still gives O(n) extra space. |
#include <vector>
using namespace std;
class Solution {
public:
vector<int> pivotArray(vector<int>& nums, int pivot) {
vector<int> less, equal, greater;
for (int x : nums) {
if (x < pivot) {
less.push_back(x);
} else if (x == pivot) {
equal.push_back(x);
} else {
greater.push_back(x);
}
}
less.insert(less.end(), equal.begin(), equal.end());
less.insert(less.end(), greater.begin(), greater.end());
return less;
}
};The range-based loop is the stability mechanism: values enter each vector in exactly the order they appear in nums. The insert calls deliberately target less, turning it into the final output in two stages. Since the output is returned by value, the temporary group storage is separate from the input and the caller receives the completed arrangement.