Partition Array According to Given Pivot - Problem

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 pivot appears before every element greater than pivot
Every element equal to pivot appears in between the elements less than and greater than pivot
The relative order of the elements less than pivot and the elements greater than pivot is maintained

More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. If i < j and both elements are smaller (or larger) than pivot, then pi < pj.

Return nums after the rearrangement.

Input & Output

Example 1 — Basic Partitioning
$ Input: nums = [9,12,5,10,14,3,10], pivot = 10
Output: [9,5,3,10,10,12,14]
💡 Note: Elements less than 10: [9,5,3] maintain relative order. Elements equal to 10: [10,10]. Elements greater than 10: [12,14] maintain relative order.
Example 2 — All Elements Same
$ Input: nums = [-3,-3,-3], pivot = -3
Output: [-3,-3,-3]
💡 Note: All elements equal to pivot, so array remains unchanged.
Example 3 — No Pivot Elements
$ Input: nums = [1,2,3,4], pivot = 10
Output: [1,2,3,4]
💡 Note: All elements are less than pivot 10, so they stay in original order. No equal or greater elements.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106
  • -106 ≤ pivot ≤ 106

Visualization

Tap to expand
Partition Array: nums=[9,12,5,10,14,3,10], pivot=10Input Array:91251014310Partitioned Array:95310101214< 10= 10> 10Result: [9,5,3,10,10,12,14] - Relative order preserved!
Understanding the Visualization
1
Input
Original array with mixed element values
2
Partition
Group elements: less than, equal to, greater than pivot
3
Output
Rearranged array maintaining relative order within groups
Key Takeaway
🎯 Key Insight: Separate elements into three groups while maintaining original relative order within each group
Asked in
Amazon 35 Microsoft 28 Google 22
38.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen