Back to articles
Segregate Positive and Negative Numbers in an Array Without Changing Order

Segregate Positive and Negative Numbers in an Array Without Changing Order

via Dev.toPadma Priya R

When working with arrays, a common problem is rearranging elements based on a condition while preserving their original order. In this post, we will solve the problem of moving all negative numbers in an array to the end without disturbing the order of positive and negative numbers . Problem Statement Given an array of integers, rearrange it so that all non-negative elements appear first, followed by negative elements. The relative order of elements must remain unchanged. Example 1: Input: [1, -1, 3, 2, -7, -5, 11, 6] Output: [1, 3, 2, 11, 6, -1, -7, -5] Example 2: Input: [-5, 7, -3, -4, 9, 10, -1, 11] Output: [7, 9, 10, 11, -5, -3, -4, -1] Constraints: 1 ≤ array size ≤ 10⁶ -10⁹ ≤ arr[i] ≤ 10⁹ Expected Time Complexity: O(n) Expected Auxiliary Space: O(n) Approach To solve this efficiently: Traverse the array once and store all non-negative elements in one temporary list. Store all negative elements in another temporary list. Merge both lists back into the original array. This approach

Continue reading on Dev.to

Opens in a new tab

Read Full Article
6 views

Related Articles