알고리즘/LeetCode

[LeetCode] 2161. Partition Array According to Given Pivot (Python)

Laewon Jeong 2025. 3. 3. 22:58

 

 

난이도: Medium

Problem Description


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

Return nums after the rearrangement.

 

Problem Example


Example 1:

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.
The elements 12 and 14 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.

Example 2:

Input: nums = [-3,4,3,2], pivot = 2
Output: [-3,2,4,3]
Explanation: 
The element -3 is less than the pivot so it is on the left side of the array.
The elements 4 and 3 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.

 

Constraints


  • 1 <= nums.length <= 105
  • -106 <= nums[i] <= 106
  • pivot equals to an element of nums.

 

✏️ Solution


class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        left = []
        mid = []
        right = []

        for num in nums:
            if num < pivot:
                left.append(num)
            elif num > pivot:
                right.append(num)
            else:
                mid.append(num)

        return left + mid + right

 

쉽게 해결할 수 있는 문제였다.

 

먼저, left, mid, right 리스트를 만들어주었다.

 

그리고 nums의 요소들을 pivot과 비교하여 pivot보다 작으면 left 리스트에 넣어주었고, pivot 보다 크면 right 리스트에 넣어주었다. 또한, pivot과 같은 값이면 mid 리스트에 넣어주었다.

 

마지막에는 세 리스트를 합쳐주어서 즉, left + mid + right하여 return하였고 정답을 맞을 수 있었다.

 

⚙️ Runtime & Memory


 

 


문제: 2161. Partition Array According to Given Pivot

 

깃허브: github

 

algorithmPractice/LeetCode/2265-partition-array-according-to-given-pivot at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com