Rearrange Array Elements by Sign

Pattern: Next permutation and rearrangement

medium

Positives go to even indexes and negatives to odd ones, each keeping its order. Two write indexes into a new array, each moving by 2, do it in one pass.

The problem

You are given an array of even length with equally many positive and negative numbers (no zeros). Rearrange it so that signs alternate, starting with a positive, and the positives keep their original order, and so do the negatives. For example, [3, 1, -2, -5, 2, -4] gives [3, -2, 1, -5, 2, -4].

The function name rearrangeArray matches LeetCode. Use the link above for the exact statement and limits. Return a new array.

Think first

  • In the answer, which indexes hold positives and which hold negatives?
  • The k-th positive in the input, where does it end up?
  • Can you place each value the moment you see it?

Hints

    Brute force, and why it fails

    Copy the positives into one list and the negatives into another, then interleave them: O(n) time with two extra lists. The two write indexes do the same with one output array and no separate lists.

    The key insight

    The answer's shape is fixed: even slots for one sign, odd slots for the other. Order within each sign is kept by filling each kind of slot from left to right as values arrive.

    Dry run

    00 
    01 
    02 
    03 
    04 
    05 
    pos0
    neg1

    nums = [3, 1, -2, -5, 2, -4]. Positives will fill indexes 0, 2, 4 and negatives 1, 3, 5.

    Step 1 of 4

    The plan

    out = array of n zeros
    pos = 0, neg = 1
    for each v in nums:
        if v > 0: out[pos] = v; pos = pos + 2
        else:     out[neg] = v; neg = neg + 2
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One pass, and the output array is the only extra memory.

    Edge cases

    • Two values, [-1, 1]: the answer is [1, -1].
    • Already alternating: the output equals the input.
    • All positives first, as in [5, 6, 7, -1, -2, -3]: they spread out to [5, -1, 6, -2, 7, -3].
    I've built my logic, show the code

    Java

    class Solution {
        public int[] rearrangeArray(int[] nums) {
            int[] out = new int[nums.length];
            int pos = 0, neg = 1;                 // next even slot for a positive, next odd slot for a negative
            for (int v : nums) {
                if (v > 0) { out[pos] = v; pos += 2; }
                else { out[neg] = v; neg += 2; }
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> rearrangeArray(vector<int>& nums) {
            vector<int> out(nums.size());
            int pos = 0, neg = 1;                 // next even slot for a positive, next odd slot for a negative
            for (int v : nums) {
                if (v > 0) { out[pos] = v; pos += 2; }
                else { out[neg] = v; neg += 2; }
            }
            return out;
        }
    };

    Python

    class Solution:
        def rearrangeArray(self, nums: list[int]) -> list[int]:
            out = [0] * len(nums)
            pos, neg = 0, 1                       # next even slot for a positive, next odd slot for a negative
            for v in nums:
                if v > 0:
                    out[pos] = v
                    pos += 2
                else:
                    out[neg] = v
                    neg += 2
            return out

    Common mistakes

    • Swapping in place, which breaks the original order of one of the signs.
    • Starting negatives at index 0, which gives an answer that begins with a negative.
    • Moving the write index by 1 instead of 2.

    Similar problems