Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 3, 2025 22:36
Show Gist options
  • Save Ifihan/8f137555498a4fe8c89c55a3800c894f to your computer and use it in GitHub Desktop.
Save Ifihan/8f137555498a4fe8c89c55a3800c894f to your computer and use it in GitHub Desktop.
Partition Array According to Given Pivot

Question

Approach

I iterate through nums and categorize elements into three lists: less_than, equal_to, and greater_than. This shows that all elements less than pivot appear first, followed by elements equal to pivot, then elements greater than pivot.

The relative order of elements in each category is preserved as required.

Implementation

class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        less_than = []
        equal_to = []
        greater_than = []
        
        for num in nums:
            if num < pivot:
                less_than.append(num)
            elif num == pivot:
                equal_to.append(num)
            else:
                greater_than.append(num)
        
        return less_than + equal_to + greater_than

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment