2161. Partition Array According to Given Pivot
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Divide array into elements below pivot, equal to pivot, and above pivot, maintaining relative order.
Intuition
Divide array into elements below pivot, equal to pivot, and above pivot, maintaining relative order.
Algorithm
- 1Three passes: collect elements < pivot, then == pivot, then > pivot.
- 2Concatenate.
Common Pitfalls
- •Maintain relative order within each group. Three-pass approach is simplest.
2161.cs
C#
// Approach: Three-pass stable partition: less-than, equal, greater-than pivot.
// Time: O(n) Space: O(n)
public class Solution
{
public int[] PivotArray(int[] nums, int pivot)
{
int[] ans = new int[nums.Length];
int i = 0; // ans' index
foreach (int num in nums)
{
if (num < pivot)
ans[i++] = num;
}
foreach (int num in nums)
{
if (num == pivot)
ans[i++] = num;
}
foreach (int num in nums)
{
if (num > pivot)
ans[i++] = num;
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 19. Remove Nth Node From End of List(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)