Python – Partition an Array into Three Parts Around a Given Value
This tutorial explains how to partition an array into three segments based on a given pivot value. The goal is to rearrange the array so that all elements less than the pivot come first, followed by elements equal to the pivot, and then elements greater than the pivot.
Problem Statement
Given an array arr and a pivot value p, partition the array into three parts such that:
- All elements less than pcome first.
- All elements equal to pcome in the middle.
- All elements greater than pcome last.
The partitioning does not require sorting within the three segments; it only groups the elements based on the pivot.
Sample Input and Output
Example 1:
Input:  arr = [4, 9, 4, 2, 7, 4, 10], pivot = 4
Output: [2, 4, 4, 4, 9, 7, 10]Example 2:
Input:  arr = [5, 3, 8, 5, 2, 5, 9], pivot = 5
Output: [3, 2, 5, 5, 5, 8, 9]Solution Approach
We can solve this problem efficiently using the Dutch National Flag algorithm (three-way partitioning) with the following steps:
- Initialize three pointers:
- low: Marks the boundary for elements less than the pivot.
- mid: Traverses the array.
- high: Marks the boundary for elements greater than the pivot.
 
- Traverse the array:
- If arr[mid]is less than the pivot, swap it witharr[low]and increment bothlowandmid.
- If arr[mid]equals the pivot, just incrementmid.
- If arr[mid]is greater than the pivot, swap it witharr[high]and decrementhigh(without incrementingmid).
 
- If 
- Continue this process until midexceedshigh.
Python Program
def partition_array(arr, pivot):
    low = 0           # Index for elements less than pivot
    mid = 0           # Index to traverse the array
    high = len(arr) - 1  # Index for elements greater than pivot
    while mid <= high:
        if arr[mid] < pivot:
            arr[low], arr[mid] = arr[mid], arr[low]
            low += 1
            mid += 1
        elif arr[mid] == pivot:
            mid += 1
        else:
            arr[mid], arr[high] = arr[high], arr[mid]
            high -= 1
    return arr
# Example usage:
arr1 = [4, 9, 4, 2, 7, 4, 10]
pivot1 = 4
print("Partitioned Array:", partition_array(arr1, pivot1))
arr2 = [5, 3, 8, 5, 2, 5, 9]
pivot2 = 5
print("Partitioned Array:", partition_array(arr2, pivot2))
Expected Output:
Partitioned Array: [2, 4, 4, 4, 7, 10, 9]
Partitioned Array: [3, 2, 5, 5, 5, 9, 8]Conclusion
This tutorial demonstrated how to partition an array into three parts around a given pivot using the Dutch National Flag algorithm. The approach partitions the array in-place with a time complexity of O(n) and uses O(1) extra space.
