Partition Array According to Given Pivot

Given an integer array nums and an integer pivot, rearrange nums so that every element less than pivot comes before every element greater than pivot, and every element equal to pivot sits between them. The relative order of the elements less than pivot, and of the elements greater than pivot, must stay the same as in nums. Return the rearranged array.

30:00

Partition Array According to Given Pivot
medium
Free written solution
Topics
Companies

Given an integer array nums and an integer pivot, rearrange nums so that every element less than pivot comes before every element greater than pivot, and every element equal to pivot sits between them. The relative order of the elements less than pivot, and of the elements greater than pivot, must stay the same as in nums. Return the rearranged array.

Example 1:
Input: {"nums":[9,12,5,10,14,3,10],"pivot":10}
Output: [9,5,3,10,10,12,14]
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • −106≤nums[i]≤106-10^6 \leq \text{nums}[i] \leq 10^6

  • pivot equals an element of nums.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[9,12,5,10,14,3,10],"pivot":10}

Fill the answer with the pivot 10. 3 values will land on the left, 2 on the right, and the 2 slots left in the middle already hold the right value.

■ < 10
■ = 10
■ > 10

nums (read from both ends)

9
12
5
10
14
3
10

result (starts as all 10)

10
10
10
10
10
10
10
0
1
2
3
4
5
6

smaller placed

0

larger placed

0

Variables
VariableValue
pivot10
i-1
lo0
hi6
DepthFunction Call
Stack empty
0/11