Problem
Move all negative elements to end
You are given an unsorted array arr[] containing both positive and negative integers.
Your task is to move all negative elements to the end of the array without changing the order of positive and negative elements.
Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]Input: [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
Approach
The key requirement here is stability the relative order must remain unchanged.
A simple way to achieve this:
- Traverse the array and collect positive elements first
- Then collect negative elements
Place them back into the original array
Steps:Create a temporary list
Add all non-negative elements in order
Then add all negative elements in order
Copy back to the original array
This preserves order while achieving the required arrangement.
Complexity:
Time Complexity: O(n)
Space Complexity: O(n)
def rearrange(arr):
temp = []
for num in arr:
if num >= 0:
temp.append(num)
for num in arr:
if num < 0:
temp.append(num)
for i in range(len(arr)):
arr[i] = temp[i]
return arr
arr = [1, -1, 3, 2, -7, -5, 11, 6]
print(rearrange(arr))
Top comments (0)