How do you rearrange positive and negative integers alternately while preserving relative order? | A1LabDavid to DSAEnglish • 16 hours ago

How do you rearrange positive and negative integers alternately while preserving relative order?

message-square
0
1
How do you rearrange positive and negative integers alternately while preserving relative order?
How do you rearrange positive and negative integers alternately while preserving relative order? | A1LabDavid to DSAEnglish • 16 hours ago

Alternating Positive and Negative Integers While Preserving Relative Order

Rearranging positive and negative integers alternately (pos, neg, pos, neg, ... or starting with neg) while preserving relative order (stability) has two distinct cases depending on constraints:

  1. Equal Counts of Positives and Negatives (n / 2 each): Two-pointer placement into an output array gives $O(n)$ time and $O(n)$ space while keeping relative order exact.
  2. Unequal Counts (or Strict In-Place $O(1)$ Space): When counts differ or extra space is forbidden, placing elements in-place while preserving relative order requires shifting/rotation (leading to $O(n^2)$ worst-case time in standard rotation approaches). Below, we cover the standard order-preserving two-pointer solution (for equal counts) plus order-preserving leftover appending (when counts are unequal), and note the $O(1)$-space trade-off clearly.

How Order-Preserving Alternating Placement Works

Assume positives are x > 0 and negatives are x < 0 (zeros, if present, can be treated as non-negative or handled per problem rules; here x >= 0 is treated as positive/non-negative and x < 0 as negative).

  • Even indices (0, 2, 4, ...): Place the next positive element in left-to-right scan order.
  • Odd indices (1, 3, 5, ...): Place the next negative element in left-to-right scan order.

Because we scan nums once from index 0 to n - 1 and write positives to pos_idx += 2 and negatives to neg_idx += 2, relative order within positives and within negatives is preserved automatically.

If counts are unequal and all elements must still appear in the result without dropping extras:

  • Alternate while both positives and negatives queues/lists have elements.
  • Append any remaining surplus elements at the end in their original relative order.

(Note: Pure in-place rearrangement with $O(1)$ auxiliary space that strictly preserves relative order—such as rotating out-of-place blocks—takes $O(n^2)$ time in the worst case because shifting elements across blocks can take linear work per element.)


Quick Trace: nums = [3, -2, -5, 1, -4, 6]

  • Positives in order: [3, 1, 6] $\rightarrow$ placed at indices 0, 2, 4.
  • Negatives in order: [-2, -5, -4] $\rightarrow$ placed at indices 1, 3, 5.
  • Output: [3, -2, 1, -5, 6, -4].

Code Implementation

Python Solution (Equal Counts + Unequal-Count Safe Fallback)

def rearrange_alternating_preserve_order(nums: list[int]) -> list[int]:
    positives = [x for x in nums if x >= 0]
    negatives = [x for x in nums if x < 0]

    result: list[int] = []
    p_idx = 0
    n_idx = 0

    # Alternate starting with positive at even slots, negative at odd slots
    while p_idx < len(positives) and n_idx < len(negatives):
        result.append(positives[p_idx])
        p_idx += 1
        result.append(negatives[n_idx])
        n_idx += 1

    # Append remaining elements while preserving relative order (if counts differ)
    while p_idx < len(positives):
        result.append(positives[p_idx])
        p_idx += 1

    while n_idx < len(negatives):
        result.append(negatives[n_idx])
        n_idx += 1

    return result

C++ Solution (Direct Two-Pointer Index Placement for Equal Counts)

#include <vector>

std::vector<int> rearrangeArrayEqualCounts(const std::vector<int>& nums) {
    int n = static_cast<int>(nums.size());
    std::vector<int> ans(n, 0);

    int pos_idx = 0; // Even indices for positive/non-negative values
    int neg_idx = 1; // Odd indices for negative values

    for (int x : nums) {
        if (x >= 0) {
            ans[pos_idx] = x;
            pos_idx += 2;
        } else {
            ans[neg_idx] = x;
            neg_idx += 2;
        }
    }

    return ans;
}

Complexity

Approach Time Complexity Auxiliary Space Preserves Relative Order?
Two-Pointer / Partitioned Pass $O(n)$ $O(n)$ Yes
In-Place Block Shift / Rotation $O(n^2)$ worst-case $O(1)$ Yes