
Move All Negative Elements to End of Array
Move All Negative Elements to End of Array Problem Statement Given an array of integers, move all negative elements to the end of the array while maintaining the order of positive elements. Examples Input arr = [1, -1, 3, 2, -7, -5, 11, 6] Output [1, 3, 2, 11, 6, -1, -7, -5] Input arr = [-5, 7, -3, -4, 9, 10] Output [7, 9, 10, -5, -3, -4] Approach 1 Using Extra Space Create a new array to store positive and negative elements separately. Steps 1 Traverse the array and store positive elements 2 Traverse again and store negative elements 3 Combine both Code ```python id="neg1" def moveNegatives(arr): result = [] for num in arr: if num >= 0: result.append(num) for num in arr: if num < 0: result.append(num) return result --- ## Approach 2 In Place Method Rearrange elements within the same array. --- ### Steps 1 Initialize index to track position 2 Traverse array 3 If element is positive swap it with current index 4 Increment index --- ### Code ```python id="neg2" def moveNegatives(arr): j =
Continue reading on Dev.to
Opens in a new tab



