Partition Array According to Given Pivot — LeetCode 2161 Python Solution

MediumArrayTwo PointersSimulation
Problem
#2161
Reading time
2 min

The 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.

Example

Input
nums = [9,12,5,10,14,3,10], pivot = 10
Output
[9,5,3,10,10,12,14]
Explanation
The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.

Python solution

Python
class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        a, b, c = [], [], []
        for x in nums:
            if x < pivot:
                a.append(x)
            elif x == pivot:
                b.append(x)
            else:
                c.append(x)
        return a + b + c

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2161. Partition Array According to Given Pivot is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2161. Partition Array According to Given Pivot?
LeetCode 2161. Partition Array According to Given Pivot is rated Medium on LeetCode.
What is the time complexity of LeetCode 2161. Partition Array According to Given Pivot?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 2161. Partition Array According to Given Pivot?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2161. Partition Array According to Given Pivot cover?
LeetCode 2161. Partition Array According to Given Pivot is tagged Array, Two Pointers and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview