Partition Array According to Given Pivot
Problem Statement
You are given an integer array nums and a number pivot (which appears in nums at least once).
Rearrange the numbers so that:
- every number smaller than
pivotcomes first, - then every number equal to
pivot, - then every number bigger than
pivot.
The catch: inside the smaller group, the numbers must stay in the same order as in nums. The same goes for the bigger group. Return the rearranged array.
An integer array nums and an integer pivot that is one of the values in nums.
A new array: the smaller numbers in their original order, then all the pivots, then the bigger numbers in their original order.
Smaller than 10: 9, 5, 3 (in that order in nums). Equal: 10, 10. Bigger: 12, 14 (12 comes before 14 in nums). [9, 5, 3, 10, 10, 14, 12] would be wrong, because 14 jumped ahead of 12.
Smaller: -3. Equal: 2. Bigger: 4, 3 β kept in their original order, even though 4 > 3.
- β’ 1 β€ nums.length β€ 10^5
- β’ β10^6 β€ nums[i] β€ 10^6
- β’ pivot equals at least one element of nums
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Give each number a group (0/1/2) and stable-sort by it
One pass drops each number into its group's list; glue the lists
Front reader writes smaller numbers at lo++, back reader writes bigger numbers at hi--
Give each number a group: 0 if it is smaller than pivot, 1 if equal, 2 if bigger. Sort by the group with stable_sort, which never changes the order of numbers that compare equal. So each group keeps its original order.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.