Partition Array According to Given Pivot
Real-world version: Reorder Readings Around a ReferenceThe statement here is our own: the same inputs, outputs and technique.
A calibration run leaves you with a list of signed drift readings, one per probe, in the order the probes were sampled. One of the sampled values is singled out as the reference.
Rearrange the readings into a new list so that:
- every reading smaller than
referencecomes before every reading equal toreference; - every reading equal to
referencecomes before every reading larger thanreference; - two readings that are both smaller than
referencekeep the order they had in the input, and two readings that are both larger thanreferencealso keep the order they had in the input.
Return the rearranged list. Exactly one list satisfies all three rules, so the answer is unique.
Examples
Example 1
- Input
- readings = [8, 2, 7, 5, 1, 5], reference = 5
- Output
- [2, 1, 5, 5, 8, 7]
The readings smaller than `5` are `2` and `1`, read in that order, and they open the list. The two readings equal to `5` follow. The readings larger than `5` are `8` and `7`, read in that order, and they close the list.
Example 2
- Input
- readings = [-5, 2, -9, 2], reference = 2
- Output
- [-5, -9, 2, 2]
Nothing is larger than `2`, so the list is just the two smaller readings `-5` and `-9` in their sampled order, followed by the two readings equal to `2`.
Example 3
- Input
- readings = [0, -4, 6, -4, 6, 0, -4], reference = -4
- Output
- [-4, -4, -4, 0, 6, 6, 0]
No reading is smaller than `-4`, so the three readings equal to `-4` come first. The four larger readings keep their sampled order `0`, `6`, `6`, `0`.
Constraints
- 1 <= readings.length <= 10^5
- -10^6 <= readings[i] <= 10^6
- -10^6 <= reference <= 10^6
- reference is equal to at least one of the readings.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def reorder_readings(readings: list[int], reference: int) -> list[int]:public int[] reorderReadings(int[] readings, int reference)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Apply Operations to an ArrayReal-world version: Settle the Conveyor TraysEasy
- Rearrange Array Elements by SignReal-world version: Interleaving the Statement LinesMedium
- Candy CrushReal-world version: Settling the Colour Match BoardMedium
- Sum of GCD of Formed PairsReal-world version: Total Mesh Cycle of the Gear BinMedium