Move all the negative elements to one side of the array
Pattern: Two pointers
Put every negative number before every non-negative one in place, by swapping each negative into the next slot of a growing front section.
The problem
You are given an array of whole numbers. Rearrange it in place so that every negative number comes before every
non-negative number (0 counts as non-negative). The order inside each group does not matter. Return the array. For
example, [-12, 11, -13, -5, 6, -7] can become [-12, -13, -5, -7, 6, 11].
This problem is from Love Babbar's 450 sheet. Its main link points to GeeksforGeeks, which this site has not been able to
check automatically. The function name rearrange is this guide's own. Because several answers are correct, the tests
check the rule (negatives first, same values) rather than one exact order.
Think first
- How is this like moving zeros to the end?
- If a front section holds only negatives, what do you do when you meet a new negative?
- Does this need the order of the values to stay the same?
Hints
Brute force, and why it fails
Sort the array: O(n log n), and it does much more than asked. Copying negatives and then non-negatives into a new array is O(n) but uses extra memory. The swap pass is O(n) in place.
The key insight
This is the partition step of quick sort with 0 as the dividing line: one pass and a boundary index split the array without any extra memory.
Dry run
arr = [-12, 11, -13, -5, 6, -7]. next marks where the next negative goes. It starts at 0.
The plan
next = 0
for i from 0 to n - 1:
if arr[i] < 0:
swap arr[i] and arr[next]
next = next + 1
return arr
Complexity
- Time
O(n)- Space
O(1)
One pass, at most one swap per element.
Edge cases
- No negatives, or only negatives: nothing needs to move.
- Zeros stay with the non-negative values.
- This method may change the order within the non-negative side. If the order must be kept, the problem becomes harder.
I've built my logic, show the code
Java
class Solution {
public int[] rearrange(int[] arr) {
int next = 0; // where the next negative value goes
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
int temp = arr[i];
arr[i] = arr[next];
arr[next] = temp;
next++;
}
}
return arr;
}
}C++
class Solution {
public:
vector<int> rearrange(vector<int>& arr) {
int next = 0; // where the next negative value goes
for (int i = 0; i < static_cast<int>(arr.size()); i++) {
if (arr[i] < 0) {
swap(arr[i], arr[next]);
next++;
}
}
return arr;
}
};Python
class Solution:
def rearrange(self, arr):
nxt = 0 # where the next negative value goes
for i in range(len(arr)):
if arr[i] < 0:
arr[i], arr[nxt] = arr[nxt], arr[i]
nxt += 1
return arrCommon mistakes
- Treating 0 as negative.
- Swapping with the last index and moving it inwards without re-checking the swapped-in value.
- Assuming the order inside each side is preserved; with swaps it is not.