Rearrange Array Elements by Sign (LeetCode 2149): Solution and Explanation
The array has as many positives as negatives. Rearrange it so signs alternate, starting with a positive, while each sign keeps its original order.
Intuition
The shape of the answer is fixed before you read a single value. Index 0 holds a positive, index 1 a negative, index 2 a positive, and so on. Think of the output as a row of seats marked + and - in alternation.
Because each sign must keep its input order, the first positive you meet takes the first + seat, the second positive takes the second + seat, and so on. The same goes for negatives on the - seats.
So you never need to search or swap. Keep a pointer to the next free + seat (starting at 0) and one to the next free - seat (starting at 1). Each time you seat a value, its pointer skips over the other sign's seat by moving 2.
Approach: Two write pointers that jump by 2
- Create an output array
resultof the same length asnums. - Set
pos = 0(next positive seat) andneg = 1(next negative seat). - Read
numsleft to right. A positivexgoes toresult[pos]andpos += 2. A negativexgoes toresult[neg]andneg += 2. - Return
result.
Step-by-step example
nums = [3,1,-2,-5,2,-4]
- Start with six empty seats,
pos = 0,neg = 1. - 3 is positive, so it sits at 0 and
posbecomes 2. 1 is positive, so it sits at 2 andposbecomes 4. - -2 is negative, so it sits at 1 and
negbecomes 3. -5 sits at 3 andnegbecomes 5. - 2 sits at 4 and
posbecomes 6. -4 sits at 5 andnegbecomes 7. - Every seat is filled, so return
[3,-2,1,-5,2,-4].
Code: Python, Java, C++
1class Solution:
2 def rearrangeArray(self, nums: List[int]) -> List[int]:
3 result = [0] * len(nums)
4 pos, neg = 0, 1
5 for x in nums:
6 if x > 0:
7 result[pos] = x
8 pos += 2
9 else:
10 result[neg] = x
11 neg += 2
12 return result1class Solution {
2 public int[] rearrangeArray(int[] nums) {
3 int[] result = new int[nums.length];
4 int pos = 0, neg = 1;
5 for (int x : nums) {
6 if (x > 0) {
7 result[pos] = x;
8 pos += 2;
9 } else {
10 result[neg] = x;
11 neg += 2;
12 }
13 }
14 return result;
15 }
16}1class Solution {
2public:
3 vector<int> rearrangeArray(vector<int>& nums) {
4 vector<int> result(nums.size());
5 int pos = 0, neg = 1;
6 for (int x : nums) {
7 if (x > 0) {
8 result[pos] = x;
9 pos += 2;
10 } else {
11 result[neg] = x;
12 neg += 2;
13 }
14 }
15 return result;
16 }
17};Time and space complexity
O(n)
Each value is read once and written once.
O(n)
The output array holds all n values. The two pointers take constant space.
Other approaches
Split, then interleave (time O(n), space O(n))
Copy positives into one list and negatives into another, then build the answer by taking one from each list in turn. It is easy to reason about but makes two extra arrays and two passes.
In-place rotation (time O(n^2), space O(1))
Walk the array and, when a value has the wrong sign for its index, find the next value of the right sign and rotate it into place. It avoids the extra array but costs O(n^2) time in the worst case, which is too slow for 2 * 10^5 values.
Common mistakes
- Moving the pointers by 1 instead of 2. Each pointer must skip the seat that belongs to the other sign.
- Starting with the negative seat at index 0. The problem requires the result to begin with a positive.
- Trying to swap in place with two read pointers. Swapping breaks the relative order of one of the signs.
Frequently asked questions
Why is an extra array allowed here?
The problem only asks you to return the rearranged array. Keeping relative order while rearranging in place is much more expensive, so the O(n) output array is the standard solution.
Can the pointers run past the end?
Each pointer is used exactly n / 2 times because there are n / 2 values of each sign. The last write lands on index n - 2 or n - 1, and the pointer then moves to n or n + 1 but is never used again.
What changes if the counts were unequal?
A common interview variant drops the equal-count rule: alternate while both signs remain, then append the leftover values in order. Fixed seats no longer work there, so you split the values by sign first and then merge them.