Skip to content

2149. Rearrange Array Elements by Sign 👍

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

    for (const int num : nums)
      (num > 0 ? pos : neg).push_back(num);

    for (int i = 0; i < pos.size(); ++i) {
      ans.push_back(pos[i]);
      ans.push_back(neg[i]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int[] rearrangeArray(int[] nums) {
    int[] ans = new int[nums.length];
    List<Integer> pos = new ArrayList<>();
    List<Integer> neg = new ArrayList<>();

    for (final int num : nums)
      (num > 0 ? pos : neg).add(num);

    for (int i = 0; i < pos.size(); ++i) {
      ans[i * 2] = pos.get(i);
      ans[i * 2 + 1] = neg.get(i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def rearrangeArray(self, nums: list[int]) -> list[int]:
    ans = []
    pos = []
    neg = []

    for num in nums:
      (pos if num > 0 else neg).append(num)

    for p, n in zip(pos, neg):
      ans += [p, n]

    return ans