Skip to main content
LeetCode 2161, Medium. Topics: Array, Two Pointers, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

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 p_i, p_j where p_i is the new position of the ith element and p_j is the new position of the jth element. If i < j and both elements are smaller (or larger) than pivot, then p_i < p_j.
Return nums* after the rearrangement.*

Examples

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026