Move all negative elements to one side
Problem
Rearrange the array so that all negative numbers come before all non-negative numbers. The relative order within each group does not need to be preserved. Use O(1) extra space.
Example 1
Input: [-12, 11, -13, -5, 6, -7, 5, -3, -6] Output: [-12, -13, -5, -7, -3, -6, 11, 6, 5]
Any order is fine as long as every negative comes first.
Also asked as: Move all the negative elements to one side of the array
Test cases
No automated tests for this problem yet. Use the examples above to check your output.
This problem has no automated tests. Run executes your code and shows what it logs.
View solutionHide solution1 approach
1. Two pointers (order not preserved)
Time O(n)Space O(1)
Partition like quicksort: `j` tracks the boundary; swap each negative to the front.
function moveNegatives(a) { let j = 0; for (let i = 0; i < a.length; i++) { if (a[i] < 0) { [a[i], a[j]] = [a[j], a[i]]; j++; } } return a;}Preserving relative order in O(1) space needs the rotation trick and is O(n²); with O(n) space it is a stable two-bucket pass.