Skip to main content
Back to problems
#2149
Medium Algorithms

Rearrange array elements by sign

Array Two Pointers Simulation
84.5% acceptance
Feb 25, 2026
4136
231
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should return the array of nums such that the array follows the given conditions: Every consecutive pair of integers have opposite signs. For all integers with the same sign, the order in which they were present in nums is preserved. The rearranged array begins with a positive integer. Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn rearrange_array(nums: Vec<i32>) -> Vec<i32> {
    let pos: Vec<i32> = nums.iter().filter(|&&x| x > 0).cloned().collect();
    let neg: Vec<i32> = nums.iter().filter(|&&x| x < 0).cloned().collect();
    let mut result = Vec::with_capacity(nums.len());
    for (p, n) in pos.iter().zip(neg.iter()) {
      result.push(*p);
      result.push(*n);
    }
    result
  }
}