Rearrange an array so that elements smaller than a pivot come first, followed by elements equal to the pivot, then elements greater than the pivot, while preserving relative order within each group.
Given an integer array nums and an integer pivot, reorder the array into three consecutive groups:
- all values less than
pivot - all values equal to
pivot - all values greater than
pivot
The relative order of elements within each group should remain the same as in the original array.
Return the rearranged array.
Input Format
- An integer array
nums - An integer
pivot
Output Format
- Return a new array containing the elements of
numspartitioned aroundpivotin stable order.
Constraints
1 <= nums.lengthis assumed to be within typical interview limits- Elements may be negative, zero, or positive
- The partition must preserve the original relative order inside each of the three groups
Example 1
Input
nums = [9,12,5,10,14,3,10], pivot = 10
Output
[9,5,3,10,10,12,14]
Explanation
Numbers less than 10 appear first in original order: [9,5,3]. Then the values equal to 10: [10,10]. Finally, the values greater than 10: [12,14].
Example 2
Input
nums = [-3,4,2,0,4], pivot = 4
Output
[-3,2,0,4,4]
Explanation
The elements smaller than 4 are kept first, followed by all 4s, then values greater than 4. The order inside each group stays unchanged.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.