LC2161. Partition Array According to Given Pivot
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:
- Every element less than
pivotappears before every element greater thanpivot. - Every element equal to
pivotappears in between the elements less than and greater thanpivot. - The relative order of the elements less than
pivotand the elements greater thanpivotis maintained.- More formally, consider every
pi,pjwherepiis the new position of theiᵗʰelement andpjis the new position of thejᵗʰelement. Ifi < jand both elements are smaller (or larger) thanpivot, thenpi < pj.
- More formally, consider every
Return nums after the rearrangement.
Constraints:
1 <= nums.length <= 105-106 <= nums[i] <= 106pivotequals to an element ofnums.
Approach 1: Dynamic Slices
func pivotArray(nums []int, pivot int) []int {
left := make([]int, 0, len(nums))
mid := make([]int, 0, len(nums))
right := make([]int, 0, len(nums))
for _, num := range nums {
switch {
case num < pivot:
left = append(left, num)
case num == pivot:
mid = append(mid, num)
default:
right = append(right, num)
}
}
return slices.Concat(left, mid, right)
}Intuition
The problem requires rearranging an array such that:
- Elements smaller than the pivot appear first.
- Elements equal to the pivot appear next.
- Elements greater than the pivot appear last.
To achieve this, we can iterate through the array and classify each element into one of three separate lists (left, mid, and right). Finally, we concatenate these lists to obtain the desired order while maintaining relative positioning.
Algorithm
- Initialize three slices:
leftfor elements less thanpivotmidfor elements equal topivotrightfor elements greater thanpivot
- Iterate through
numsand append each element to its respective slice based on comparison withpivot. - Concatenate and return the three slices.
Complexity Analysis
-
Time Complexity: O(N)
- We iterate through
numsonce, processing each element in O(1) time. - The final concatenation using
slices.Concat()is O(N). - Overall, the algorithm runs in O(N) time.
- We iterate through
-
Space Complexity: O(N)
- Three separate slices (
left,mid,right) store elements temporarily, requiring O(N) additional space. - The final result uses the same space, making the overall auxiliary space complexity O(N).
- Three separate slices (
Wrap up
If you found this guide helpful, consider subscribing to my newsletter on jyotirmoy.dev/blogs , You can also follow me on Twitter jyotirmoydotdev for updates and more content.

