Partition Array According to Given Pivot - Problem
You are given a 0-indexed integer array nums and an integer pivot. Your task is to rearrange the array according to specific partitioning rules while maintaining the relative order of elements within each partition.
Partitioning Rules:
- All elements less than
pivotmust appear first - All elements equal to
pivotmust appear in the middle - All elements greater than
pivotmust appear last - Crucially: The relative order within each group must be preserved
Example: Given nums = [9,12,5,10,14,3,10] and pivot = 10
Result: [9,5,3,10,10,12,14]
(Less than 10: [9,5,3], Equal to 10: [10,10], Greater than 10: [12,14])
This is like organizing a queue where you need to maintain the original arrival order within each priority group!
Input & Output
example_1.py โ Basic Partitioning
$
Input:
nums = [9,12,5,10,14,3,10], pivot = 10
โบ
Output:
[9,5,3,10,10,12,14]
๐ก Note:
Elements less than 10: [9,5,3] (maintaining original order), elements equal to 10: [10,10], elements greater than 10: [12,14] (maintaining original order)
example_2.py โ All Elements Equal
$
Input:
nums = [5,5,5,5], pivot = 5
โบ
Output:
[5,5,5,5]
๐ก Note:
All elements are equal to the pivot, so they all go in the middle section, maintaining their original relative order
example_3.py โ Already Partitioned
$
Input:
nums = [1,2,6,7], pivot = 5
โบ
Output:
[1,2,6,7]
๐ก Note:
Array is already correctly partitioned: [1,2] are less than 5, no elements equal to 5, [6,7] are greater than 5
Visualization
Tap to expand
Understanding the Visualization
1
Mixed Queue
All passengers are initially in one mixed line
2
Check Tickets
Look at each passenger's ticket and direct them to the appropriate lane
3
Separate Lanes
Economy, Business, and First Class passengers are now in separate lanes
4
Final Order
Combine the lanes: Economy โ Business โ First Class
Key Takeaway
๐ฏ Key Insight: Instead of complex in-place rearrangement, create three separate collections and merge them - this naturally preserves order and achieves optimal time complexity!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array to categorize elements, plus O(n) to combine arrays
โ Linear Growth
Space Complexity
O(n)
Need space for three separate arrays that together contain all n elements
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- -106 โค nums[i] โค 106
- pivot equals to one of the elements in nums
- The relative order within each partition must be maintained
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code