Skip to content

2161. Partition Array According to Given Pivot 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  vector<int> pivotArray(vector<int>& nums, int pivot) {
    vector<int> ans;

    for (const int num : nums)
      if (num < pivot)
        ans.push_back(num);

    for (const int num : nums)
      if (num == pivot)
        ans.push_back(num);

    for (const int num : nums)
      if (num > pivot)
        ans.push_back(num);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int[] pivotArray(int[] nums, int pivot) {
    int[] ans = new int[nums.length];
    int i = 0; // ans' index

    for (final int num : nums)
      if (num < pivot)
        ans[i++] = num;

    for (final int num : nums)
      if (num == pivot)
        ans[i++] = num;

    for (final int num : nums)
      if (num > pivot)
        ans[i++] = num;

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def pivotArray(self, nums: list[int], pivot: int) -> list[int]:
    return ([num for num in nums if num < pivot] +
            [num for num in nums if num == pivot] +
            [num for num in nums if num > pivot])