2161. Partition Array According to Given Pivot #1385
-
Topics: You are given a 0-indexed integer array
Return Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to rearrange an array such that elements less than a given pivot appear first, followed by elements equal to the pivot, and finally elements greater than the pivot. The relative order of elements within the less than and greater than groups must be maintained. Approach
This approach ensures that the relative order of elements within the less than and greater than groups is preserved, while elements equal to the pivot are placed in the middle. Let's implement this solution in PHP: 2161. Partition Array According to Given Pivot <?php
/**
* @param Integer[] $nums
* @param Integer $pivot
* @return Integer[]
*/
function pivotArray($nums, $pivot) {
$less = [];
$equal = [];
$greater = [];
// Categorize numbers
foreach ($nums as $num) {
if ($num < $pivot) {
array_push($less, $num);
} elseif ($num == $pivot) {
array_push($equal, $num);
} else {
array_push($greater, $num);
}
}
// Merge the partitions while maintaining relative order
return array_merge($less, $equal, $greater);
}
// Test cases
print_r(pivotArray([9,12,5,10,14,3,10], 10));
print_r(pivotArray([-3,4,3,2], 2));
?> Explanation:
This approach efficiently rearranges the array in O(n) time and O(n) space, which is optimal for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to rearrange an array such that elements less than a given pivot appear first, followed by elements equal to the pivot, and finally elements greater than the pivot. The relative order of elements within the less than and greater than groups must be maintained.
Approach
Separate Elements into Groups: We can divide the elements into three groups:
Maintain Relative Order: By iterating through the array and appending elements to their respective groups, we maintain their relative order as they appear in the original array.
Concatenate Groups: Finally, concatenate the three groups (less …