Partition Array According to Given Pivot

Medium Topics Company Tags

Rearrange nums into three consecutive groups: values less than pivot, values equal to pivot, and values greater than pivot. Within the less-than group and within the greater-than group, preserve the original order of the values. Return the resulting array. The pivot is guaranteed to occur in nums.

Example 1:

Input: nums = [3,1,2,1,4]
pivot = 2

Output: [1,1,2,3,4]

Explanation: The smaller values stay in order as [1,1], followed by pivot value 2, then the larger values in their original order [3,4].

Example 2:

Input: nums = [-2,0,-3,-2,1]
pivot = -2

Output: [-3,-2,-2,0,1]

Explanation: The smaller group is [-3], the equal group is [-2,-2], and the larger group is [0,1]. Concatenating them gives [-3,-2,-2,0,1].

Example 3:

Input: nums = [5,5]
pivot = 5

Output: [5,5]

Explanation: Every value equals the pivot, so the array stays [5,5].

Constraints:

  • 1 <= nums.length <= 100000
  • -1000000 <= nums[i] <= 1000000
  • pivot occurs in nums.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.