Back to articles
Task – Move All Negative Elements to the End (Maintain Order)

Task – Move All Negative Elements to the End (Maintain Order)

via Dev.toSanthoshi Mary A

Problem Statement Given an unsorted array arr[] containing both positive and negative integers, move all negative elements to the end of the array without changing the order of: Positive elements Negative elements Important: Perform the operation in-place (do not return a new array). Example 1 Input: arr[] = [1, -1, 3, 2, -7, -5, 11, 6] Output: [1, 3, 2, 11, 6, -1, -7, -5] Explanation: Positive numbers remain in same order → 1, 3, 2, 11, 6 Negative numbers remain in same order → -1, -7, -5 All negatives are moved to the end Example 2 Input: arr[] = [-5, 7, -3, -4, 9, 10, -1, 11] Output: [7, 9, 10, 11, -5, -3, -4, -1] Constraints 1 ≤ arr.size ≤ 10^6 -10^9 ≤ arr[i] ≤ 10^9 Expected Time Complexity: O(n) Expected Auxiliary Space: O(n) Approach – Stable Separation Using Extra Space Since we must: Maintain order of positives Maintain order of negatives We cannot simply swap randomly. Logical Steps Traverse the array once. Store positive elements in one list. Store negative elements in anothe

Continue reading on Dev.to

Opens in a new tab

Read Full Article
8 views

Related Articles