Problem Statement
Given an unsorted array arr[] having both negative and positive integers. The task is to place all negative elements at the end of the array without changing the order of positive elements and negative elements.
Note: Don't return any array, just do in-place on the array.
Examples:
Input: arr[] = [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Explanation: By doing operations we separated the integers without changing the order.
Input: arr[] = [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
My Goal
For this problem, my goal was to:
Maintain the order of elements (stable arrangement)
Separate positive and negative numbers efficiently
Solve the problem in linear time
Keep the logic simple and readable
Solution
I used a two-list approach for simplicity and clarity.
Idea:
Traverse the array once
Store positive elements in one list
Store negative elements in another list
Combine both lists back into the original array
This ensures the order is preserved.
Solution Code (Python)
a = [1, -1, 3, 2, -7, -5, 11, 6]
p = []
n = []
for x in a:
if x >= 0:
p.append(x)
else:
n.append(x)
a = p + n
print(a)
Explanation
Loop through each element
Add positives to list p
Add negatives to list n
Combine both lists → positives first, negatives after
Order is preserved in both groups
Top comments (0)