Back to articles
Move Negative Elements to End While Maintaining Order

Move Negative Elements to End While Maintaining Order

via Dev.toSandhya Steffy M

Problem Statement: Given an unsorted array containing both positive and negative integers, rearrange the array such that all negative elements are moved to the end without changing the order of positive and negative elements. Example: Input: [1, -1, 3, 2, -7, -5, 11, 6] Output: [1, 3, 2, 11, 6, -1, -7, -5] Approach: We use two separate lists: One for positive elements One for negative elements Then we combine both lists and update the original array. Code: def rearrange(arr): positives = [] negatives = [] for num in arr: if num >= 0: positives.append(num) else: negatives.append(num) arr[:] = positives + negatives Explanation: This method preserves the order of elements. All positive numbers are stored first, followed by all negative numbers. Time Complexity: O(n), since we traverse the array once Space Complexity: O(n), since extra space is used

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles