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 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 i^th element and pj is the new position of the j^th element. If i < j and both elements are smaller (or larger) than pivot, then pi < pj.

Return nums after the rearrangement.

Example 1
Inputnums = [9,12,5,10,14,3,10], pivot = 10
Output[9,5,3,10,10,12,14]
The elements 9, 5, and 3 are less than the pivot, the elements 12 and 14 are greater than the pivot, and the relative orderings [9, 5, 3] and [12, 14] are maintained.
Example 2
Inputnums = [-3,4,3,2], pivot = 2
Output[-3,2,4,3]
The element -3 is less than the pivot, the elements 4 and 3 are greater than the pivot, and the relative orderings [-3] and [4, 3] are maintained.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^6 <= nums[i] <= 10^6
  • pivot equals to an element of nums.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate