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 According to Given Pivot INPUT nums array: 9 12 5 10 14 3 10 pivot = 10 Categories: Less than 10 Equal to 10 Greater than 10 nums = [9,12,5,10,14,3,10] pivot = 10 ALGORITHM STEPS 1 Count Elements Count less, equal, greater less=3, equal=2, greater=2 2 Create 3 Sections Prepare result array slots <10 =10 >10 3 Place in Order Scan and place elements 9 5 3 10 10 12 14 4 Maintain Order Original relative order preserved in each section Time: O(n) - single pass Space: O(n) - result array FINAL RESULT Partitioned Array: 9 5 3 10 10 12 14 < pivot = pivot > pivot Verification: [OK] 9,5,3 all less than 10 [OK] 10,10 equal to pivot [OK] 12,14 greater than 10 [OK] Relative order preserved [9,5,3,10,10,12,14] Partition Complete! All conditions satisfied Key Insight: The in-place counting approach uses THREE pointers to track positions for each category (less, equal, greater). By scanning left-to-right and placing elements in order, we naturally preserve the relative ordering within each partition. This achieves O(n) time with a single pass through the array. TutorialsPoint - Partition Array According to Given Pivot | In-Place with Counting Approach
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