2161. Partition Array According to Given Pivot

Question

LeetCode Problem

You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:

Input: nums = [9,12,5,10,14,3,10], pivot = 10
Output: [9,5,3,10,10,12,14]
Explanation: The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.
The elements 12 and 14 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.

Example 2:

Input: nums = [-3,4,3,2], pivot = 2
Output: [-3,2,4,3]
Explanation: The element -3 is less than the pivot so it is on the left side of the array.
The elements 4 and 3 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.

Constraints:


Solutions

This question is similar to three way partition but it required to preserve the original relative order.

vector<int> pivotArray(vector<int> & nums, int pivot) {
	int m = static_cast<int>(nums.size());
	vector<int> sBuf;
	vector<int> lBuf;
	sBuf.reserve(m);
	lBuf.reserve(m);
	int pivotCounts = 0;
	for (int i : nums) {
		if (i < pivot) {
			sBuf.push_back(i);
		} else if (i > pivot) {
			lBuf.push_back(i);
		} else {
			pivotCounts++;
		}
	}
	int sLen = static_cast<int>(sBuf.size());
	int lLen = static_cast<int>(lBuf.size());
	for (int i = 0; i < sLen; ++i) {
		nums[i] = sBuf[i];
	}
	for (int i = 0; i < pivotCounts; ++i) {
		nums[sLen + i] = sBuf[i];
	} 
	for (int i = 0; i < lBuf; ++i) {
		nums[sLen + lLen + i] = lBuf[i];
	}
	return nums;
}