Rearrange the array in alternating positive and negative items with O(1) extra space

Pattern: Next permutation and rearrangement

medium

Alternate negatives and non-negatives in place, keeping the original order, with leftovers at the end. Remember the first slot with the wrong sign, and when a value of the needed sign arrives, rotate it back into that slot.

The problem

You are given an array with positive and negative numbers in any mix. Rearrange it in place, with O(1) extra memory, so that negatives and non-negatives alternate, starting with a negative. Each group keeps its original order. When one group runs out, the rest of the other group stays at the end in order. For example, [1, 2, 3, -4, -1, 4] becomes [-4, 1, -1, 2, 3, 4].

The link above is a GeeksforGeeks article. The function name rearrange is this guide's own, and this guide counts 0 as non-negative. The O(1) memory rule is the point: with a spare array the problem is easy.

Think first

  • Which sign does each index want: even indexes, odd indexes?
  • If an index holds the wrong sign, where is the value that should go there?
  • How can you move that value back without breaking the order of the values in between?

Hints

    Brute force, and why it fails

    With an extra array: copy negatives and non-negatives into two lists and interleave them, in O(n) time and O(n) memory. The rule says O(1) memory, and plain swapping breaks the order. Rotating keeps the order with O(1) memory, at up to O(n²) time.

    The key insight

    Between the wrong slot and the value it needs, every value has the same sign as the wrong slot's value. Shifting them all one step right keeps their order and keeps them alternating with what comes next.

    Dry run

    10wrong, i
    21 
    32 
    -43 
    -14 
    45 

    arr = [1, 2, 3, -4, -1, 4]. Even indexes want a negative and odd ones a non-negative. Index 0 holds 1, which is wrong.

    Step 1 of 4

    The plan

    wrong = -1
    for i from 0 to n - 1:
        if wrong >= 0:
            if sign of arr[i] differs from sign of arr[wrong]:
                rotate arr[wrong..i] one step right
                if i - wrong >= 2: wrong = wrong + 2
                else: wrong = -1
        else if (i is even and arr[i] >= 0) or (i is odd and arr[i] < 0):
            wrong = i
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    Each rotation can shift up to n values, and there can be up to about n / 2 rotations. Only wrong, i and one temporary value are stored.

    Edge cases

    • All non-negative, or all negative: nothing moves.
    • Zeros count as non-negative, as in [0, -1, 0, -2], which becomes [-1, 0, -2, 0].
    • More negatives than non-negatives: the extra negatives stay at the end in order.
    I've built my logic, show the code

    Java

    class Solution {
        public void rearrange(int[] arr) {
            int n = arr.length;
            int wrong = -1;                       // the first index holding the wrong sign, or -1
            for (int i = 0; i < n; i++) {
                if (wrong >= 0) {
                    // arr[i] has the sign that index 'wrong' needs: rotate it back to 'wrong'
                    if ((arr[i] >= 0) != (arr[wrong] >= 0)) {
                        rotateRight(arr, wrong, i);
                        if (i - wrong >= 2) wrong += 2;   // the next slot of the same wrong kind
                        else wrong = -1;
                    }
                } else {
                    boolean needNeg = i % 2 == 0;         // even slots want a negative, odd slots a non-negative
                    if ((arr[i] < 0) != needNeg) wrong = i;
                }
            }
        }
    
        private void rotateRight(int[] a, int from, int to) {
            int t = a[to];                        // a[from..to] moves one step right, a[to] goes to a[from]
            for (int k = to; k > from; k--) a[k] = a[k - 1];
            a[from] = t;
        }
    }

    C++

    class Solution {
    public:
        void rearrange(vector<int>& arr) {
            int n = static_cast<int>(arr.size());
            int wrong = -1;                       // the first index holding the wrong sign, or -1
            for (int i = 0; i < n; i++) {
                if (wrong >= 0) {
                    // arr[i] has the sign that index 'wrong' needs: rotate it back to 'wrong'
                    if ((arr[i] >= 0) != (arr[wrong] >= 0)) {
                        rotate(arr.begin() + wrong, arr.begin() + i, arr.begin() + i + 1);
                        if (i - wrong >= 2) wrong += 2;   // the next slot of the same wrong kind
                        else wrong = -1;
                    }
                } else {
                    bool needNeg = i % 2 == 0;            // even slots want a negative, odd slots a non-negative
                    if ((arr[i] < 0) != needNeg) wrong = i;
                }
            }
        }
    };

    Python

    class Solution:
        def rearrange(self, arr: list[int]) -> None:
            wrong = -1                            # the first index holding the wrong sign, or -1
            for i in range(len(arr)):
                if wrong >= 0:
                    # arr[i] has the sign that index 'wrong' needs: rotate it back to 'wrong'
                    if (arr[i] >= 0) != (arr[wrong] >= 0):
                        v = arr[i]
                        for k in range(i, wrong, -1):     # shift arr[wrong..i-1] one step right
                            arr[k] = arr[k - 1]
                        arr[wrong] = v
                        wrong = wrong + 2 if i - wrong >= 2 else -1
                else:
                    need_neg = i % 2 == 0                 # even slots want a negative, odd slots a non-negative
                    if (arr[i] < 0) != need_neg:
                        wrong = i

    Common mistakes

    • Swapping arr[wrong] with arr[i], which jumps one value over the others and breaks their order.
    • Clearing wrong after every rotation. When the stretch was at least 3 long, wrong + 2 still holds the wrong sign.
    • Treating 0 as negative in one check and non-negative in another.

    Similar problems